GNU Linux-libre 5.10.153-gnu1
[releases.git] / drivers / md / raid5.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * raid5.c : Multiple Devices driver for Linux
4  *         Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
5  *         Copyright (C) 1999, 2000 Ingo Molnar
6  *         Copyright (C) 2002, 2003 H. Peter Anvin
7  *
8  * RAID-4/5/6 management functions.
9  * Thanks to Penguin Computing for making the RAID-6 development possible
10  * by donating a test server!
11  */
12
13 /*
14  * BITMAP UNPLUGGING:
15  *
16  * The sequencing for updating the bitmap reliably is a little
17  * subtle (and I got it wrong the first time) so it deserves some
18  * explanation.
19  *
20  * We group bitmap updates into batches.  Each batch has a number.
21  * We may write out several batches at once, but that isn't very important.
22  * conf->seq_write is the number of the last batch successfully written.
23  * conf->seq_flush is the number of the last batch that was closed to
24  *    new additions.
25  * When we discover that we will need to write to any block in a stripe
26  * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
27  * the number of the batch it will be in. This is seq_flush+1.
28  * When we are ready to do a write, if that batch hasn't been written yet,
29  *   we plug the array and queue the stripe for later.
30  * When an unplug happens, we increment bm_flush, thus closing the current
31  *   batch.
32  * When we notice that bm_flush > bm_write, we write out all pending updates
33  * to the bitmap, and advance bm_write to where bm_flush was.
34  * This may occasionally write a bit out twice, but is sure never to
35  * miss any bits.
36  */
37
38 #include <linux/blkdev.h>
39 #include <linux/delay.h>
40 #include <linux/kthread.h>
41 #include <linux/raid/pq.h>
42 #include <linux/async_tx.h>
43 #include <linux/module.h>
44 #include <linux/async.h>
45 #include <linux/seq_file.h>
46 #include <linux/cpu.h>
47 #include <linux/slab.h>
48 #include <linux/ratelimit.h>
49 #include <linux/nodemask.h>
50
51 #include <trace/events/block.h>
52 #include <linux/list_sort.h>
53
54 #include "md.h"
55 #include "raid5.h"
56 #include "raid0.h"
57 #include "md-bitmap.h"
58 #include "raid5-log.h"
59
60 #define UNSUPPORTED_MDDEV_FLAGS (1L << MD_FAILFAST_SUPPORTED)
61
62 #define cpu_to_group(cpu) cpu_to_node(cpu)
63 #define ANY_GROUP NUMA_NO_NODE
64
65 static bool devices_handle_discard_safely = false;
66 module_param(devices_handle_discard_safely, bool, 0644);
67 MODULE_PARM_DESC(devices_handle_discard_safely,
68                  "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
69 static struct workqueue_struct *raid5_wq;
70
71 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
72 {
73         int hash = (sect >> RAID5_STRIPE_SHIFT(conf)) & HASH_MASK;
74         return &conf->stripe_hashtbl[hash];
75 }
76
77 static inline int stripe_hash_locks_hash(struct r5conf *conf, sector_t sect)
78 {
79         return (sect >> RAID5_STRIPE_SHIFT(conf)) & STRIPE_HASH_LOCKS_MASK;
80 }
81
82 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
83 {
84         spin_lock_irq(conf->hash_locks + hash);
85         spin_lock(&conf->device_lock);
86 }
87
88 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
89 {
90         spin_unlock(&conf->device_lock);
91         spin_unlock_irq(conf->hash_locks + hash);
92 }
93
94 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
95 {
96         int i;
97         spin_lock_irq(conf->hash_locks);
98         for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
99                 spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
100         spin_lock(&conf->device_lock);
101 }
102
103 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
104 {
105         int i;
106         spin_unlock(&conf->device_lock);
107         for (i = NR_STRIPE_HASH_LOCKS - 1; i; i--)
108                 spin_unlock(conf->hash_locks + i);
109         spin_unlock_irq(conf->hash_locks);
110 }
111
112 /* Find first data disk in a raid6 stripe */
113 static inline int raid6_d0(struct stripe_head *sh)
114 {
115         if (sh->ddf_layout)
116                 /* ddf always start from first device */
117                 return 0;
118         /* md starts just after Q block */
119         if (sh->qd_idx == sh->disks - 1)
120                 return 0;
121         else
122                 return sh->qd_idx + 1;
123 }
124 static inline int raid6_next_disk(int disk, int raid_disks)
125 {
126         disk++;
127         return (disk < raid_disks) ? disk : 0;
128 }
129
130 /* When walking through the disks in a raid5, starting at raid6_d0,
131  * We need to map each disk to a 'slot', where the data disks are slot
132  * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
133  * is raid_disks-1.  This help does that mapping.
134  */
135 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
136                              int *count, int syndrome_disks)
137 {
138         int slot = *count;
139
140         if (sh->ddf_layout)
141                 (*count)++;
142         if (idx == sh->pd_idx)
143                 return syndrome_disks;
144         if (idx == sh->qd_idx)
145                 return syndrome_disks + 1;
146         if (!sh->ddf_layout)
147                 (*count)++;
148         return slot;
149 }
150
151 static void print_raid5_conf (struct r5conf *conf);
152
153 static int stripe_operations_active(struct stripe_head *sh)
154 {
155         return sh->check_state || sh->reconstruct_state ||
156                test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
157                test_bit(STRIPE_COMPUTE_RUN, &sh->state);
158 }
159
160 static bool stripe_is_lowprio(struct stripe_head *sh)
161 {
162         return (test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) ||
163                 test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state)) &&
164                !test_bit(STRIPE_R5C_CACHING, &sh->state);
165 }
166
167 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
168 {
169         struct r5conf *conf = sh->raid_conf;
170         struct r5worker_group *group;
171         int thread_cnt;
172         int i, cpu = sh->cpu;
173
174         if (!cpu_online(cpu)) {
175                 cpu = cpumask_any(cpu_online_mask);
176                 sh->cpu = cpu;
177         }
178
179         if (list_empty(&sh->lru)) {
180                 struct r5worker_group *group;
181                 group = conf->worker_groups + cpu_to_group(cpu);
182                 if (stripe_is_lowprio(sh))
183                         list_add_tail(&sh->lru, &group->loprio_list);
184                 else
185                         list_add_tail(&sh->lru, &group->handle_list);
186                 group->stripes_cnt++;
187                 sh->group = group;
188         }
189
190         if (conf->worker_cnt_per_group == 0) {
191                 md_wakeup_thread(conf->mddev->thread);
192                 return;
193         }
194
195         group = conf->worker_groups + cpu_to_group(sh->cpu);
196
197         group->workers[0].working = true;
198         /* at least one worker should run to avoid race */
199         queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
200
201         thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
202         /* wakeup more workers */
203         for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
204                 if (group->workers[i].working == false) {
205                         group->workers[i].working = true;
206                         queue_work_on(sh->cpu, raid5_wq,
207                                       &group->workers[i].work);
208                         thread_cnt--;
209                 }
210         }
211 }
212
213 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
214                               struct list_head *temp_inactive_list)
215 {
216         int i;
217         int injournal = 0;      /* number of date pages with R5_InJournal */
218
219         BUG_ON(!list_empty(&sh->lru));
220         BUG_ON(atomic_read(&conf->active_stripes)==0);
221
222         if (r5c_is_writeback(conf->log))
223                 for (i = sh->disks; i--; )
224                         if (test_bit(R5_InJournal, &sh->dev[i].flags))
225                                 injournal++;
226         /*
227          * In the following cases, the stripe cannot be released to cached
228          * lists. Therefore, we make the stripe write out and set
229          * STRIPE_HANDLE:
230          *   1. when quiesce in r5c write back;
231          *   2. when resync is requested fot the stripe.
232          */
233         if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) ||
234             (conf->quiesce && r5c_is_writeback(conf->log) &&
235              !test_bit(STRIPE_HANDLE, &sh->state) && injournal != 0)) {
236                 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
237                         r5c_make_stripe_write_out(sh);
238                 set_bit(STRIPE_HANDLE, &sh->state);
239         }
240
241         if (test_bit(STRIPE_HANDLE, &sh->state)) {
242                 if (test_bit(STRIPE_DELAYED, &sh->state) &&
243                     !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
244                         list_add_tail(&sh->lru, &conf->delayed_list);
245                 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
246                            sh->bm_seq - conf->seq_write > 0)
247                         list_add_tail(&sh->lru, &conf->bitmap_list);
248                 else {
249                         clear_bit(STRIPE_DELAYED, &sh->state);
250                         clear_bit(STRIPE_BIT_DELAY, &sh->state);
251                         if (conf->worker_cnt_per_group == 0) {
252                                 if (stripe_is_lowprio(sh))
253                                         list_add_tail(&sh->lru,
254                                                         &conf->loprio_list);
255                                 else
256                                         list_add_tail(&sh->lru,
257                                                         &conf->handle_list);
258                         } else {
259                                 raid5_wakeup_stripe_thread(sh);
260                                 return;
261                         }
262                 }
263                 md_wakeup_thread(conf->mddev->thread);
264         } else {
265                 BUG_ON(stripe_operations_active(sh));
266                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
267                         if (atomic_dec_return(&conf->preread_active_stripes)
268                             < IO_THRESHOLD)
269                                 md_wakeup_thread(conf->mddev->thread);
270                 atomic_dec(&conf->active_stripes);
271                 if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
272                         if (!r5c_is_writeback(conf->log))
273                                 list_add_tail(&sh->lru, temp_inactive_list);
274                         else {
275                                 WARN_ON(test_bit(R5_InJournal, &sh->dev[sh->pd_idx].flags));
276                                 if (injournal == 0)
277                                         list_add_tail(&sh->lru, temp_inactive_list);
278                                 else if (injournal == conf->raid_disks - conf->max_degraded) {
279                                         /* full stripe */
280                                         if (!test_and_set_bit(STRIPE_R5C_FULL_STRIPE, &sh->state))
281                                                 atomic_inc(&conf->r5c_cached_full_stripes);
282                                         if (test_and_clear_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state))
283                                                 atomic_dec(&conf->r5c_cached_partial_stripes);
284                                         list_add_tail(&sh->lru, &conf->r5c_full_stripe_list);
285                                         r5c_check_cached_full_stripe(conf);
286                                 } else
287                                         /*
288                                          * STRIPE_R5C_PARTIAL_STRIPE is set in
289                                          * r5c_try_caching_write(). No need to
290                                          * set it again.
291                                          */
292                                         list_add_tail(&sh->lru, &conf->r5c_partial_stripe_list);
293                         }
294                 }
295         }
296 }
297
298 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
299                              struct list_head *temp_inactive_list)
300 {
301         if (atomic_dec_and_test(&sh->count))
302                 do_release_stripe(conf, sh, temp_inactive_list);
303 }
304
305 /*
306  * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
307  *
308  * Be careful: Only one task can add/delete stripes from temp_inactive_list at
309  * given time. Adding stripes only takes device lock, while deleting stripes
310  * only takes hash lock.
311  */
312 static void release_inactive_stripe_list(struct r5conf *conf,
313                                          struct list_head *temp_inactive_list,
314                                          int hash)
315 {
316         int size;
317         bool do_wakeup = false;
318         unsigned long flags;
319
320         if (hash == NR_STRIPE_HASH_LOCKS) {
321                 size = NR_STRIPE_HASH_LOCKS;
322                 hash = NR_STRIPE_HASH_LOCKS - 1;
323         } else
324                 size = 1;
325         while (size) {
326                 struct list_head *list = &temp_inactive_list[size - 1];
327
328                 /*
329                  * We don't hold any lock here yet, raid5_get_active_stripe() might
330                  * remove stripes from the list
331                  */
332                 if (!list_empty_careful(list)) {
333                         spin_lock_irqsave(conf->hash_locks + hash, flags);
334                         if (list_empty(conf->inactive_list + hash) &&
335                             !list_empty(list))
336                                 atomic_dec(&conf->empty_inactive_list_nr);
337                         list_splice_tail_init(list, conf->inactive_list + hash);
338                         do_wakeup = true;
339                         spin_unlock_irqrestore(conf->hash_locks + hash, flags);
340                 }
341                 size--;
342                 hash--;
343         }
344
345         if (do_wakeup) {
346                 wake_up(&conf->wait_for_stripe);
347                 if (atomic_read(&conf->active_stripes) == 0)
348                         wake_up(&conf->wait_for_quiescent);
349                 if (conf->retry_read_aligned)
350                         md_wakeup_thread(conf->mddev->thread);
351         }
352 }
353
354 /* should hold conf->device_lock already */
355 static int release_stripe_list(struct r5conf *conf,
356                                struct list_head *temp_inactive_list)
357 {
358         struct stripe_head *sh, *t;
359         int count = 0;
360         struct llist_node *head;
361
362         head = llist_del_all(&conf->released_stripes);
363         head = llist_reverse_order(head);
364         llist_for_each_entry_safe(sh, t, head, release_list) {
365                 int hash;
366
367                 /* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
368                 smp_mb();
369                 clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
370                 /*
371                  * Don't worry the bit is set here, because if the bit is set
372                  * again, the count is always > 1. This is true for
373                  * STRIPE_ON_UNPLUG_LIST bit too.
374                  */
375                 hash = sh->hash_lock_index;
376                 __release_stripe(conf, sh, &temp_inactive_list[hash]);
377                 count++;
378         }
379
380         return count;
381 }
382
383 void raid5_release_stripe(struct stripe_head *sh)
384 {
385         struct r5conf *conf = sh->raid_conf;
386         unsigned long flags;
387         struct list_head list;
388         int hash;
389         bool wakeup;
390
391         /* Avoid release_list until the last reference.
392          */
393         if (atomic_add_unless(&sh->count, -1, 1))
394                 return;
395
396         if (unlikely(!conf->mddev->thread) ||
397                 test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
398                 goto slow_path;
399         wakeup = llist_add(&sh->release_list, &conf->released_stripes);
400         if (wakeup)
401                 md_wakeup_thread(conf->mddev->thread);
402         return;
403 slow_path:
404         /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
405         if (atomic_dec_and_lock_irqsave(&sh->count, &conf->device_lock, flags)) {
406                 INIT_LIST_HEAD(&list);
407                 hash = sh->hash_lock_index;
408                 do_release_stripe(conf, sh, &list);
409                 spin_unlock_irqrestore(&conf->device_lock, flags);
410                 release_inactive_stripe_list(conf, &list, hash);
411         }
412 }
413
414 static inline void remove_hash(struct stripe_head *sh)
415 {
416         pr_debug("remove_hash(), stripe %llu\n",
417                 (unsigned long long)sh->sector);
418
419         hlist_del_init(&sh->hash);
420 }
421
422 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
423 {
424         struct hlist_head *hp = stripe_hash(conf, sh->sector);
425
426         pr_debug("insert_hash(), stripe %llu\n",
427                 (unsigned long long)sh->sector);
428
429         hlist_add_head(&sh->hash, hp);
430 }
431
432 /* find an idle stripe, make sure it is unhashed, and return it. */
433 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
434 {
435         struct stripe_head *sh = NULL;
436         struct list_head *first;
437
438         if (list_empty(conf->inactive_list + hash))
439                 goto out;
440         first = (conf->inactive_list + hash)->next;
441         sh = list_entry(first, struct stripe_head, lru);
442         list_del_init(first);
443         remove_hash(sh);
444         atomic_inc(&conf->active_stripes);
445         BUG_ON(hash != sh->hash_lock_index);
446         if (list_empty(conf->inactive_list + hash))
447                 atomic_inc(&conf->empty_inactive_list_nr);
448 out:
449         return sh;
450 }
451
452 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
453 static void free_stripe_pages(struct stripe_head *sh)
454 {
455         int i;
456         struct page *p;
457
458         /* Have not allocate page pool */
459         if (!sh->pages)
460                 return;
461
462         for (i = 0; i < sh->nr_pages; i++) {
463                 p = sh->pages[i];
464                 if (p)
465                         put_page(p);
466                 sh->pages[i] = NULL;
467         }
468 }
469
470 static int alloc_stripe_pages(struct stripe_head *sh, gfp_t gfp)
471 {
472         int i;
473         struct page *p;
474
475         for (i = 0; i < sh->nr_pages; i++) {
476                 /* The page have allocated. */
477                 if (sh->pages[i])
478                         continue;
479
480                 p = alloc_page(gfp);
481                 if (!p) {
482                         free_stripe_pages(sh);
483                         return -ENOMEM;
484                 }
485                 sh->pages[i] = p;
486         }
487         return 0;
488 }
489
490 static int
491 init_stripe_shared_pages(struct stripe_head *sh, struct r5conf *conf, int disks)
492 {
493         int nr_pages, cnt;
494
495         if (sh->pages)
496                 return 0;
497
498         /* Each of the sh->dev[i] need one conf->stripe_size */
499         cnt = PAGE_SIZE / conf->stripe_size;
500         nr_pages = (disks + cnt - 1) / cnt;
501
502         sh->pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
503         if (!sh->pages)
504                 return -ENOMEM;
505         sh->nr_pages = nr_pages;
506         sh->stripes_per_page = cnt;
507         return 0;
508 }
509 #endif
510
511 static void shrink_buffers(struct stripe_head *sh)
512 {
513         int i;
514         int num = sh->raid_conf->pool_size;
515
516 #if PAGE_SIZE == DEFAULT_STRIPE_SIZE
517         for (i = 0; i < num ; i++) {
518                 struct page *p;
519
520                 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
521                 p = sh->dev[i].page;
522                 if (!p)
523                         continue;
524                 sh->dev[i].page = NULL;
525                 put_page(p);
526         }
527 #else
528         for (i = 0; i < num; i++)
529                 sh->dev[i].page = NULL;
530         free_stripe_pages(sh); /* Free pages */
531 #endif
532 }
533
534 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
535 {
536         int i;
537         int num = sh->raid_conf->pool_size;
538
539 #if PAGE_SIZE == DEFAULT_STRIPE_SIZE
540         for (i = 0; i < num; i++) {
541                 struct page *page;
542
543                 if (!(page = alloc_page(gfp))) {
544                         return 1;
545                 }
546                 sh->dev[i].page = page;
547                 sh->dev[i].orig_page = page;
548                 sh->dev[i].offset = 0;
549         }
550 #else
551         if (alloc_stripe_pages(sh, gfp))
552                 return -ENOMEM;
553
554         for (i = 0; i < num; i++) {
555                 sh->dev[i].page = raid5_get_dev_page(sh, i);
556                 sh->dev[i].orig_page = sh->dev[i].page;
557                 sh->dev[i].offset = raid5_get_page_offset(sh, i);
558         }
559 #endif
560         return 0;
561 }
562
563 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
564                             struct stripe_head *sh);
565
566 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
567 {
568         struct r5conf *conf = sh->raid_conf;
569         int i, seq;
570
571         BUG_ON(atomic_read(&sh->count) != 0);
572         BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
573         BUG_ON(stripe_operations_active(sh));
574         BUG_ON(sh->batch_head);
575
576         pr_debug("init_stripe called, stripe %llu\n",
577                 (unsigned long long)sector);
578 retry:
579         seq = read_seqcount_begin(&conf->gen_lock);
580         sh->generation = conf->generation - previous;
581         sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
582         sh->sector = sector;
583         stripe_set_idx(sector, conf, previous, sh);
584         sh->state = 0;
585
586         for (i = sh->disks; i--; ) {
587                 struct r5dev *dev = &sh->dev[i];
588
589                 if (dev->toread || dev->read || dev->towrite || dev->written ||
590                     test_bit(R5_LOCKED, &dev->flags)) {
591                         pr_err("sector=%llx i=%d %p %p %p %p %d\n",
592                                (unsigned long long)sh->sector, i, dev->toread,
593                                dev->read, dev->towrite, dev->written,
594                                test_bit(R5_LOCKED, &dev->flags));
595                         WARN_ON(1);
596                 }
597                 dev->flags = 0;
598                 dev->sector = raid5_compute_blocknr(sh, i, previous);
599         }
600         if (read_seqcount_retry(&conf->gen_lock, seq))
601                 goto retry;
602         sh->overwrite_disks = 0;
603         insert_hash(conf, sh);
604         sh->cpu = smp_processor_id();
605         set_bit(STRIPE_BATCH_READY, &sh->state);
606 }
607
608 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
609                                          short generation)
610 {
611         struct stripe_head *sh;
612
613         pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
614         hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
615                 if (sh->sector == sector && sh->generation == generation)
616                         return sh;
617         pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
618         return NULL;
619 }
620
621 /*
622  * Need to check if array has failed when deciding whether to:
623  *  - start an array
624  *  - remove non-faulty devices
625  *  - add a spare
626  *  - allow a reshape
627  * This determination is simple when no reshape is happening.
628  * However if there is a reshape, we need to carefully check
629  * both the before and after sections.
630  * This is because some failed devices may only affect one
631  * of the two sections, and some non-in_sync devices may
632  * be insync in the section most affected by failed devices.
633  */
634 int raid5_calc_degraded(struct r5conf *conf)
635 {
636         int degraded, degraded2;
637         int i;
638
639         rcu_read_lock();
640         degraded = 0;
641         for (i = 0; i < conf->previous_raid_disks; i++) {
642                 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
643                 if (rdev && test_bit(Faulty, &rdev->flags))
644                         rdev = rcu_dereference(conf->disks[i].replacement);
645                 if (!rdev || test_bit(Faulty, &rdev->flags))
646                         degraded++;
647                 else if (test_bit(In_sync, &rdev->flags))
648                         ;
649                 else
650                         /* not in-sync or faulty.
651                          * If the reshape increases the number of devices,
652                          * this is being recovered by the reshape, so
653                          * this 'previous' section is not in_sync.
654                          * If the number of devices is being reduced however,
655                          * the device can only be part of the array if
656                          * we are reverting a reshape, so this section will
657                          * be in-sync.
658                          */
659                         if (conf->raid_disks >= conf->previous_raid_disks)
660                                 degraded++;
661         }
662         rcu_read_unlock();
663         if (conf->raid_disks == conf->previous_raid_disks)
664                 return degraded;
665         rcu_read_lock();
666         degraded2 = 0;
667         for (i = 0; i < conf->raid_disks; i++) {
668                 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
669                 if (rdev && test_bit(Faulty, &rdev->flags))
670                         rdev = rcu_dereference(conf->disks[i].replacement);
671                 if (!rdev || test_bit(Faulty, &rdev->flags))
672                         degraded2++;
673                 else if (test_bit(In_sync, &rdev->flags))
674                         ;
675                 else
676                         /* not in-sync or faulty.
677                          * If reshape increases the number of devices, this
678                          * section has already been recovered, else it
679                          * almost certainly hasn't.
680                          */
681                         if (conf->raid_disks <= conf->previous_raid_disks)
682                                 degraded2++;
683         }
684         rcu_read_unlock();
685         if (degraded2 > degraded)
686                 return degraded2;
687         return degraded;
688 }
689
690 static bool has_failed(struct r5conf *conf)
691 {
692         int degraded = conf->mddev->degraded;
693
694         if (test_bit(MD_BROKEN, &conf->mddev->flags))
695                 return true;
696
697         if (conf->mddev->reshape_position != MaxSector)
698                 degraded = raid5_calc_degraded(conf);
699
700         return degraded > conf->max_degraded;
701 }
702
703 struct stripe_head *
704 raid5_get_active_stripe(struct r5conf *conf, sector_t sector,
705                         int previous, int noblock, int noquiesce)
706 {
707         struct stripe_head *sh;
708         int hash = stripe_hash_locks_hash(conf, sector);
709         int inc_empty_inactive_list_flag;
710
711         pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
712
713         spin_lock_irq(conf->hash_locks + hash);
714
715         do {
716                 wait_event_lock_irq(conf->wait_for_quiescent,
717                                     conf->quiesce == 0 || noquiesce,
718                                     *(conf->hash_locks + hash));
719                 sh = __find_stripe(conf, sector, conf->generation - previous);
720                 if (!sh) {
721                         if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
722                                 sh = get_free_stripe(conf, hash);
723                                 if (!sh && !test_bit(R5_DID_ALLOC,
724                                                      &conf->cache_state))
725                                         set_bit(R5_ALLOC_MORE,
726                                                 &conf->cache_state);
727                         }
728                         if (noblock && sh == NULL)
729                                 break;
730
731                         r5c_check_stripe_cache_usage(conf);
732                         if (!sh) {
733                                 set_bit(R5_INACTIVE_BLOCKED,
734                                         &conf->cache_state);
735                                 r5l_wake_reclaim(conf->log, 0);
736                                 wait_event_lock_irq(
737                                         conf->wait_for_stripe,
738                                         !list_empty(conf->inactive_list + hash) &&
739                                         (atomic_read(&conf->active_stripes)
740                                          < (conf->max_nr_stripes * 3 / 4)
741                                          || !test_bit(R5_INACTIVE_BLOCKED,
742                                                       &conf->cache_state)),
743                                         *(conf->hash_locks + hash));
744                                 clear_bit(R5_INACTIVE_BLOCKED,
745                                           &conf->cache_state);
746                         } else {
747                                 init_stripe(sh, sector, previous);
748                                 atomic_inc(&sh->count);
749                         }
750                 } else if (!atomic_inc_not_zero(&sh->count)) {
751                         spin_lock(&conf->device_lock);
752                         if (!atomic_read(&sh->count)) {
753                                 if (!test_bit(STRIPE_HANDLE, &sh->state))
754                                         atomic_inc(&conf->active_stripes);
755                                 BUG_ON(list_empty(&sh->lru) &&
756                                        !test_bit(STRIPE_EXPANDING, &sh->state));
757                                 inc_empty_inactive_list_flag = 0;
758                                 if (!list_empty(conf->inactive_list + hash))
759                                         inc_empty_inactive_list_flag = 1;
760                                 list_del_init(&sh->lru);
761                                 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
762                                         atomic_inc(&conf->empty_inactive_list_nr);
763                                 if (sh->group) {
764                                         sh->group->stripes_cnt--;
765                                         sh->group = NULL;
766                                 }
767                         }
768                         atomic_inc(&sh->count);
769                         spin_unlock(&conf->device_lock);
770                 }
771         } while (sh == NULL);
772
773         spin_unlock_irq(conf->hash_locks + hash);
774         return sh;
775 }
776
777 static bool is_full_stripe_write(struct stripe_head *sh)
778 {
779         BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
780         return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
781 }
782
783 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
784                 __acquires(&sh1->stripe_lock)
785                 __acquires(&sh2->stripe_lock)
786 {
787         if (sh1 > sh2) {
788                 spin_lock_irq(&sh2->stripe_lock);
789                 spin_lock_nested(&sh1->stripe_lock, 1);
790         } else {
791                 spin_lock_irq(&sh1->stripe_lock);
792                 spin_lock_nested(&sh2->stripe_lock, 1);
793         }
794 }
795
796 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
797                 __releases(&sh1->stripe_lock)
798                 __releases(&sh2->stripe_lock)
799 {
800         spin_unlock(&sh1->stripe_lock);
801         spin_unlock_irq(&sh2->stripe_lock);
802 }
803
804 /* Only freshly new full stripe normal write stripe can be added to a batch list */
805 static bool stripe_can_batch(struct stripe_head *sh)
806 {
807         struct r5conf *conf = sh->raid_conf;
808
809         if (raid5_has_log(conf) || raid5_has_ppl(conf))
810                 return false;
811         return test_bit(STRIPE_BATCH_READY, &sh->state) &&
812                 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
813                 is_full_stripe_write(sh);
814 }
815
816 /* we only do back search */
817 static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
818 {
819         struct stripe_head *head;
820         sector_t head_sector, tmp_sec;
821         int hash;
822         int dd_idx;
823         int inc_empty_inactive_list_flag;
824
825         /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
826         tmp_sec = sh->sector;
827         if (!sector_div(tmp_sec, conf->chunk_sectors))
828                 return;
829         head_sector = sh->sector - RAID5_STRIPE_SECTORS(conf);
830
831         hash = stripe_hash_locks_hash(conf, head_sector);
832         spin_lock_irq(conf->hash_locks + hash);
833         head = __find_stripe(conf, head_sector, conf->generation);
834         if (head && !atomic_inc_not_zero(&head->count)) {
835                 spin_lock(&conf->device_lock);
836                 if (!atomic_read(&head->count)) {
837                         if (!test_bit(STRIPE_HANDLE, &head->state))
838                                 atomic_inc(&conf->active_stripes);
839                         BUG_ON(list_empty(&head->lru) &&
840                                !test_bit(STRIPE_EXPANDING, &head->state));
841                         inc_empty_inactive_list_flag = 0;
842                         if (!list_empty(conf->inactive_list + hash))
843                                 inc_empty_inactive_list_flag = 1;
844                         list_del_init(&head->lru);
845                         if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
846                                 atomic_inc(&conf->empty_inactive_list_nr);
847                         if (head->group) {
848                                 head->group->stripes_cnt--;
849                                 head->group = NULL;
850                         }
851                 }
852                 atomic_inc(&head->count);
853                 spin_unlock(&conf->device_lock);
854         }
855         spin_unlock_irq(conf->hash_locks + hash);
856
857         if (!head)
858                 return;
859         if (!stripe_can_batch(head))
860                 goto out;
861
862         lock_two_stripes(head, sh);
863         /* clear_batch_ready clear the flag */
864         if (!stripe_can_batch(head) || !stripe_can_batch(sh))
865                 goto unlock_out;
866
867         if (sh->batch_head)
868                 goto unlock_out;
869
870         dd_idx = 0;
871         while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
872                 dd_idx++;
873         if (head->dev[dd_idx].towrite->bi_opf != sh->dev[dd_idx].towrite->bi_opf ||
874             bio_op(head->dev[dd_idx].towrite) != bio_op(sh->dev[dd_idx].towrite))
875                 goto unlock_out;
876
877         if (head->batch_head) {
878                 spin_lock(&head->batch_head->batch_lock);
879                 /* This batch list is already running */
880                 if (!stripe_can_batch(head)) {
881                         spin_unlock(&head->batch_head->batch_lock);
882                         goto unlock_out;
883                 }
884                 /*
885                  * We must assign batch_head of this stripe within the
886                  * batch_lock, otherwise clear_batch_ready of batch head
887                  * stripe could clear BATCH_READY bit of this stripe and
888                  * this stripe->batch_head doesn't get assigned, which
889                  * could confuse clear_batch_ready for this stripe
890                  */
891                 sh->batch_head = head->batch_head;
892
893                 /*
894                  * at this point, head's BATCH_READY could be cleared, but we
895                  * can still add the stripe to batch list
896                  */
897                 list_add(&sh->batch_list, &head->batch_list);
898                 spin_unlock(&head->batch_head->batch_lock);
899         } else {
900                 head->batch_head = head;
901                 sh->batch_head = head->batch_head;
902                 spin_lock(&head->batch_lock);
903                 list_add_tail(&sh->batch_list, &head->batch_list);
904                 spin_unlock(&head->batch_lock);
905         }
906
907         if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
908                 if (atomic_dec_return(&conf->preread_active_stripes)
909                     < IO_THRESHOLD)
910                         md_wakeup_thread(conf->mddev->thread);
911
912         if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
913                 int seq = sh->bm_seq;
914                 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
915                     sh->batch_head->bm_seq > seq)
916                         seq = sh->batch_head->bm_seq;
917                 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
918                 sh->batch_head->bm_seq = seq;
919         }
920
921         atomic_inc(&sh->count);
922 unlock_out:
923         unlock_two_stripes(head, sh);
924 out:
925         raid5_release_stripe(head);
926 }
927
928 /* Determine if 'data_offset' or 'new_data_offset' should be used
929  * in this stripe_head.
930  */
931 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
932 {
933         sector_t progress = conf->reshape_progress;
934         /* Need a memory barrier to make sure we see the value
935          * of conf->generation, or ->data_offset that was set before
936          * reshape_progress was updated.
937          */
938         smp_rmb();
939         if (progress == MaxSector)
940                 return 0;
941         if (sh->generation == conf->generation - 1)
942                 return 0;
943         /* We are in a reshape, and this is a new-generation stripe,
944          * so use new_data_offset.
945          */
946         return 1;
947 }
948
949 static void dispatch_bio_list(struct bio_list *tmp)
950 {
951         struct bio *bio;
952
953         while ((bio = bio_list_pop(tmp)))
954                 submit_bio_noacct(bio);
955 }
956
957 static int cmp_stripe(void *priv, const struct list_head *a,
958                       const struct list_head *b)
959 {
960         const struct r5pending_data *da = list_entry(a,
961                                 struct r5pending_data, sibling);
962         const struct r5pending_data *db = list_entry(b,
963                                 struct r5pending_data, sibling);
964         if (da->sector > db->sector)
965                 return 1;
966         if (da->sector < db->sector)
967                 return -1;
968         return 0;
969 }
970
971 static void dispatch_defer_bios(struct r5conf *conf, int target,
972                                 struct bio_list *list)
973 {
974         struct r5pending_data *data;
975         struct list_head *first, *next = NULL;
976         int cnt = 0;
977
978         if (conf->pending_data_cnt == 0)
979                 return;
980
981         list_sort(NULL, &conf->pending_list, cmp_stripe);
982
983         first = conf->pending_list.next;
984
985         /* temporarily move the head */
986         if (conf->next_pending_data)
987                 list_move_tail(&conf->pending_list,
988                                 &conf->next_pending_data->sibling);
989
990         while (!list_empty(&conf->pending_list)) {
991                 data = list_first_entry(&conf->pending_list,
992                         struct r5pending_data, sibling);
993                 if (&data->sibling == first)
994                         first = data->sibling.next;
995                 next = data->sibling.next;
996
997                 bio_list_merge(list, &data->bios);
998                 list_move(&data->sibling, &conf->free_list);
999                 cnt++;
1000                 if (cnt >= target)
1001                         break;
1002         }
1003         conf->pending_data_cnt -= cnt;
1004         BUG_ON(conf->pending_data_cnt < 0 || cnt < target);
1005
1006         if (next != &conf->pending_list)
1007                 conf->next_pending_data = list_entry(next,
1008                                 struct r5pending_data, sibling);
1009         else
1010                 conf->next_pending_data = NULL;
1011         /* list isn't empty */
1012         if (first != &conf->pending_list)
1013                 list_move_tail(&conf->pending_list, first);
1014 }
1015
1016 static void flush_deferred_bios(struct r5conf *conf)
1017 {
1018         struct bio_list tmp = BIO_EMPTY_LIST;
1019
1020         if (conf->pending_data_cnt == 0)
1021                 return;
1022
1023         spin_lock(&conf->pending_bios_lock);
1024         dispatch_defer_bios(conf, conf->pending_data_cnt, &tmp);
1025         BUG_ON(conf->pending_data_cnt != 0);
1026         spin_unlock(&conf->pending_bios_lock);
1027
1028         dispatch_bio_list(&tmp);
1029 }
1030
1031 static void defer_issue_bios(struct r5conf *conf, sector_t sector,
1032                                 struct bio_list *bios)
1033 {
1034         struct bio_list tmp = BIO_EMPTY_LIST;
1035         struct r5pending_data *ent;
1036
1037         spin_lock(&conf->pending_bios_lock);
1038         ent = list_first_entry(&conf->free_list, struct r5pending_data,
1039                                                         sibling);
1040         list_move_tail(&ent->sibling, &conf->pending_list);
1041         ent->sector = sector;
1042         bio_list_init(&ent->bios);
1043         bio_list_merge(&ent->bios, bios);
1044         conf->pending_data_cnt++;
1045         if (conf->pending_data_cnt >= PENDING_IO_MAX)
1046                 dispatch_defer_bios(conf, PENDING_IO_ONE_FLUSH, &tmp);
1047
1048         spin_unlock(&conf->pending_bios_lock);
1049
1050         dispatch_bio_list(&tmp);
1051 }
1052
1053 static void
1054 raid5_end_read_request(struct bio *bi);
1055 static void
1056 raid5_end_write_request(struct bio *bi);
1057
1058 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
1059 {
1060         struct r5conf *conf = sh->raid_conf;
1061         int i, disks = sh->disks;
1062         struct stripe_head *head_sh = sh;
1063         struct bio_list pending_bios = BIO_EMPTY_LIST;
1064         bool should_defer;
1065
1066         might_sleep();
1067
1068         if (log_stripe(sh, s) == 0)
1069                 return;
1070
1071         should_defer = conf->batch_bio_dispatch && conf->group_cnt;
1072
1073         for (i = disks; i--; ) {
1074                 int op, op_flags = 0;
1075                 int replace_only = 0;
1076                 struct bio *bi, *rbi;
1077                 struct md_rdev *rdev, *rrdev = NULL;
1078
1079                 sh = head_sh;
1080                 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
1081                         op = REQ_OP_WRITE;
1082                         if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
1083                                 op_flags = REQ_FUA;
1084                         if (test_bit(R5_Discard, &sh->dev[i].flags))
1085                                 op = REQ_OP_DISCARD;
1086                 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
1087                         op = REQ_OP_READ;
1088                 else if (test_and_clear_bit(R5_WantReplace,
1089                                             &sh->dev[i].flags)) {
1090                         op = REQ_OP_WRITE;
1091                         replace_only = 1;
1092                 } else
1093                         continue;
1094                 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
1095                         op_flags |= REQ_SYNC;
1096
1097 again:
1098                 bi = &sh->dev[i].req;
1099                 rbi = &sh->dev[i].rreq; /* For writing to replacement */
1100
1101                 rcu_read_lock();
1102                 rrdev = rcu_dereference(conf->disks[i].replacement);
1103                 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
1104                 rdev = rcu_dereference(conf->disks[i].rdev);
1105                 if (!rdev) {
1106                         rdev = rrdev;
1107                         rrdev = NULL;
1108                 }
1109                 if (op_is_write(op)) {
1110                         if (replace_only)
1111                                 rdev = NULL;
1112                         if (rdev == rrdev)
1113                                 /* We raced and saw duplicates */
1114                                 rrdev = NULL;
1115                 } else {
1116                         if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
1117                                 rdev = rrdev;
1118                         rrdev = NULL;
1119                 }
1120
1121                 if (rdev && test_bit(Faulty, &rdev->flags))
1122                         rdev = NULL;
1123                 if (rdev)
1124                         atomic_inc(&rdev->nr_pending);
1125                 if (rrdev && test_bit(Faulty, &rrdev->flags))
1126                         rrdev = NULL;
1127                 if (rrdev)
1128                         atomic_inc(&rrdev->nr_pending);
1129                 rcu_read_unlock();
1130
1131                 /* We have already checked bad blocks for reads.  Now
1132                  * need to check for writes.  We never accept write errors
1133                  * on the replacement, so we don't to check rrdev.
1134                  */
1135                 while (op_is_write(op) && rdev &&
1136                        test_bit(WriteErrorSeen, &rdev->flags)) {
1137                         sector_t first_bad;
1138                         int bad_sectors;
1139                         int bad = is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
1140                                               &first_bad, &bad_sectors);
1141                         if (!bad)
1142                                 break;
1143
1144                         if (bad < 0) {
1145                                 set_bit(BlockedBadBlocks, &rdev->flags);
1146                                 if (!conf->mddev->external &&
1147                                     conf->mddev->sb_flags) {
1148                                         /* It is very unlikely, but we might
1149                                          * still need to write out the
1150                                          * bad block log - better give it
1151                                          * a chance*/
1152                                         md_check_recovery(conf->mddev);
1153                                 }
1154                                 /*
1155                                  * Because md_wait_for_blocked_rdev
1156                                  * will dec nr_pending, we must
1157                                  * increment it first.
1158                                  */
1159                                 atomic_inc(&rdev->nr_pending);
1160                                 md_wait_for_blocked_rdev(rdev, conf->mddev);
1161                         } else {
1162                                 /* Acknowledged bad block - skip the write */
1163                                 rdev_dec_pending(rdev, conf->mddev);
1164                                 rdev = NULL;
1165                         }
1166                 }
1167
1168                 if (rdev) {
1169                         if (s->syncing || s->expanding || s->expanded
1170                             || s->replacing)
1171                                 md_sync_acct(rdev->bdev, RAID5_STRIPE_SECTORS(conf));
1172
1173                         set_bit(STRIPE_IO_STARTED, &sh->state);
1174
1175                         bio_set_dev(bi, rdev->bdev);
1176                         bio_set_op_attrs(bi, op, op_flags);
1177                         bi->bi_end_io = op_is_write(op)
1178                                 ? raid5_end_write_request
1179                                 : raid5_end_read_request;
1180                         bi->bi_private = sh;
1181
1182                         pr_debug("%s: for %llu schedule op %d on disc %d\n",
1183                                 __func__, (unsigned long long)sh->sector,
1184                                 bi->bi_opf, i);
1185                         atomic_inc(&sh->count);
1186                         if (sh != head_sh)
1187                                 atomic_inc(&head_sh->count);
1188                         if (use_new_offset(conf, sh))
1189                                 bi->bi_iter.bi_sector = (sh->sector
1190                                                  + rdev->new_data_offset);
1191                         else
1192                                 bi->bi_iter.bi_sector = (sh->sector
1193                                                  + rdev->data_offset);
1194                         if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1195                                 bi->bi_opf |= REQ_NOMERGE;
1196
1197                         if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1198                                 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1199
1200                         if (!op_is_write(op) &&
1201                             test_bit(R5_InJournal, &sh->dev[i].flags))
1202                                 /*
1203                                  * issuing read for a page in journal, this
1204                                  * must be preparing for prexor in rmw; read
1205                                  * the data into orig_page
1206                                  */
1207                                 sh->dev[i].vec.bv_page = sh->dev[i].orig_page;
1208                         else
1209                                 sh->dev[i].vec.bv_page = sh->dev[i].page;
1210                         bi->bi_vcnt = 1;
1211                         bi->bi_io_vec[0].bv_len = RAID5_STRIPE_SIZE(conf);
1212                         bi->bi_io_vec[0].bv_offset = sh->dev[i].offset;
1213                         bi->bi_iter.bi_size = RAID5_STRIPE_SIZE(conf);
1214                         bi->bi_write_hint = sh->dev[i].write_hint;
1215                         if (!rrdev)
1216                                 sh->dev[i].write_hint = RWH_WRITE_LIFE_NOT_SET;
1217                         /*
1218                          * If this is discard request, set bi_vcnt 0. We don't
1219                          * want to confuse SCSI because SCSI will replace payload
1220                          */
1221                         if (op == REQ_OP_DISCARD)
1222                                 bi->bi_vcnt = 0;
1223                         if (rrdev)
1224                                 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1225
1226                         if (conf->mddev->gendisk)
1227                                 trace_block_bio_remap(bi->bi_disk->queue,
1228                                                       bi, disk_devt(conf->mddev->gendisk),
1229                                                       sh->dev[i].sector);
1230                         if (should_defer && op_is_write(op))
1231                                 bio_list_add(&pending_bios, bi);
1232                         else
1233                                 submit_bio_noacct(bi);
1234                 }
1235                 if (rrdev) {
1236                         if (s->syncing || s->expanding || s->expanded
1237                             || s->replacing)
1238                                 md_sync_acct(rrdev->bdev, RAID5_STRIPE_SECTORS(conf));
1239
1240                         set_bit(STRIPE_IO_STARTED, &sh->state);
1241
1242                         bio_set_dev(rbi, rrdev->bdev);
1243                         bio_set_op_attrs(rbi, op, op_flags);
1244                         BUG_ON(!op_is_write(op));
1245                         rbi->bi_end_io = raid5_end_write_request;
1246                         rbi->bi_private = sh;
1247
1248                         pr_debug("%s: for %llu schedule op %d on "
1249                                  "replacement disc %d\n",
1250                                 __func__, (unsigned long long)sh->sector,
1251                                 rbi->bi_opf, i);
1252                         atomic_inc(&sh->count);
1253                         if (sh != head_sh)
1254                                 atomic_inc(&head_sh->count);
1255                         if (use_new_offset(conf, sh))
1256                                 rbi->bi_iter.bi_sector = (sh->sector
1257                                                   + rrdev->new_data_offset);
1258                         else
1259                                 rbi->bi_iter.bi_sector = (sh->sector
1260                                                   + rrdev->data_offset);
1261                         if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1262                                 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1263                         sh->dev[i].rvec.bv_page = sh->dev[i].page;
1264                         rbi->bi_vcnt = 1;
1265                         rbi->bi_io_vec[0].bv_len = RAID5_STRIPE_SIZE(conf);
1266                         rbi->bi_io_vec[0].bv_offset = sh->dev[i].offset;
1267                         rbi->bi_iter.bi_size = RAID5_STRIPE_SIZE(conf);
1268                         rbi->bi_write_hint = sh->dev[i].write_hint;
1269                         sh->dev[i].write_hint = RWH_WRITE_LIFE_NOT_SET;
1270                         /*
1271                          * If this is discard request, set bi_vcnt 0. We don't
1272                          * want to confuse SCSI because SCSI will replace payload
1273                          */
1274                         if (op == REQ_OP_DISCARD)
1275                                 rbi->bi_vcnt = 0;
1276                         if (conf->mddev->gendisk)
1277                                 trace_block_bio_remap(rbi->bi_disk->queue,
1278                                                       rbi, disk_devt(conf->mddev->gendisk),
1279                                                       sh->dev[i].sector);
1280                         if (should_defer && op_is_write(op))
1281                                 bio_list_add(&pending_bios, rbi);
1282                         else
1283                                 submit_bio_noacct(rbi);
1284                 }
1285                 if (!rdev && !rrdev) {
1286                         if (op_is_write(op))
1287                                 set_bit(STRIPE_DEGRADED, &sh->state);
1288                         pr_debug("skip op %d on disc %d for sector %llu\n",
1289                                 bi->bi_opf, i, (unsigned long long)sh->sector);
1290                         clear_bit(R5_LOCKED, &sh->dev[i].flags);
1291                         set_bit(STRIPE_HANDLE, &sh->state);
1292                 }
1293
1294                 if (!head_sh->batch_head)
1295                         continue;
1296                 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1297                                       batch_list);
1298                 if (sh != head_sh)
1299                         goto again;
1300         }
1301
1302         if (should_defer && !bio_list_empty(&pending_bios))
1303                 defer_issue_bios(conf, head_sh->sector, &pending_bios);
1304 }
1305
1306 static struct dma_async_tx_descriptor *
1307 async_copy_data(int frombio, struct bio *bio, struct page **page,
1308         unsigned int poff, sector_t sector, struct dma_async_tx_descriptor *tx,
1309         struct stripe_head *sh, int no_skipcopy)
1310 {
1311         struct bio_vec bvl;
1312         struct bvec_iter iter;
1313         struct page *bio_page;
1314         int page_offset;
1315         struct async_submit_ctl submit;
1316         enum async_tx_flags flags = 0;
1317         struct r5conf *conf = sh->raid_conf;
1318
1319         if (bio->bi_iter.bi_sector >= sector)
1320                 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1321         else
1322                 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1323
1324         if (frombio)
1325                 flags |= ASYNC_TX_FENCE;
1326         init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1327
1328         bio_for_each_segment(bvl, bio, iter) {
1329                 int len = bvl.bv_len;
1330                 int clen;
1331                 int b_offset = 0;
1332
1333                 if (page_offset < 0) {
1334                         b_offset = -page_offset;
1335                         page_offset += b_offset;
1336                         len -= b_offset;
1337                 }
1338
1339                 if (len > 0 && page_offset + len > RAID5_STRIPE_SIZE(conf))
1340                         clen = RAID5_STRIPE_SIZE(conf) - page_offset;
1341                 else
1342                         clen = len;
1343
1344                 if (clen > 0) {
1345                         b_offset += bvl.bv_offset;
1346                         bio_page = bvl.bv_page;
1347                         if (frombio) {
1348                                 if (conf->skip_copy &&
1349                                     b_offset == 0 && page_offset == 0 &&
1350                                     clen == RAID5_STRIPE_SIZE(conf) &&
1351                                     !no_skipcopy)
1352                                         *page = bio_page;
1353                                 else
1354                                         tx = async_memcpy(*page, bio_page, page_offset + poff,
1355                                                   b_offset, clen, &submit);
1356                         } else
1357                                 tx = async_memcpy(bio_page, *page, b_offset,
1358                                                   page_offset + poff, clen, &submit);
1359                 }
1360                 /* chain the operations */
1361                 submit.depend_tx = tx;
1362
1363                 if (clen < len) /* hit end of page */
1364                         break;
1365                 page_offset +=  len;
1366         }
1367
1368         return tx;
1369 }
1370
1371 static void ops_complete_biofill(void *stripe_head_ref)
1372 {
1373         struct stripe_head *sh = stripe_head_ref;
1374         int i;
1375         struct r5conf *conf = sh->raid_conf;
1376
1377         pr_debug("%s: stripe %llu\n", __func__,
1378                 (unsigned long long)sh->sector);
1379
1380         /* clear completed biofills */
1381         for (i = sh->disks; i--; ) {
1382                 struct r5dev *dev = &sh->dev[i];
1383
1384                 /* acknowledge completion of a biofill operation */
1385                 /* and check if we need to reply to a read request,
1386                  * new R5_Wantfill requests are held off until
1387                  * !STRIPE_BIOFILL_RUN
1388                  */
1389                 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1390                         struct bio *rbi, *rbi2;
1391
1392                         BUG_ON(!dev->read);
1393                         rbi = dev->read;
1394                         dev->read = NULL;
1395                         while (rbi && rbi->bi_iter.bi_sector <
1396                                 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1397                                 rbi2 = r5_next_bio(conf, rbi, dev->sector);
1398                                 bio_endio(rbi);
1399                                 rbi = rbi2;
1400                         }
1401                 }
1402         }
1403         clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1404
1405         set_bit(STRIPE_HANDLE, &sh->state);
1406         raid5_release_stripe(sh);
1407 }
1408
1409 static void ops_run_biofill(struct stripe_head *sh)
1410 {
1411         struct dma_async_tx_descriptor *tx = NULL;
1412         struct async_submit_ctl submit;
1413         int i;
1414         struct r5conf *conf = sh->raid_conf;
1415
1416         BUG_ON(sh->batch_head);
1417         pr_debug("%s: stripe %llu\n", __func__,
1418                 (unsigned long long)sh->sector);
1419
1420         for (i = sh->disks; i--; ) {
1421                 struct r5dev *dev = &sh->dev[i];
1422                 if (test_bit(R5_Wantfill, &dev->flags)) {
1423                         struct bio *rbi;
1424                         spin_lock_irq(&sh->stripe_lock);
1425                         dev->read = rbi = dev->toread;
1426                         dev->toread = NULL;
1427                         spin_unlock_irq(&sh->stripe_lock);
1428                         while (rbi && rbi->bi_iter.bi_sector <
1429                                 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1430                                 tx = async_copy_data(0, rbi, &dev->page,
1431                                                      dev->offset,
1432                                                      dev->sector, tx, sh, 0);
1433                                 rbi = r5_next_bio(conf, rbi, dev->sector);
1434                         }
1435                 }
1436         }
1437
1438         atomic_inc(&sh->count);
1439         init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1440         async_trigger_callback(&submit);
1441 }
1442
1443 static void mark_target_uptodate(struct stripe_head *sh, int target)
1444 {
1445         struct r5dev *tgt;
1446
1447         if (target < 0)
1448                 return;
1449
1450         tgt = &sh->dev[target];
1451         set_bit(R5_UPTODATE, &tgt->flags);
1452         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1453         clear_bit(R5_Wantcompute, &tgt->flags);
1454 }
1455
1456 static void ops_complete_compute(void *stripe_head_ref)
1457 {
1458         struct stripe_head *sh = stripe_head_ref;
1459
1460         pr_debug("%s: stripe %llu\n", __func__,
1461                 (unsigned long long)sh->sector);
1462
1463         /* mark the computed target(s) as uptodate */
1464         mark_target_uptodate(sh, sh->ops.target);
1465         mark_target_uptodate(sh, sh->ops.target2);
1466
1467         clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1468         if (sh->check_state == check_state_compute_run)
1469                 sh->check_state = check_state_compute_result;
1470         set_bit(STRIPE_HANDLE, &sh->state);
1471         raid5_release_stripe(sh);
1472 }
1473
1474 /* return a pointer to the address conversion region of the scribble buffer */
1475 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1476 {
1477         return percpu->scribble + i * percpu->scribble_obj_size;
1478 }
1479
1480 /* return a pointer to the address conversion region of the scribble buffer */
1481 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1482                                  struct raid5_percpu *percpu, int i)
1483 {
1484         return (void *) (to_addr_page(percpu, i) + sh->disks + 2);
1485 }
1486
1487 /*
1488  * Return a pointer to record offset address.
1489  */
1490 static unsigned int *
1491 to_addr_offs(struct stripe_head *sh, struct raid5_percpu *percpu)
1492 {
1493         return (unsigned int *) (to_addr_conv(sh, percpu, 0) + sh->disks + 2);
1494 }
1495
1496 static struct dma_async_tx_descriptor *
1497 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1498 {
1499         int disks = sh->disks;
1500         struct page **xor_srcs = to_addr_page(percpu, 0);
1501         unsigned int *off_srcs = to_addr_offs(sh, percpu);
1502         int target = sh->ops.target;
1503         struct r5dev *tgt = &sh->dev[target];
1504         struct page *xor_dest = tgt->page;
1505         unsigned int off_dest = tgt->offset;
1506         int count = 0;
1507         struct dma_async_tx_descriptor *tx;
1508         struct async_submit_ctl submit;
1509         int i;
1510
1511         BUG_ON(sh->batch_head);
1512
1513         pr_debug("%s: stripe %llu block: %d\n",
1514                 __func__, (unsigned long long)sh->sector, target);
1515         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1516
1517         for (i = disks; i--; ) {
1518                 if (i != target) {
1519                         off_srcs[count] = sh->dev[i].offset;
1520                         xor_srcs[count++] = sh->dev[i].page;
1521                 }
1522         }
1523
1524         atomic_inc(&sh->count);
1525
1526         init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1527                           ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1528         if (unlikely(count == 1))
1529                 tx = async_memcpy(xor_dest, xor_srcs[0], off_dest, off_srcs[0],
1530                                 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1531         else
1532                 tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
1533                                 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1534
1535         return tx;
1536 }
1537
1538 /* set_syndrome_sources - populate source buffers for gen_syndrome
1539  * @srcs - (struct page *) array of size sh->disks
1540  * @offs - (unsigned int) array of offset for each page
1541  * @sh - stripe_head to parse
1542  *
1543  * Populates srcs in proper layout order for the stripe and returns the
1544  * 'count' of sources to be used in a call to async_gen_syndrome.  The P
1545  * destination buffer is recorded in srcs[count] and the Q destination
1546  * is recorded in srcs[count+1]].
1547  */
1548 static int set_syndrome_sources(struct page **srcs,
1549                                 unsigned int *offs,
1550                                 struct stripe_head *sh,
1551                                 int srctype)
1552 {
1553         int disks = sh->disks;
1554         int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1555         int d0_idx = raid6_d0(sh);
1556         int count;
1557         int i;
1558
1559         for (i = 0; i < disks; i++)
1560                 srcs[i] = NULL;
1561
1562         count = 0;
1563         i = d0_idx;
1564         do {
1565                 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1566                 struct r5dev *dev = &sh->dev[i];
1567
1568                 if (i == sh->qd_idx || i == sh->pd_idx ||
1569                     (srctype == SYNDROME_SRC_ALL) ||
1570                     (srctype == SYNDROME_SRC_WANT_DRAIN &&
1571                      (test_bit(R5_Wantdrain, &dev->flags) ||
1572                       test_bit(R5_InJournal, &dev->flags))) ||
1573                     (srctype == SYNDROME_SRC_WRITTEN &&
1574                      (dev->written ||
1575                       test_bit(R5_InJournal, &dev->flags)))) {
1576                         if (test_bit(R5_InJournal, &dev->flags))
1577                                 srcs[slot] = sh->dev[i].orig_page;
1578                         else
1579                                 srcs[slot] = sh->dev[i].page;
1580                         /*
1581                          * For R5_InJournal, PAGE_SIZE must be 4KB and will
1582                          * not shared page. In that case, dev[i].offset
1583                          * is 0.
1584                          */
1585                         offs[slot] = sh->dev[i].offset;
1586                 }
1587                 i = raid6_next_disk(i, disks);
1588         } while (i != d0_idx);
1589
1590         return syndrome_disks;
1591 }
1592
1593 static struct dma_async_tx_descriptor *
1594 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1595 {
1596         int disks = sh->disks;
1597         struct page **blocks = to_addr_page(percpu, 0);
1598         unsigned int *offs = to_addr_offs(sh, percpu);
1599         int target;
1600         int qd_idx = sh->qd_idx;
1601         struct dma_async_tx_descriptor *tx;
1602         struct async_submit_ctl submit;
1603         struct r5dev *tgt;
1604         struct page *dest;
1605         unsigned int dest_off;
1606         int i;
1607         int count;
1608
1609         BUG_ON(sh->batch_head);
1610         if (sh->ops.target < 0)
1611                 target = sh->ops.target2;
1612         else if (sh->ops.target2 < 0)
1613                 target = sh->ops.target;
1614         else
1615                 /* we should only have one valid target */
1616                 BUG();
1617         BUG_ON(target < 0);
1618         pr_debug("%s: stripe %llu block: %d\n",
1619                 __func__, (unsigned long long)sh->sector, target);
1620
1621         tgt = &sh->dev[target];
1622         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1623         dest = tgt->page;
1624         dest_off = tgt->offset;
1625
1626         atomic_inc(&sh->count);
1627
1628         if (target == qd_idx) {
1629                 count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_ALL);
1630                 blocks[count] = NULL; /* regenerating p is not necessary */
1631                 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1632                 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1633                                   ops_complete_compute, sh,
1634                                   to_addr_conv(sh, percpu, 0));
1635                 tx = async_gen_syndrome(blocks, offs, count+2,
1636                                 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1637         } else {
1638                 /* Compute any data- or p-drive using XOR */
1639                 count = 0;
1640                 for (i = disks; i-- ; ) {
1641                         if (i == target || i == qd_idx)
1642                                 continue;
1643                         offs[count] = sh->dev[i].offset;
1644                         blocks[count++] = sh->dev[i].page;
1645                 }
1646
1647                 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1648                                   NULL, ops_complete_compute, sh,
1649                                   to_addr_conv(sh, percpu, 0));
1650                 tx = async_xor_offs(dest, dest_off, blocks, offs, count,
1651                                 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1652         }
1653
1654         return tx;
1655 }
1656
1657 static struct dma_async_tx_descriptor *
1658 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1659 {
1660         int i, count, disks = sh->disks;
1661         int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1662         int d0_idx = raid6_d0(sh);
1663         int faila = -1, failb = -1;
1664         int target = sh->ops.target;
1665         int target2 = sh->ops.target2;
1666         struct r5dev *tgt = &sh->dev[target];
1667         struct r5dev *tgt2 = &sh->dev[target2];
1668         struct dma_async_tx_descriptor *tx;
1669         struct page **blocks = to_addr_page(percpu, 0);
1670         unsigned int *offs = to_addr_offs(sh, percpu);
1671         struct async_submit_ctl submit;
1672
1673         BUG_ON(sh->batch_head);
1674         pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1675                  __func__, (unsigned long long)sh->sector, target, target2);
1676         BUG_ON(target < 0 || target2 < 0);
1677         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1678         BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1679
1680         /* we need to open-code set_syndrome_sources to handle the
1681          * slot number conversion for 'faila' and 'failb'
1682          */
1683         for (i = 0; i < disks ; i++) {
1684                 offs[i] = 0;
1685                 blocks[i] = NULL;
1686         }
1687         count = 0;
1688         i = d0_idx;
1689         do {
1690                 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1691
1692                 offs[slot] = sh->dev[i].offset;
1693                 blocks[slot] = sh->dev[i].page;
1694
1695                 if (i == target)
1696                         faila = slot;
1697                 if (i == target2)
1698                         failb = slot;
1699                 i = raid6_next_disk(i, disks);
1700         } while (i != d0_idx);
1701
1702         BUG_ON(faila == failb);
1703         if (failb < faila)
1704                 swap(faila, failb);
1705         pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1706                  __func__, (unsigned long long)sh->sector, faila, failb);
1707
1708         atomic_inc(&sh->count);
1709
1710         if (failb == syndrome_disks+1) {
1711                 /* Q disk is one of the missing disks */
1712                 if (faila == syndrome_disks) {
1713                         /* Missing P+Q, just recompute */
1714                         init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1715                                           ops_complete_compute, sh,
1716                                           to_addr_conv(sh, percpu, 0));
1717                         return async_gen_syndrome(blocks, offs, syndrome_disks+2,
1718                                                   RAID5_STRIPE_SIZE(sh->raid_conf),
1719                                                   &submit);
1720                 } else {
1721                         struct page *dest;
1722                         unsigned int dest_off;
1723                         int data_target;
1724                         int qd_idx = sh->qd_idx;
1725
1726                         /* Missing D+Q: recompute D from P, then recompute Q */
1727                         if (target == qd_idx)
1728                                 data_target = target2;
1729                         else
1730                                 data_target = target;
1731
1732                         count = 0;
1733                         for (i = disks; i-- ; ) {
1734                                 if (i == data_target || i == qd_idx)
1735                                         continue;
1736                                 offs[count] = sh->dev[i].offset;
1737                                 blocks[count++] = sh->dev[i].page;
1738                         }
1739                         dest = sh->dev[data_target].page;
1740                         dest_off = sh->dev[data_target].offset;
1741                         init_async_submit(&submit,
1742                                           ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1743                                           NULL, NULL, NULL,
1744                                           to_addr_conv(sh, percpu, 0));
1745                         tx = async_xor_offs(dest, dest_off, blocks, offs, count,
1746                                        RAID5_STRIPE_SIZE(sh->raid_conf),
1747                                        &submit);
1748
1749                         count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_ALL);
1750                         init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1751                                           ops_complete_compute, sh,
1752                                           to_addr_conv(sh, percpu, 0));
1753                         return async_gen_syndrome(blocks, offs, count+2,
1754                                                   RAID5_STRIPE_SIZE(sh->raid_conf),
1755                                                   &submit);
1756                 }
1757         } else {
1758                 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1759                                   ops_complete_compute, sh,
1760                                   to_addr_conv(sh, percpu, 0));
1761                 if (failb == syndrome_disks) {
1762                         /* We're missing D+P. */
1763                         return async_raid6_datap_recov(syndrome_disks+2,
1764                                                 RAID5_STRIPE_SIZE(sh->raid_conf),
1765                                                 faila,
1766                                                 blocks, offs, &submit);
1767                 } else {
1768                         /* We're missing D+D. */
1769                         return async_raid6_2data_recov(syndrome_disks+2,
1770                                                 RAID5_STRIPE_SIZE(sh->raid_conf),
1771                                                 faila, failb,
1772                                                 blocks, offs, &submit);
1773                 }
1774         }
1775 }
1776
1777 static void ops_complete_prexor(void *stripe_head_ref)
1778 {
1779         struct stripe_head *sh = stripe_head_ref;
1780
1781         pr_debug("%s: stripe %llu\n", __func__,
1782                 (unsigned long long)sh->sector);
1783
1784         if (r5c_is_writeback(sh->raid_conf->log))
1785                 /*
1786                  * raid5-cache write back uses orig_page during prexor.
1787                  * After prexor, it is time to free orig_page
1788                  */
1789                 r5c_release_extra_page(sh);
1790 }
1791
1792 static struct dma_async_tx_descriptor *
1793 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1794                 struct dma_async_tx_descriptor *tx)
1795 {
1796         int disks = sh->disks;
1797         struct page **xor_srcs = to_addr_page(percpu, 0);
1798         unsigned int *off_srcs = to_addr_offs(sh, percpu);
1799         int count = 0, pd_idx = sh->pd_idx, i;
1800         struct async_submit_ctl submit;
1801
1802         /* existing parity data subtracted */
1803         unsigned int off_dest = off_srcs[count] = sh->dev[pd_idx].offset;
1804         struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1805
1806         BUG_ON(sh->batch_head);
1807         pr_debug("%s: stripe %llu\n", __func__,
1808                 (unsigned long long)sh->sector);
1809
1810         for (i = disks; i--; ) {
1811                 struct r5dev *dev = &sh->dev[i];
1812                 /* Only process blocks that are known to be uptodate */
1813                 if (test_bit(R5_InJournal, &dev->flags)) {
1814                         /*
1815                          * For this case, PAGE_SIZE must be equal to 4KB and
1816                          * page offset is zero.
1817                          */
1818                         off_srcs[count] = dev->offset;
1819                         xor_srcs[count++] = dev->orig_page;
1820                 } else if (test_bit(R5_Wantdrain, &dev->flags)) {
1821                         off_srcs[count] = dev->offset;
1822                         xor_srcs[count++] = dev->page;
1823                 }
1824         }
1825
1826         init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1827                           ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1828         tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
1829                         RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1830
1831         return tx;
1832 }
1833
1834 static struct dma_async_tx_descriptor *
1835 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1836                 struct dma_async_tx_descriptor *tx)
1837 {
1838         struct page **blocks = to_addr_page(percpu, 0);
1839         unsigned int *offs = to_addr_offs(sh, percpu);
1840         int count;
1841         struct async_submit_ctl submit;
1842
1843         pr_debug("%s: stripe %llu\n", __func__,
1844                 (unsigned long long)sh->sector);
1845
1846         count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_WANT_DRAIN);
1847
1848         init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1849                           ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1850         tx = async_gen_syndrome(blocks, offs, count+2,
1851                         RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1852
1853         return tx;
1854 }
1855
1856 static struct dma_async_tx_descriptor *
1857 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1858 {
1859         struct r5conf *conf = sh->raid_conf;
1860         int disks = sh->disks;
1861         int i;
1862         struct stripe_head *head_sh = sh;
1863
1864         pr_debug("%s: stripe %llu\n", __func__,
1865                 (unsigned long long)sh->sector);
1866
1867         for (i = disks; i--; ) {
1868                 struct r5dev *dev;
1869                 struct bio *chosen;
1870
1871                 sh = head_sh;
1872                 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1873                         struct bio *wbi;
1874
1875 again:
1876                         dev = &sh->dev[i];
1877                         /*
1878                          * clear R5_InJournal, so when rewriting a page in
1879                          * journal, it is not skipped by r5l_log_stripe()
1880                          */
1881                         clear_bit(R5_InJournal, &dev->flags);
1882                         spin_lock_irq(&sh->stripe_lock);
1883                         chosen = dev->towrite;
1884                         dev->towrite = NULL;
1885                         sh->overwrite_disks = 0;
1886                         BUG_ON(dev->written);
1887                         wbi = dev->written = chosen;
1888                         spin_unlock_irq(&sh->stripe_lock);
1889                         WARN_ON(dev->page != dev->orig_page);
1890
1891                         while (wbi && wbi->bi_iter.bi_sector <
1892                                 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1893                                 if (wbi->bi_opf & REQ_FUA)
1894                                         set_bit(R5_WantFUA, &dev->flags);
1895                                 if (wbi->bi_opf & REQ_SYNC)
1896                                         set_bit(R5_SyncIO, &dev->flags);
1897                                 if (bio_op(wbi) == REQ_OP_DISCARD)
1898                                         set_bit(R5_Discard, &dev->flags);
1899                                 else {
1900                                         tx = async_copy_data(1, wbi, &dev->page,
1901                                                              dev->offset,
1902                                                              dev->sector, tx, sh,
1903                                                              r5c_is_writeback(conf->log));
1904                                         if (dev->page != dev->orig_page &&
1905                                             !r5c_is_writeback(conf->log)) {
1906                                                 set_bit(R5_SkipCopy, &dev->flags);
1907                                                 clear_bit(R5_UPTODATE, &dev->flags);
1908                                                 clear_bit(R5_OVERWRITE, &dev->flags);
1909                                         }
1910                                 }
1911                                 wbi = r5_next_bio(conf, wbi, dev->sector);
1912                         }
1913
1914                         if (head_sh->batch_head) {
1915                                 sh = list_first_entry(&sh->batch_list,
1916                                                       struct stripe_head,
1917                                                       batch_list);
1918                                 if (sh == head_sh)
1919                                         continue;
1920                                 goto again;
1921                         }
1922                 }
1923         }
1924
1925         return tx;
1926 }
1927
1928 static void ops_complete_reconstruct(void *stripe_head_ref)
1929 {
1930         struct stripe_head *sh = stripe_head_ref;
1931         int disks = sh->disks;
1932         int pd_idx = sh->pd_idx;
1933         int qd_idx = sh->qd_idx;
1934         int i;
1935         bool fua = false, sync = false, discard = false;
1936
1937         pr_debug("%s: stripe %llu\n", __func__,
1938                 (unsigned long long)sh->sector);
1939
1940         for (i = disks; i--; ) {
1941                 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1942                 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1943                 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1944         }
1945
1946         for (i = disks; i--; ) {
1947                 struct r5dev *dev = &sh->dev[i];
1948
1949                 if (dev->written || i == pd_idx || i == qd_idx) {
1950                         if (!discard && !test_bit(R5_SkipCopy, &dev->flags)) {
1951                                 set_bit(R5_UPTODATE, &dev->flags);
1952                                 if (test_bit(STRIPE_EXPAND_READY, &sh->state))
1953                                         set_bit(R5_Expanded, &dev->flags);
1954                         }
1955                         if (fua)
1956                                 set_bit(R5_WantFUA, &dev->flags);
1957                         if (sync)
1958                                 set_bit(R5_SyncIO, &dev->flags);
1959                 }
1960         }
1961
1962         if (sh->reconstruct_state == reconstruct_state_drain_run)
1963                 sh->reconstruct_state = reconstruct_state_drain_result;
1964         else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1965                 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1966         else {
1967                 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1968                 sh->reconstruct_state = reconstruct_state_result;
1969         }
1970
1971         set_bit(STRIPE_HANDLE, &sh->state);
1972         raid5_release_stripe(sh);
1973 }
1974
1975 static void
1976 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1977                      struct dma_async_tx_descriptor *tx)
1978 {
1979         int disks = sh->disks;
1980         struct page **xor_srcs;
1981         unsigned int *off_srcs;
1982         struct async_submit_ctl submit;
1983         int count, pd_idx = sh->pd_idx, i;
1984         struct page *xor_dest;
1985         unsigned int off_dest;
1986         int prexor = 0;
1987         unsigned long flags;
1988         int j = 0;
1989         struct stripe_head *head_sh = sh;
1990         int last_stripe;
1991
1992         pr_debug("%s: stripe %llu\n", __func__,
1993                 (unsigned long long)sh->sector);
1994
1995         for (i = 0; i < sh->disks; i++) {
1996                 if (pd_idx == i)
1997                         continue;
1998                 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1999                         break;
2000         }
2001         if (i >= sh->disks) {
2002                 atomic_inc(&sh->count);
2003                 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
2004                 ops_complete_reconstruct(sh);
2005                 return;
2006         }
2007 again:
2008         count = 0;
2009         xor_srcs = to_addr_page(percpu, j);
2010         off_srcs = to_addr_offs(sh, percpu);
2011         /* check if prexor is active which means only process blocks
2012          * that are part of a read-modify-write (written)
2013          */
2014         if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
2015                 prexor = 1;
2016                 off_dest = off_srcs[count] = sh->dev[pd_idx].offset;
2017                 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
2018                 for (i = disks; i--; ) {
2019                         struct r5dev *dev = &sh->dev[i];
2020                         if (head_sh->dev[i].written ||
2021                             test_bit(R5_InJournal, &head_sh->dev[i].flags)) {
2022                                 off_srcs[count] = dev->offset;
2023                                 xor_srcs[count++] = dev->page;
2024                         }
2025                 }
2026         } else {
2027                 xor_dest = sh->dev[pd_idx].page;
2028                 off_dest = sh->dev[pd_idx].offset;
2029                 for (i = disks; i--; ) {
2030                         struct r5dev *dev = &sh->dev[i];
2031                         if (i != pd_idx) {
2032                                 off_srcs[count] = dev->offset;
2033                                 xor_srcs[count++] = dev->page;
2034                         }
2035                 }
2036         }
2037
2038         /* 1/ if we prexor'd then the dest is reused as a source
2039          * 2/ if we did not prexor then we are redoing the parity
2040          * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
2041          * for the synchronous xor case
2042          */
2043         last_stripe = !head_sh->batch_head ||
2044                 list_first_entry(&sh->batch_list,
2045                                  struct stripe_head, batch_list) == head_sh;
2046         if (last_stripe) {
2047                 flags = ASYNC_TX_ACK |
2048                         (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
2049
2050                 atomic_inc(&head_sh->count);
2051                 init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
2052                                   to_addr_conv(sh, percpu, j));
2053         } else {
2054                 flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
2055                 init_async_submit(&submit, flags, tx, NULL, NULL,
2056                                   to_addr_conv(sh, percpu, j));
2057         }
2058
2059         if (unlikely(count == 1))
2060                 tx = async_memcpy(xor_dest, xor_srcs[0], off_dest, off_srcs[0],
2061                                 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
2062         else
2063                 tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
2064                                 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
2065         if (!last_stripe) {
2066                 j++;
2067                 sh = list_first_entry(&sh->batch_list, struct stripe_head,
2068                                       batch_list);
2069                 goto again;
2070         }
2071 }
2072
2073 static void
2074 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
2075                      struct dma_async_tx_descriptor *tx)
2076 {
2077         struct async_submit_ctl submit;
2078         struct page **blocks;
2079         unsigned int *offs;
2080         int count, i, j = 0;
2081         struct stripe_head *head_sh = sh;
2082         int last_stripe;
2083         int synflags;
2084         unsigned long txflags;
2085
2086         pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
2087
2088         for (i = 0; i < sh->disks; i++) {
2089                 if (sh->pd_idx == i || sh->qd_idx == i)
2090                         continue;
2091                 if (!test_bit(R5_Discard, &sh->dev[i].flags))
2092                         break;
2093         }
2094         if (i >= sh->disks) {
2095                 atomic_inc(&sh->count);
2096                 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
2097                 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
2098                 ops_complete_reconstruct(sh);
2099                 return;
2100         }
2101
2102 again:
2103         blocks = to_addr_page(percpu, j);
2104         offs = to_addr_offs(sh, percpu);
2105
2106         if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
2107                 synflags = SYNDROME_SRC_WRITTEN;
2108                 txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
2109         } else {
2110                 synflags = SYNDROME_SRC_ALL;
2111                 txflags = ASYNC_TX_ACK;
2112         }
2113
2114         count = set_syndrome_sources(blocks, offs, sh, synflags);
2115         last_stripe = !head_sh->batch_head ||
2116                 list_first_entry(&sh->batch_list,
2117                                  struct stripe_head, batch_list) == head_sh;
2118
2119         if (last_stripe) {
2120                 atomic_inc(&head_sh->count);
2121                 init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
2122                                   head_sh, to_addr_conv(sh, percpu, j));
2123         } else
2124                 init_async_submit(&submit, 0, tx, NULL, NULL,
2125                                   to_addr_conv(sh, percpu, j));
2126         tx = async_gen_syndrome(blocks, offs, count+2,
2127                         RAID5_STRIPE_SIZE(sh->raid_conf),  &submit);
2128         if (!last_stripe) {
2129                 j++;
2130                 sh = list_first_entry(&sh->batch_list, struct stripe_head,
2131                                       batch_list);
2132                 goto again;
2133         }
2134 }
2135
2136 static void ops_complete_check(void *stripe_head_ref)
2137 {
2138         struct stripe_head *sh = stripe_head_ref;
2139
2140         pr_debug("%s: stripe %llu\n", __func__,
2141                 (unsigned long long)sh->sector);
2142
2143         sh->check_state = check_state_check_result;
2144         set_bit(STRIPE_HANDLE, &sh->state);
2145         raid5_release_stripe(sh);
2146 }
2147
2148 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
2149 {
2150         int disks = sh->disks;
2151         int pd_idx = sh->pd_idx;
2152         int qd_idx = sh->qd_idx;
2153         struct page *xor_dest;
2154         unsigned int off_dest;
2155         struct page **xor_srcs = to_addr_page(percpu, 0);
2156         unsigned int *off_srcs = to_addr_offs(sh, percpu);
2157         struct dma_async_tx_descriptor *tx;
2158         struct async_submit_ctl submit;
2159         int count;
2160         int i;
2161
2162         pr_debug("%s: stripe %llu\n", __func__,
2163                 (unsigned long long)sh->sector);
2164
2165         BUG_ON(sh->batch_head);
2166         count = 0;
2167         xor_dest = sh->dev[pd_idx].page;
2168         off_dest = sh->dev[pd_idx].offset;
2169         off_srcs[count] = off_dest;
2170         xor_srcs[count++] = xor_dest;
2171         for (i = disks; i--; ) {
2172                 if (i == pd_idx || i == qd_idx)
2173                         continue;
2174                 off_srcs[count] = sh->dev[i].offset;
2175                 xor_srcs[count++] = sh->dev[i].page;
2176         }
2177
2178         init_async_submit(&submit, 0, NULL, NULL, NULL,
2179                           to_addr_conv(sh, percpu, 0));
2180         tx = async_xor_val_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
2181                            RAID5_STRIPE_SIZE(sh->raid_conf),
2182                            &sh->ops.zero_sum_result, &submit);
2183
2184         atomic_inc(&sh->count);
2185         init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
2186         tx = async_trigger_callback(&submit);
2187 }
2188
2189 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
2190 {
2191         struct page **srcs = to_addr_page(percpu, 0);
2192         unsigned int *offs = to_addr_offs(sh, percpu);
2193         struct async_submit_ctl submit;
2194         int count;
2195
2196         pr_debug("%s: stripe %llu checkp: %d\n", __func__,
2197                 (unsigned long long)sh->sector, checkp);
2198
2199         BUG_ON(sh->batch_head);
2200         count = set_syndrome_sources(srcs, offs, sh, SYNDROME_SRC_ALL);
2201         if (!checkp)
2202                 srcs[count] = NULL;
2203
2204         atomic_inc(&sh->count);
2205         init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
2206                           sh, to_addr_conv(sh, percpu, 0));
2207         async_syndrome_val(srcs, offs, count+2,
2208                            RAID5_STRIPE_SIZE(sh->raid_conf),
2209                            &sh->ops.zero_sum_result, percpu->spare_page, 0, &submit);
2210 }
2211
2212 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
2213 {
2214         int overlap_clear = 0, i, disks = sh->disks;
2215         struct dma_async_tx_descriptor *tx = NULL;
2216         struct r5conf *conf = sh->raid_conf;
2217         int level = conf->level;
2218         struct raid5_percpu *percpu;
2219         unsigned long cpu;
2220
2221         cpu = get_cpu();
2222         percpu = per_cpu_ptr(conf->percpu, cpu);
2223         if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
2224                 ops_run_biofill(sh);
2225                 overlap_clear++;
2226         }
2227
2228         if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
2229                 if (level < 6)
2230                         tx = ops_run_compute5(sh, percpu);
2231                 else {
2232                         if (sh->ops.target2 < 0 || sh->ops.target < 0)
2233                                 tx = ops_run_compute6_1(sh, percpu);
2234                         else
2235                                 tx = ops_run_compute6_2(sh, percpu);
2236                 }
2237                 /* terminate the chain if reconstruct is not set to be run */
2238                 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
2239                         async_tx_ack(tx);
2240         }
2241
2242         if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
2243                 if (level < 6)
2244                         tx = ops_run_prexor5(sh, percpu, tx);
2245                 else
2246                         tx = ops_run_prexor6(sh, percpu, tx);
2247         }
2248
2249         if (test_bit(STRIPE_OP_PARTIAL_PARITY, &ops_request))
2250                 tx = ops_run_partial_parity(sh, percpu, tx);
2251
2252         if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
2253                 tx = ops_run_biodrain(sh, tx);
2254                 overlap_clear++;
2255         }
2256
2257         if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
2258                 if (level < 6)
2259                         ops_run_reconstruct5(sh, percpu, tx);
2260                 else
2261                         ops_run_reconstruct6(sh, percpu, tx);
2262         }
2263
2264         if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
2265                 if (sh->check_state == check_state_run)
2266                         ops_run_check_p(sh, percpu);
2267                 else if (sh->check_state == check_state_run_q)
2268                         ops_run_check_pq(sh, percpu, 0);
2269                 else if (sh->check_state == check_state_run_pq)
2270                         ops_run_check_pq(sh, percpu, 1);
2271                 else
2272                         BUG();
2273         }
2274
2275         if (overlap_clear && !sh->batch_head)
2276                 for (i = disks; i--; ) {
2277                         struct r5dev *dev = &sh->dev[i];
2278                         if (test_and_clear_bit(R5_Overlap, &dev->flags))
2279                                 wake_up(&sh->raid_conf->wait_for_overlap);
2280                 }
2281         put_cpu();
2282 }
2283
2284 static void free_stripe(struct kmem_cache *sc, struct stripe_head *sh)
2285 {
2286 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2287         kfree(sh->pages);
2288 #endif
2289         if (sh->ppl_page)
2290                 __free_page(sh->ppl_page);
2291         kmem_cache_free(sc, sh);
2292 }
2293
2294 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp,
2295         int disks, struct r5conf *conf)
2296 {
2297         struct stripe_head *sh;
2298         int i;
2299
2300         sh = kmem_cache_zalloc(sc, gfp);
2301         if (sh) {
2302                 spin_lock_init(&sh->stripe_lock);
2303                 spin_lock_init(&sh->batch_lock);
2304                 INIT_LIST_HEAD(&sh->batch_list);
2305                 INIT_LIST_HEAD(&sh->lru);
2306                 INIT_LIST_HEAD(&sh->r5c);
2307                 INIT_LIST_HEAD(&sh->log_list);
2308                 atomic_set(&sh->count, 1);
2309                 sh->raid_conf = conf;
2310                 sh->log_start = MaxSector;
2311                 for (i = 0; i < disks; i++) {
2312                         struct r5dev *dev = &sh->dev[i];
2313
2314                         bio_init(&dev->req, &dev->vec, 1);
2315                         bio_init(&dev->rreq, &dev->rvec, 1);
2316                 }
2317
2318                 if (raid5_has_ppl(conf)) {
2319                         sh->ppl_page = alloc_page(gfp);
2320                         if (!sh->ppl_page) {
2321                                 free_stripe(sc, sh);
2322                                 return NULL;
2323                         }
2324                 }
2325 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2326                 if (init_stripe_shared_pages(sh, conf, disks)) {
2327                         free_stripe(sc, sh);
2328                         return NULL;
2329                 }
2330 #endif
2331         }
2332         return sh;
2333 }
2334 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2335 {
2336         struct stripe_head *sh;
2337
2338         sh = alloc_stripe(conf->slab_cache, gfp, conf->pool_size, conf);
2339         if (!sh)
2340                 return 0;
2341
2342         if (grow_buffers(sh, gfp)) {
2343                 shrink_buffers(sh);
2344                 free_stripe(conf->slab_cache, sh);
2345                 return 0;
2346         }
2347         sh->hash_lock_index =
2348                 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2349         /* we just created an active stripe so... */
2350         atomic_inc(&conf->active_stripes);
2351
2352         raid5_release_stripe(sh);
2353         conf->max_nr_stripes++;
2354         return 1;
2355 }
2356
2357 static int grow_stripes(struct r5conf *conf, int num)
2358 {
2359         struct kmem_cache *sc;
2360         size_t namelen = sizeof(conf->cache_name[0]);
2361         int devs = max(conf->raid_disks, conf->previous_raid_disks);
2362
2363         if (conf->mddev->gendisk)
2364                 snprintf(conf->cache_name[0], namelen,
2365                         "raid%d-%s", conf->level, mdname(conf->mddev));
2366         else
2367                 snprintf(conf->cache_name[0], namelen,
2368                         "raid%d-%p", conf->level, conf->mddev);
2369         snprintf(conf->cache_name[1], namelen, "%.27s-alt", conf->cache_name[0]);
2370
2371         conf->active_name = 0;
2372         sc = kmem_cache_create(conf->cache_name[conf->active_name],
2373                                sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2374                                0, 0, NULL);
2375         if (!sc)
2376                 return 1;
2377         conf->slab_cache = sc;
2378         conf->pool_size = devs;
2379         while (num--)
2380                 if (!grow_one_stripe(conf, GFP_KERNEL))
2381                         return 1;
2382
2383         return 0;
2384 }
2385
2386 /**
2387  * scribble_alloc - allocate percpu scribble buffer for required size
2388  *                  of the scribble region
2389  * @percpu: from for_each_present_cpu() of the caller
2390  * @num: total number of disks in the array
2391  * @cnt: scribble objs count for required size of the scribble region
2392  *
2393  * The scribble buffer size must be enough to contain:
2394  * 1/ a struct page pointer for each device in the array +2
2395  * 2/ room to convert each entry in (1) to its corresponding dma
2396  *    (dma_map_page()) or page (page_address()) address.
2397  *
2398  * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2399  * calculate over all devices (not just the data blocks), using zeros in place
2400  * of the P and Q blocks.
2401  */
2402 static int scribble_alloc(struct raid5_percpu *percpu,
2403                           int num, int cnt)
2404 {
2405         size_t obj_size =
2406                 sizeof(struct page *) * (num + 2) +
2407                 sizeof(addr_conv_t) * (num + 2) +
2408                 sizeof(unsigned int) * (num + 2);
2409         void *scribble;
2410
2411         /*
2412          * If here is in raid array suspend context, it is in memalloc noio
2413          * context as well, there is no potential recursive memory reclaim
2414          * I/Os with the GFP_KERNEL flag.
2415          */
2416         scribble = kvmalloc_array(cnt, obj_size, GFP_KERNEL);
2417         if (!scribble)
2418                 return -ENOMEM;
2419
2420         kvfree(percpu->scribble);
2421
2422         percpu->scribble = scribble;
2423         percpu->scribble_obj_size = obj_size;
2424         return 0;
2425 }
2426
2427 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2428 {
2429         unsigned long cpu;
2430         int err = 0;
2431
2432         /*
2433          * Never shrink. And mddev_suspend() could deadlock if this is called
2434          * from raid5d. In that case, scribble_disks and scribble_sectors
2435          * should equal to new_disks and new_sectors
2436          */
2437         if (conf->scribble_disks >= new_disks &&
2438             conf->scribble_sectors >= new_sectors)
2439                 return 0;
2440         mddev_suspend(conf->mddev);
2441         get_online_cpus();
2442
2443         for_each_present_cpu(cpu) {
2444                 struct raid5_percpu *percpu;
2445
2446                 percpu = per_cpu_ptr(conf->percpu, cpu);
2447                 err = scribble_alloc(percpu, new_disks,
2448                                      new_sectors / RAID5_STRIPE_SECTORS(conf));
2449                 if (err)
2450                         break;
2451         }
2452
2453         put_online_cpus();
2454         mddev_resume(conf->mddev);
2455         if (!err) {
2456                 conf->scribble_disks = new_disks;
2457                 conf->scribble_sectors = new_sectors;
2458         }
2459         return err;
2460 }
2461
2462 static int resize_stripes(struct r5conf *conf, int newsize)
2463 {
2464         /* Make all the stripes able to hold 'newsize' devices.
2465          * New slots in each stripe get 'page' set to a new page.
2466          *
2467          * This happens in stages:
2468          * 1/ create a new kmem_cache and allocate the required number of
2469          *    stripe_heads.
2470          * 2/ gather all the old stripe_heads and transfer the pages across
2471          *    to the new stripe_heads.  This will have the side effect of
2472          *    freezing the array as once all stripe_heads have been collected,
2473          *    no IO will be possible.  Old stripe heads are freed once their
2474          *    pages have been transferred over, and the old kmem_cache is
2475          *    freed when all stripes are done.
2476          * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
2477          *    we simple return a failure status - no need to clean anything up.
2478          * 4/ allocate new pages for the new slots in the new stripe_heads.
2479          *    If this fails, we don't bother trying the shrink the
2480          *    stripe_heads down again, we just leave them as they are.
2481          *    As each stripe_head is processed the new one is released into
2482          *    active service.
2483          *
2484          * Once step2 is started, we cannot afford to wait for a write,
2485          * so we use GFP_NOIO allocations.
2486          */
2487         struct stripe_head *osh, *nsh;
2488         LIST_HEAD(newstripes);
2489         struct disk_info *ndisks;
2490         int err = 0;
2491         struct kmem_cache *sc;
2492         int i;
2493         int hash, cnt;
2494
2495         md_allow_write(conf->mddev);
2496
2497         /* Step 1 */
2498         sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2499                                sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2500                                0, 0, NULL);
2501         if (!sc)
2502                 return -ENOMEM;
2503
2504         /* Need to ensure auto-resizing doesn't interfere */
2505         mutex_lock(&conf->cache_size_mutex);
2506
2507         for (i = conf->max_nr_stripes; i; i--) {
2508                 nsh = alloc_stripe(sc, GFP_KERNEL, newsize, conf);
2509                 if (!nsh)
2510                         break;
2511
2512                 list_add(&nsh->lru, &newstripes);
2513         }
2514         if (i) {
2515                 /* didn't get enough, give up */
2516                 while (!list_empty(&newstripes)) {
2517                         nsh = list_entry(newstripes.next, struct stripe_head, lru);
2518                         list_del(&nsh->lru);
2519                         free_stripe(sc, nsh);
2520                 }
2521                 kmem_cache_destroy(sc);
2522                 mutex_unlock(&conf->cache_size_mutex);
2523                 return -ENOMEM;
2524         }
2525         /* Step 2 - Must use GFP_NOIO now.
2526          * OK, we have enough stripes, start collecting inactive
2527          * stripes and copying them over
2528          */
2529         hash = 0;
2530         cnt = 0;
2531         list_for_each_entry(nsh, &newstripes, lru) {
2532                 lock_device_hash_lock(conf, hash);
2533                 wait_event_cmd(conf->wait_for_stripe,
2534                                     !list_empty(conf->inactive_list + hash),
2535                                     unlock_device_hash_lock(conf, hash),
2536                                     lock_device_hash_lock(conf, hash));
2537                 osh = get_free_stripe(conf, hash);
2538                 unlock_device_hash_lock(conf, hash);
2539
2540 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2541         for (i = 0; i < osh->nr_pages; i++) {
2542                 nsh->pages[i] = osh->pages[i];
2543                 osh->pages[i] = NULL;
2544         }
2545 #endif
2546                 for(i=0; i<conf->pool_size; i++) {
2547                         nsh->dev[i].page = osh->dev[i].page;
2548                         nsh->dev[i].orig_page = osh->dev[i].page;
2549                         nsh->dev[i].offset = osh->dev[i].offset;
2550                 }
2551                 nsh->hash_lock_index = hash;
2552                 free_stripe(conf->slab_cache, osh);
2553                 cnt++;
2554                 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2555                     !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2556                         hash++;
2557                         cnt = 0;
2558                 }
2559         }
2560         kmem_cache_destroy(conf->slab_cache);
2561
2562         /* Step 3.
2563          * At this point, we are holding all the stripes so the array
2564          * is completely stalled, so now is a good time to resize
2565          * conf->disks and the scribble region
2566          */
2567         ndisks = kcalloc(newsize, sizeof(struct disk_info), GFP_NOIO);
2568         if (ndisks) {
2569                 for (i = 0; i < conf->pool_size; i++)
2570                         ndisks[i] = conf->disks[i];
2571
2572                 for (i = conf->pool_size; i < newsize; i++) {
2573                         ndisks[i].extra_page = alloc_page(GFP_NOIO);
2574                         if (!ndisks[i].extra_page)
2575                                 err = -ENOMEM;
2576                 }
2577
2578                 if (err) {
2579                         for (i = conf->pool_size; i < newsize; i++)
2580                                 if (ndisks[i].extra_page)
2581                                         put_page(ndisks[i].extra_page);
2582                         kfree(ndisks);
2583                 } else {
2584                         kfree(conf->disks);
2585                         conf->disks = ndisks;
2586                 }
2587         } else
2588                 err = -ENOMEM;
2589
2590         conf->slab_cache = sc;
2591         conf->active_name = 1-conf->active_name;
2592
2593         /* Step 4, return new stripes to service */
2594         while(!list_empty(&newstripes)) {
2595                 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2596                 list_del_init(&nsh->lru);
2597
2598 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2599                 for (i = 0; i < nsh->nr_pages; i++) {
2600                         if (nsh->pages[i])
2601                                 continue;
2602                         nsh->pages[i] = alloc_page(GFP_NOIO);
2603                         if (!nsh->pages[i])
2604                                 err = -ENOMEM;
2605                 }
2606
2607                 for (i = conf->raid_disks; i < newsize; i++) {
2608                         if (nsh->dev[i].page)
2609                                 continue;
2610                         nsh->dev[i].page = raid5_get_dev_page(nsh, i);
2611                         nsh->dev[i].orig_page = nsh->dev[i].page;
2612                         nsh->dev[i].offset = raid5_get_page_offset(nsh, i);
2613                 }
2614 #else
2615                 for (i=conf->raid_disks; i < newsize; i++)
2616                         if (nsh->dev[i].page == NULL) {
2617                                 struct page *p = alloc_page(GFP_NOIO);
2618                                 nsh->dev[i].page = p;
2619                                 nsh->dev[i].orig_page = p;
2620                                 nsh->dev[i].offset = 0;
2621                                 if (!p)
2622                                         err = -ENOMEM;
2623                         }
2624 #endif
2625                 raid5_release_stripe(nsh);
2626         }
2627         /* critical section pass, GFP_NOIO no longer needed */
2628
2629         if (!err)
2630                 conf->pool_size = newsize;
2631         mutex_unlock(&conf->cache_size_mutex);
2632
2633         return err;
2634 }
2635
2636 static int drop_one_stripe(struct r5conf *conf)
2637 {
2638         struct stripe_head *sh;
2639         int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2640
2641         spin_lock_irq(conf->hash_locks + hash);
2642         sh = get_free_stripe(conf, hash);
2643         spin_unlock_irq(conf->hash_locks + hash);
2644         if (!sh)
2645                 return 0;
2646         BUG_ON(atomic_read(&sh->count));
2647         shrink_buffers(sh);
2648         free_stripe(conf->slab_cache, sh);
2649         atomic_dec(&conf->active_stripes);
2650         conf->max_nr_stripes--;
2651         return 1;
2652 }
2653
2654 static void shrink_stripes(struct r5conf *conf)
2655 {
2656         while (conf->max_nr_stripes &&
2657                drop_one_stripe(conf))
2658                 ;
2659
2660         kmem_cache_destroy(conf->slab_cache);
2661         conf->slab_cache = NULL;
2662 }
2663
2664 static void raid5_end_read_request(struct bio * bi)
2665 {
2666         struct stripe_head *sh = bi->bi_private;
2667         struct r5conf *conf = sh->raid_conf;
2668         int disks = sh->disks, i;
2669         char b[BDEVNAME_SIZE];
2670         struct md_rdev *rdev = NULL;
2671         sector_t s;
2672
2673         for (i=0 ; i<disks; i++)
2674                 if (bi == &sh->dev[i].req)
2675                         break;
2676
2677         pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2678                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2679                 bi->bi_status);
2680         if (i == disks) {
2681                 bio_reset(bi);
2682                 BUG();
2683                 return;
2684         }
2685         if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2686                 /* If replacement finished while this request was outstanding,
2687                  * 'replacement' might be NULL already.
2688                  * In that case it moved down to 'rdev'.
2689                  * rdev is not removed until all requests are finished.
2690                  */
2691                 rdev = conf->disks[i].replacement;
2692         if (!rdev)
2693                 rdev = conf->disks[i].rdev;
2694
2695         if (use_new_offset(conf, sh))
2696                 s = sh->sector + rdev->new_data_offset;
2697         else
2698                 s = sh->sector + rdev->data_offset;
2699         if (!bi->bi_status) {
2700                 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2701                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2702                         /* Note that this cannot happen on a
2703                          * replacement device.  We just fail those on
2704                          * any error
2705                          */
2706                         pr_info_ratelimited(
2707                                 "md/raid:%s: read error corrected (%lu sectors at %llu on %s)\n",
2708                                 mdname(conf->mddev), RAID5_STRIPE_SECTORS(conf),
2709                                 (unsigned long long)s,
2710                                 bdevname(rdev->bdev, b));
2711                         atomic_add(RAID5_STRIPE_SECTORS(conf), &rdev->corrected_errors);
2712                         clear_bit(R5_ReadError, &sh->dev[i].flags);
2713                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
2714                 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2715                         clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2716
2717                 if (test_bit(R5_InJournal, &sh->dev[i].flags))
2718                         /*
2719                          * end read for a page in journal, this
2720                          * must be preparing for prexor in rmw
2721                          */
2722                         set_bit(R5_OrigPageUPTDODATE, &sh->dev[i].flags);
2723
2724                 if (atomic_read(&rdev->read_errors))
2725                         atomic_set(&rdev->read_errors, 0);
2726         } else {
2727                 const char *bdn = bdevname(rdev->bdev, b);
2728                 int retry = 0;
2729                 int set_bad = 0;
2730
2731                 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2732                 if (!(bi->bi_status == BLK_STS_PROTECTION))
2733                         atomic_inc(&rdev->read_errors);
2734                 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2735                         pr_warn_ratelimited(
2736                                 "md/raid:%s: read error on replacement device (sector %llu on %s).\n",
2737                                 mdname(conf->mddev),
2738                                 (unsigned long long)s,
2739                                 bdn);
2740                 else if (conf->mddev->degraded >= conf->max_degraded) {
2741                         set_bad = 1;
2742                         pr_warn_ratelimited(
2743                                 "md/raid:%s: read error not correctable (sector %llu on %s).\n",
2744                                 mdname(conf->mddev),
2745                                 (unsigned long long)s,
2746                                 bdn);
2747                 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2748                         /* Oh, no!!! */
2749                         set_bad = 1;
2750                         pr_warn_ratelimited(
2751                                 "md/raid:%s: read error NOT corrected!! (sector %llu on %s).\n",
2752                                 mdname(conf->mddev),
2753                                 (unsigned long long)s,
2754                                 bdn);
2755                 } else if (atomic_read(&rdev->read_errors)
2756                          > conf->max_nr_stripes) {
2757                         if (!test_bit(Faulty, &rdev->flags)) {
2758                                 pr_warn("md/raid:%s: %d read_errors > %d stripes\n",
2759                                     mdname(conf->mddev),
2760                                     atomic_read(&rdev->read_errors),
2761                                     conf->max_nr_stripes);
2762                                 pr_warn("md/raid:%s: Too many read errors, failing device %s.\n",
2763                                     mdname(conf->mddev), bdn);
2764                         }
2765                 } else
2766                         retry = 1;
2767                 if (set_bad && test_bit(In_sync, &rdev->flags)
2768                     && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2769                         retry = 1;
2770                 if (retry)
2771                         if (sh->qd_idx >= 0 && sh->pd_idx == i)
2772                                 set_bit(R5_ReadError, &sh->dev[i].flags);
2773                         else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2774                                 set_bit(R5_ReadError, &sh->dev[i].flags);
2775                                 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2776                         } else
2777                                 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2778                 else {
2779                         clear_bit(R5_ReadError, &sh->dev[i].flags);
2780                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
2781                         if (!(set_bad
2782                               && test_bit(In_sync, &rdev->flags)
2783                               && rdev_set_badblocks(
2784                                       rdev, sh->sector, RAID5_STRIPE_SECTORS(conf), 0)))
2785                                 md_error(conf->mddev, rdev);
2786                 }
2787         }
2788         rdev_dec_pending(rdev, conf->mddev);
2789         bio_reset(bi);
2790         clear_bit(R5_LOCKED, &sh->dev[i].flags);
2791         set_bit(STRIPE_HANDLE, &sh->state);
2792         raid5_release_stripe(sh);
2793 }
2794
2795 static void raid5_end_write_request(struct bio *bi)
2796 {
2797         struct stripe_head *sh = bi->bi_private;
2798         struct r5conf *conf = sh->raid_conf;
2799         int disks = sh->disks, i;
2800         struct md_rdev *rdev;
2801         sector_t first_bad;
2802         int bad_sectors;
2803         int replacement = 0;
2804
2805         for (i = 0 ; i < disks; i++) {
2806                 if (bi == &sh->dev[i].req) {
2807                         rdev = conf->disks[i].rdev;
2808                         break;
2809                 }
2810                 if (bi == &sh->dev[i].rreq) {
2811                         rdev = conf->disks[i].replacement;
2812                         if (rdev)
2813                                 replacement = 1;
2814                         else
2815                                 /* rdev was removed and 'replacement'
2816                                  * replaced it.  rdev is not removed
2817                                  * until all requests are finished.
2818                                  */
2819                                 rdev = conf->disks[i].rdev;
2820                         break;
2821                 }
2822         }
2823         pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2824                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2825                 bi->bi_status);
2826         if (i == disks) {
2827                 bio_reset(bi);
2828                 BUG();
2829                 return;
2830         }
2831
2832         if (replacement) {
2833                 if (bi->bi_status)
2834                         md_error(conf->mddev, rdev);
2835                 else if (is_badblock(rdev, sh->sector,
2836                                      RAID5_STRIPE_SECTORS(conf),
2837                                      &first_bad, &bad_sectors))
2838                         set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2839         } else {
2840                 if (bi->bi_status) {
2841                         set_bit(STRIPE_DEGRADED, &sh->state);
2842                         set_bit(WriteErrorSeen, &rdev->flags);
2843                         set_bit(R5_WriteError, &sh->dev[i].flags);
2844                         if (!test_and_set_bit(WantReplacement, &rdev->flags))
2845                                 set_bit(MD_RECOVERY_NEEDED,
2846                                         &rdev->mddev->recovery);
2847                 } else if (is_badblock(rdev, sh->sector,
2848                                        RAID5_STRIPE_SECTORS(conf),
2849                                        &first_bad, &bad_sectors)) {
2850                         set_bit(R5_MadeGood, &sh->dev[i].flags);
2851                         if (test_bit(R5_ReadError, &sh->dev[i].flags))
2852                                 /* That was a successful write so make
2853                                  * sure it looks like we already did
2854                                  * a re-write.
2855                                  */
2856                                 set_bit(R5_ReWrite, &sh->dev[i].flags);
2857                 }
2858         }
2859         rdev_dec_pending(rdev, conf->mddev);
2860
2861         if (sh->batch_head && bi->bi_status && !replacement)
2862                 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2863
2864         bio_reset(bi);
2865         if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2866                 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2867         set_bit(STRIPE_HANDLE, &sh->state);
2868
2869         if (sh->batch_head && sh != sh->batch_head)
2870                 raid5_release_stripe(sh->batch_head);
2871         raid5_release_stripe(sh);
2872 }
2873
2874 static void raid5_error(struct mddev *mddev, struct md_rdev *rdev)
2875 {
2876         char b[BDEVNAME_SIZE];
2877         struct r5conf *conf = mddev->private;
2878         unsigned long flags;
2879         pr_debug("raid456: error called\n");
2880
2881         pr_crit("md/raid:%s: Disk failure on %s, disabling device.\n",
2882                 mdname(mddev), bdevname(rdev->bdev, b));
2883
2884         spin_lock_irqsave(&conf->device_lock, flags);
2885         set_bit(Faulty, &rdev->flags);
2886         clear_bit(In_sync, &rdev->flags);
2887         mddev->degraded = raid5_calc_degraded(conf);
2888
2889         if (has_failed(conf)) {
2890                 set_bit(MD_BROKEN, &conf->mddev->flags);
2891                 conf->recovery_disabled = mddev->recovery_disabled;
2892
2893                 pr_crit("md/raid:%s: Cannot continue operation (%d/%d failed).\n",
2894                         mdname(mddev), mddev->degraded, conf->raid_disks);
2895         } else {
2896                 pr_crit("md/raid:%s: Operation continuing on %d devices.\n",
2897                         mdname(mddev), conf->raid_disks - mddev->degraded);
2898         }
2899
2900         spin_unlock_irqrestore(&conf->device_lock, flags);
2901         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2902
2903         set_bit(Blocked, &rdev->flags);
2904         set_mask_bits(&mddev->sb_flags, 0,
2905                       BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
2906         r5c_update_on_rdev_error(mddev, rdev);
2907 }
2908
2909 /*
2910  * Input: a 'big' sector number,
2911  * Output: index of the data and parity disk, and the sector # in them.
2912  */
2913 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2914                               int previous, int *dd_idx,
2915                               struct stripe_head *sh)
2916 {
2917         sector_t stripe, stripe2;
2918         sector_t chunk_number;
2919         unsigned int chunk_offset;
2920         int pd_idx, qd_idx;
2921         int ddf_layout = 0;
2922         sector_t new_sector;
2923         int algorithm = previous ? conf->prev_algo
2924                                  : conf->algorithm;
2925         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2926                                          : conf->chunk_sectors;
2927         int raid_disks = previous ? conf->previous_raid_disks
2928                                   : conf->raid_disks;
2929         int data_disks = raid_disks - conf->max_degraded;
2930
2931         /* First compute the information on this sector */
2932
2933         /*
2934          * Compute the chunk number and the sector offset inside the chunk
2935          */
2936         chunk_offset = sector_div(r_sector, sectors_per_chunk);
2937         chunk_number = r_sector;
2938
2939         /*
2940          * Compute the stripe number
2941          */
2942         stripe = chunk_number;
2943         *dd_idx = sector_div(stripe, data_disks);
2944         stripe2 = stripe;
2945         /*
2946          * Select the parity disk based on the user selected algorithm.
2947          */
2948         pd_idx = qd_idx = -1;
2949         switch(conf->level) {
2950         case 4:
2951                 pd_idx = data_disks;
2952                 break;
2953         case 5:
2954                 switch (algorithm) {
2955                 case ALGORITHM_LEFT_ASYMMETRIC:
2956                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
2957                         if (*dd_idx >= pd_idx)
2958                                 (*dd_idx)++;
2959                         break;
2960                 case ALGORITHM_RIGHT_ASYMMETRIC:
2961                         pd_idx = sector_div(stripe2, raid_disks);
2962                         if (*dd_idx >= pd_idx)
2963                                 (*dd_idx)++;
2964                         break;
2965                 case ALGORITHM_LEFT_SYMMETRIC:
2966                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
2967                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2968                         break;
2969                 case ALGORITHM_RIGHT_SYMMETRIC:
2970                         pd_idx = sector_div(stripe2, raid_disks);
2971                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2972                         break;
2973                 case ALGORITHM_PARITY_0:
2974                         pd_idx = 0;
2975                         (*dd_idx)++;
2976                         break;
2977                 case ALGORITHM_PARITY_N:
2978                         pd_idx = data_disks;
2979                         break;
2980                 default:
2981                         BUG();
2982                 }
2983                 break;
2984         case 6:
2985
2986                 switch (algorithm) {
2987                 case ALGORITHM_LEFT_ASYMMETRIC:
2988                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2989                         qd_idx = pd_idx + 1;
2990                         if (pd_idx == raid_disks-1) {
2991                                 (*dd_idx)++;    /* Q D D D P */
2992                                 qd_idx = 0;
2993                         } else if (*dd_idx >= pd_idx)
2994                                 (*dd_idx) += 2; /* D D P Q D */
2995                         break;
2996                 case ALGORITHM_RIGHT_ASYMMETRIC:
2997                         pd_idx = sector_div(stripe2, raid_disks);
2998                         qd_idx = pd_idx + 1;
2999                         if (pd_idx == raid_disks-1) {
3000                                 (*dd_idx)++;    /* Q D D D P */
3001                                 qd_idx = 0;
3002                         } else if (*dd_idx >= pd_idx)
3003                                 (*dd_idx) += 2; /* D D P Q D */
3004                         break;
3005                 case ALGORITHM_LEFT_SYMMETRIC:
3006                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3007                         qd_idx = (pd_idx + 1) % raid_disks;
3008                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
3009                         break;
3010                 case ALGORITHM_RIGHT_SYMMETRIC:
3011                         pd_idx = sector_div(stripe2, raid_disks);
3012                         qd_idx = (pd_idx + 1) % raid_disks;
3013                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
3014                         break;
3015
3016                 case ALGORITHM_PARITY_0:
3017                         pd_idx = 0;
3018                         qd_idx = 1;
3019                         (*dd_idx) += 2;
3020                         break;
3021                 case ALGORITHM_PARITY_N:
3022                         pd_idx = data_disks;
3023                         qd_idx = data_disks + 1;
3024                         break;
3025
3026                 case ALGORITHM_ROTATING_ZERO_RESTART:
3027                         /* Exactly the same as RIGHT_ASYMMETRIC, but or
3028                          * of blocks for computing Q is different.
3029                          */
3030                         pd_idx = sector_div(stripe2, raid_disks);
3031                         qd_idx = pd_idx + 1;
3032                         if (pd_idx == raid_disks-1) {
3033                                 (*dd_idx)++;    /* Q D D D P */
3034                                 qd_idx = 0;
3035                         } else if (*dd_idx >= pd_idx)
3036                                 (*dd_idx) += 2; /* D D P Q D */
3037                         ddf_layout = 1;
3038                         break;
3039
3040                 case ALGORITHM_ROTATING_N_RESTART:
3041                         /* Same a left_asymmetric, by first stripe is
3042                          * D D D P Q  rather than
3043                          * Q D D D P
3044                          */
3045                         stripe2 += 1;
3046                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3047                         qd_idx = pd_idx + 1;
3048                         if (pd_idx == raid_disks-1) {
3049                                 (*dd_idx)++;    /* Q D D D P */
3050                                 qd_idx = 0;
3051                         } else if (*dd_idx >= pd_idx)
3052                                 (*dd_idx) += 2; /* D D P Q D */
3053                         ddf_layout = 1;
3054                         break;
3055
3056                 case ALGORITHM_ROTATING_N_CONTINUE:
3057                         /* Same as left_symmetric but Q is before P */
3058                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3059                         qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
3060                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
3061                         ddf_layout = 1;
3062                         break;
3063
3064                 case ALGORITHM_LEFT_ASYMMETRIC_6:
3065                         /* RAID5 left_asymmetric, with Q on last device */
3066                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
3067                         if (*dd_idx >= pd_idx)
3068                                 (*dd_idx)++;
3069                         qd_idx = raid_disks - 1;
3070                         break;
3071
3072                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3073                         pd_idx = sector_div(stripe2, raid_disks-1);
3074                         if (*dd_idx >= pd_idx)
3075                                 (*dd_idx)++;
3076                         qd_idx = raid_disks - 1;
3077                         break;
3078
3079                 case ALGORITHM_LEFT_SYMMETRIC_6:
3080                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
3081                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
3082                         qd_idx = raid_disks - 1;
3083                         break;
3084
3085                 case ALGORITHM_RIGHT_SYMMETRIC_6:
3086                         pd_idx = sector_div(stripe2, raid_disks-1);
3087                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
3088                         qd_idx = raid_disks - 1;
3089                         break;
3090
3091                 case ALGORITHM_PARITY_0_6:
3092                         pd_idx = 0;
3093                         (*dd_idx)++;
3094                         qd_idx = raid_disks - 1;
3095                         break;
3096
3097                 default:
3098                         BUG();
3099                 }
3100                 break;
3101         }
3102
3103         if (sh) {
3104                 sh->pd_idx = pd_idx;
3105                 sh->qd_idx = qd_idx;
3106                 sh->ddf_layout = ddf_layout;
3107         }
3108         /*
3109          * Finally, compute the new sector number
3110          */
3111         new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
3112         return new_sector;
3113 }
3114
3115 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
3116 {
3117         struct r5conf *conf = sh->raid_conf;
3118         int raid_disks = sh->disks;
3119         int data_disks = raid_disks - conf->max_degraded;
3120         sector_t new_sector = sh->sector, check;
3121         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
3122                                          : conf->chunk_sectors;
3123         int algorithm = previous ? conf->prev_algo
3124                                  : conf->algorithm;
3125         sector_t stripe;
3126         int chunk_offset;
3127         sector_t chunk_number;
3128         int dummy1, dd_idx = i;
3129         sector_t r_sector;
3130         struct stripe_head sh2;
3131
3132         chunk_offset = sector_div(new_sector, sectors_per_chunk);
3133         stripe = new_sector;
3134
3135         if (i == sh->pd_idx)
3136                 return 0;
3137         switch(conf->level) {
3138         case 4: break;
3139         case 5:
3140                 switch (algorithm) {
3141                 case ALGORITHM_LEFT_ASYMMETRIC:
3142                 case ALGORITHM_RIGHT_ASYMMETRIC:
3143                         if (i > sh->pd_idx)
3144                                 i--;
3145                         break;
3146                 case ALGORITHM_LEFT_SYMMETRIC:
3147                 case ALGORITHM_RIGHT_SYMMETRIC:
3148                         if (i < sh->pd_idx)
3149                                 i += raid_disks;
3150                         i -= (sh->pd_idx + 1);
3151                         break;
3152                 case ALGORITHM_PARITY_0:
3153                         i -= 1;
3154                         break;
3155                 case ALGORITHM_PARITY_N:
3156                         break;
3157                 default:
3158                         BUG();
3159                 }
3160                 break;
3161         case 6:
3162                 if (i == sh->qd_idx)
3163                         return 0; /* It is the Q disk */
3164                 switch (algorithm) {
3165                 case ALGORITHM_LEFT_ASYMMETRIC:
3166                 case ALGORITHM_RIGHT_ASYMMETRIC:
3167                 case ALGORITHM_ROTATING_ZERO_RESTART:
3168                 case ALGORITHM_ROTATING_N_RESTART:
3169                         if (sh->pd_idx == raid_disks-1)
3170                                 i--;    /* Q D D D P */
3171                         else if (i > sh->pd_idx)
3172                                 i -= 2; /* D D P Q D */
3173                         break;
3174                 case ALGORITHM_LEFT_SYMMETRIC:
3175                 case ALGORITHM_RIGHT_SYMMETRIC:
3176                         if (sh->pd_idx == raid_disks-1)
3177                                 i--; /* Q D D D P */
3178                         else {
3179                                 /* D D P Q D */
3180                                 if (i < sh->pd_idx)
3181                                         i += raid_disks;
3182                                 i -= (sh->pd_idx + 2);
3183                         }
3184                         break;
3185                 case ALGORITHM_PARITY_0:
3186                         i -= 2;
3187                         break;
3188                 case ALGORITHM_PARITY_N:
3189                         break;
3190                 case ALGORITHM_ROTATING_N_CONTINUE:
3191                         /* Like left_symmetric, but P is before Q */
3192                         if (sh->pd_idx == 0)
3193                                 i--;    /* P D D D Q */
3194                         else {
3195                                 /* D D Q P D */
3196                                 if (i < sh->pd_idx)
3197                                         i += raid_disks;
3198                                 i -= (sh->pd_idx + 1);
3199                         }
3200                         break;
3201                 case ALGORITHM_LEFT_ASYMMETRIC_6:
3202                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3203                         if (i > sh->pd_idx)
3204                                 i--;
3205                         break;
3206                 case ALGORITHM_LEFT_SYMMETRIC_6:
3207                 case ALGORITHM_RIGHT_SYMMETRIC_6:
3208                         if (i < sh->pd_idx)
3209                                 i += data_disks + 1;
3210                         i -= (sh->pd_idx + 1);
3211                         break;
3212                 case ALGORITHM_PARITY_0_6:
3213                         i -= 1;
3214                         break;
3215                 default:
3216                         BUG();
3217                 }
3218                 break;
3219         }
3220
3221         chunk_number = stripe * data_disks + i;
3222         r_sector = chunk_number * sectors_per_chunk + chunk_offset;
3223
3224         check = raid5_compute_sector(conf, r_sector,
3225                                      previous, &dummy1, &sh2);
3226         if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
3227                 || sh2.qd_idx != sh->qd_idx) {
3228                 pr_warn("md/raid:%s: compute_blocknr: map not correct\n",
3229                         mdname(conf->mddev));
3230                 return 0;
3231         }
3232         return r_sector;
3233 }
3234
3235 /*
3236  * There are cases where we want handle_stripe_dirtying() and
3237  * schedule_reconstruction() to delay towrite to some dev of a stripe.
3238  *
3239  * This function checks whether we want to delay the towrite. Specifically,
3240  * we delay the towrite when:
3241  *
3242  *   1. degraded stripe has a non-overwrite to the missing dev, AND this
3243  *      stripe has data in journal (for other devices).
3244  *
3245  *      In this case, when reading data for the non-overwrite dev, it is
3246  *      necessary to handle complex rmw of write back cache (prexor with
3247  *      orig_page, and xor with page). To keep read path simple, we would
3248  *      like to flush data in journal to RAID disks first, so complex rmw
3249  *      is handled in the write patch (handle_stripe_dirtying).
3250  *
3251  *   2. when journal space is critical (R5C_LOG_CRITICAL=1)
3252  *
3253  *      It is important to be able to flush all stripes in raid5-cache.
3254  *      Therefore, we need reserve some space on the journal device for
3255  *      these flushes. If flush operation includes pending writes to the
3256  *      stripe, we need to reserve (conf->raid_disk + 1) pages per stripe
3257  *      for the flush out. If we exclude these pending writes from flush
3258  *      operation, we only need (conf->max_degraded + 1) pages per stripe.
3259  *      Therefore, excluding pending writes in these cases enables more
3260  *      efficient use of the journal device.
3261  *
3262  *      Note: To make sure the stripe makes progress, we only delay
3263  *      towrite for stripes with data already in journal (injournal > 0).
3264  *      When LOG_CRITICAL, stripes with injournal == 0 will be sent to
3265  *      no_space_stripes list.
3266  *
3267  *   3. during journal failure
3268  *      In journal failure, we try to flush all cached data to raid disks
3269  *      based on data in stripe cache. The array is read-only to upper
3270  *      layers, so we would skip all pending writes.
3271  *
3272  */
3273 static inline bool delay_towrite(struct r5conf *conf,
3274                                  struct r5dev *dev,
3275                                  struct stripe_head_state *s)
3276 {
3277         /* case 1 above */
3278         if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3279             !test_bit(R5_Insync, &dev->flags) && s->injournal)
3280                 return true;
3281         /* case 2 above */
3282         if (test_bit(R5C_LOG_CRITICAL, &conf->cache_state) &&
3283             s->injournal > 0)
3284                 return true;
3285         /* case 3 above */
3286         if (s->log_failed && s->injournal)
3287                 return true;
3288         return false;
3289 }
3290
3291 static void
3292 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
3293                          int rcw, int expand)
3294 {
3295         int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
3296         struct r5conf *conf = sh->raid_conf;
3297         int level = conf->level;
3298
3299         if (rcw) {
3300                 /*
3301                  * In some cases, handle_stripe_dirtying initially decided to
3302                  * run rmw and allocates extra page for prexor. However, rcw is
3303                  * cheaper later on. We need to free the extra page now,
3304                  * because we won't be able to do that in ops_complete_prexor().
3305                  */
3306                 r5c_release_extra_page(sh);
3307
3308                 for (i = disks; i--; ) {
3309                         struct r5dev *dev = &sh->dev[i];
3310
3311                         if (dev->towrite && !delay_towrite(conf, dev, s)) {
3312                                 set_bit(R5_LOCKED, &dev->flags);
3313                                 set_bit(R5_Wantdrain, &dev->flags);
3314                                 if (!expand)
3315                                         clear_bit(R5_UPTODATE, &dev->flags);
3316                                 s->locked++;
3317                         } else if (test_bit(R5_InJournal, &dev->flags)) {
3318                                 set_bit(R5_LOCKED, &dev->flags);
3319                                 s->locked++;
3320                         }
3321                 }
3322                 /* if we are not expanding this is a proper write request, and
3323                  * there will be bios with new data to be drained into the
3324                  * stripe cache
3325                  */
3326                 if (!expand) {
3327                         if (!s->locked)
3328                                 /* False alarm, nothing to do */
3329                                 return;
3330                         sh->reconstruct_state = reconstruct_state_drain_run;
3331                         set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3332                 } else
3333                         sh->reconstruct_state = reconstruct_state_run;
3334
3335                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3336
3337                 if (s->locked + conf->max_degraded == disks)
3338                         if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
3339                                 atomic_inc(&conf->pending_full_writes);
3340         } else {
3341                 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
3342                         test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
3343                 BUG_ON(level == 6 &&
3344                         (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
3345                            test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
3346
3347                 for (i = disks; i--; ) {
3348                         struct r5dev *dev = &sh->dev[i];
3349                         if (i == pd_idx || i == qd_idx)
3350                                 continue;
3351
3352                         if (dev->towrite &&
3353                             (test_bit(R5_UPTODATE, &dev->flags) ||
3354                              test_bit(R5_Wantcompute, &dev->flags))) {
3355                                 set_bit(R5_Wantdrain, &dev->flags);
3356                                 set_bit(R5_LOCKED, &dev->flags);
3357                                 clear_bit(R5_UPTODATE, &dev->flags);
3358                                 s->locked++;
3359                         } else if (test_bit(R5_InJournal, &dev->flags)) {
3360                                 set_bit(R5_LOCKED, &dev->flags);
3361                                 s->locked++;
3362                         }
3363                 }
3364                 if (!s->locked)
3365                         /* False alarm - nothing to do */
3366                         return;
3367                 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
3368                 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
3369                 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3370                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3371         }
3372
3373         /* keep the parity disk(s) locked while asynchronous operations
3374          * are in flight
3375          */
3376         set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
3377         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3378         s->locked++;
3379
3380         if (level == 6) {
3381                 int qd_idx = sh->qd_idx;
3382                 struct r5dev *dev = &sh->dev[qd_idx];
3383
3384                 set_bit(R5_LOCKED, &dev->flags);
3385                 clear_bit(R5_UPTODATE, &dev->flags);
3386                 s->locked++;
3387         }
3388
3389         if (raid5_has_ppl(sh->raid_conf) && sh->ppl_page &&
3390             test_bit(STRIPE_OP_BIODRAIN, &s->ops_request) &&
3391             !test_bit(STRIPE_FULL_WRITE, &sh->state) &&
3392             test_bit(R5_Insync, &sh->dev[pd_idx].flags))
3393                 set_bit(STRIPE_OP_PARTIAL_PARITY, &s->ops_request);
3394
3395         pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
3396                 __func__, (unsigned long long)sh->sector,
3397                 s->locked, s->ops_request);
3398 }
3399
3400 /*
3401  * Each stripe/dev can have one or more bion attached.
3402  * toread/towrite point to the first in a chain.
3403  * The bi_next chain must be in order.
3404  */
3405 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
3406                           int forwrite, int previous)
3407 {
3408         struct bio **bip;
3409         struct r5conf *conf = sh->raid_conf;
3410         int firstwrite=0;
3411
3412         pr_debug("adding bi b#%llu to stripe s#%llu\n",
3413                 (unsigned long long)bi->bi_iter.bi_sector,
3414                 (unsigned long long)sh->sector);
3415
3416         spin_lock_irq(&sh->stripe_lock);
3417         sh->dev[dd_idx].write_hint = bi->bi_write_hint;
3418         /* Don't allow new IO added to stripes in batch list */
3419         if (sh->batch_head)
3420                 goto overlap;
3421         if (forwrite) {
3422                 bip = &sh->dev[dd_idx].towrite;
3423                 if (*bip == NULL)
3424                         firstwrite = 1;
3425         } else
3426                 bip = &sh->dev[dd_idx].toread;
3427         while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
3428                 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
3429                         goto overlap;
3430                 bip = & (*bip)->bi_next;
3431         }
3432         if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
3433                 goto overlap;
3434
3435         if (forwrite && raid5_has_ppl(conf)) {
3436                 /*
3437                  * With PPL only writes to consecutive data chunks within a
3438                  * stripe are allowed because for a single stripe_head we can
3439                  * only have one PPL entry at a time, which describes one data
3440                  * range. Not really an overlap, but wait_for_overlap can be
3441                  * used to handle this.
3442                  */
3443                 sector_t sector;
3444                 sector_t first = 0;
3445                 sector_t last = 0;
3446                 int count = 0;
3447                 int i;
3448
3449                 for (i = 0; i < sh->disks; i++) {
3450                         if (i != sh->pd_idx &&
3451                             (i == dd_idx || sh->dev[i].towrite)) {
3452                                 sector = sh->dev[i].sector;
3453                                 if (count == 0 || sector < first)
3454                                         first = sector;
3455                                 if (sector > last)
3456                                         last = sector;
3457                                 count++;
3458                         }
3459                 }
3460
3461                 if (first + conf->chunk_sectors * (count - 1) != last)
3462                         goto overlap;
3463         }
3464
3465         if (!forwrite || previous)
3466                 clear_bit(STRIPE_BATCH_READY, &sh->state);
3467
3468         BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3469         if (*bip)
3470                 bi->bi_next = *bip;
3471         *bip = bi;
3472         bio_inc_remaining(bi);
3473         md_write_inc(conf->mddev, bi);
3474
3475         if (forwrite) {
3476                 /* check if page is covered */
3477                 sector_t sector = sh->dev[dd_idx].sector;
3478                 for (bi=sh->dev[dd_idx].towrite;
3479                      sector < sh->dev[dd_idx].sector + RAID5_STRIPE_SECTORS(conf) &&
3480                              bi && bi->bi_iter.bi_sector <= sector;
3481                      bi = r5_next_bio(conf, bi, sh->dev[dd_idx].sector)) {
3482                         if (bio_end_sector(bi) >= sector)
3483                                 sector = bio_end_sector(bi);
3484                 }
3485                 if (sector >= sh->dev[dd_idx].sector + RAID5_STRIPE_SECTORS(conf))
3486                         if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3487                                 sh->overwrite_disks++;
3488         }
3489
3490         pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3491                 (unsigned long long)(*bip)->bi_iter.bi_sector,
3492                 (unsigned long long)sh->sector, dd_idx);
3493
3494         if (conf->mddev->bitmap && firstwrite) {
3495                 /* Cannot hold spinlock over bitmap_startwrite,
3496                  * but must ensure this isn't added to a batch until
3497                  * we have added to the bitmap and set bm_seq.
3498                  * So set STRIPE_BITMAP_PENDING to prevent
3499                  * batching.
3500                  * If multiple add_stripe_bio() calls race here they
3501                  * much all set STRIPE_BITMAP_PENDING.  So only the first one
3502                  * to complete "bitmap_startwrite" gets to set
3503                  * STRIPE_BIT_DELAY.  This is important as once a stripe
3504                  * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3505                  * any more.
3506                  */
3507                 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3508                 spin_unlock_irq(&sh->stripe_lock);
3509                 md_bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3510                                      RAID5_STRIPE_SECTORS(conf), 0);
3511                 spin_lock_irq(&sh->stripe_lock);
3512                 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3513                 if (!sh->batch_head) {
3514                         sh->bm_seq = conf->seq_flush+1;
3515                         set_bit(STRIPE_BIT_DELAY, &sh->state);
3516                 }
3517         }
3518         spin_unlock_irq(&sh->stripe_lock);
3519
3520         if (stripe_can_batch(sh))
3521                 stripe_add_to_batch_list(conf, sh);
3522         return 1;
3523
3524  overlap:
3525         set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3526         spin_unlock_irq(&sh->stripe_lock);
3527         return 0;
3528 }
3529
3530 static void end_reshape(struct r5conf *conf);
3531
3532 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3533                             struct stripe_head *sh)
3534 {
3535         int sectors_per_chunk =
3536                 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3537         int dd_idx;
3538         int chunk_offset = sector_div(stripe, sectors_per_chunk);
3539         int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3540
3541         raid5_compute_sector(conf,
3542                              stripe * (disks - conf->max_degraded)
3543                              *sectors_per_chunk + chunk_offset,
3544                              previous,
3545                              &dd_idx, sh);
3546 }
3547
3548 static void
3549 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3550                      struct stripe_head_state *s, int disks)
3551 {
3552         int i;
3553         BUG_ON(sh->batch_head);
3554         for (i = disks; i--; ) {
3555                 struct bio *bi;
3556                 int bitmap_end = 0;
3557
3558                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3559                         struct md_rdev *rdev;
3560                         rcu_read_lock();
3561                         rdev = rcu_dereference(conf->disks[i].rdev);
3562                         if (rdev && test_bit(In_sync, &rdev->flags) &&
3563                             !test_bit(Faulty, &rdev->flags))
3564                                 atomic_inc(&rdev->nr_pending);
3565                         else
3566                                 rdev = NULL;
3567                         rcu_read_unlock();
3568                         if (rdev) {
3569                                 if (!rdev_set_badblocks(
3570                                             rdev,
3571                                             sh->sector,
3572                                             RAID5_STRIPE_SECTORS(conf), 0))
3573                                         md_error(conf->mddev, rdev);
3574                                 rdev_dec_pending(rdev, conf->mddev);
3575                         }
3576                 }
3577                 spin_lock_irq(&sh->stripe_lock);
3578                 /* fail all writes first */
3579                 bi = sh->dev[i].towrite;
3580                 sh->dev[i].towrite = NULL;
3581                 sh->overwrite_disks = 0;
3582                 spin_unlock_irq(&sh->stripe_lock);
3583                 if (bi)
3584                         bitmap_end = 1;
3585
3586                 log_stripe_write_finished(sh);
3587
3588                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3589                         wake_up(&conf->wait_for_overlap);
3590
3591                 while (bi && bi->bi_iter.bi_sector <
3592                         sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3593                         struct bio *nextbi = r5_next_bio(conf, bi, sh->dev[i].sector);
3594
3595                         md_write_end(conf->mddev);
3596                         bio_io_error(bi);
3597                         bi = nextbi;
3598                 }
3599                 if (bitmap_end)
3600                         md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3601                                            RAID5_STRIPE_SECTORS(conf), 0, 0);
3602                 bitmap_end = 0;
3603                 /* and fail all 'written' */
3604                 bi = sh->dev[i].written;
3605                 sh->dev[i].written = NULL;
3606                 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3607                         WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3608                         sh->dev[i].page = sh->dev[i].orig_page;
3609                 }
3610
3611                 if (bi) bitmap_end = 1;
3612                 while (bi && bi->bi_iter.bi_sector <
3613                        sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3614                         struct bio *bi2 = r5_next_bio(conf, bi, sh->dev[i].sector);
3615
3616                         md_write_end(conf->mddev);
3617                         bio_io_error(bi);
3618                         bi = bi2;
3619                 }
3620
3621                 /* fail any reads if this device is non-operational and
3622                  * the data has not reached the cache yet.
3623                  */
3624                 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3625                     s->failed > conf->max_degraded &&
3626                     (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3627                       test_bit(R5_ReadError, &sh->dev[i].flags))) {
3628                         spin_lock_irq(&sh->stripe_lock);
3629                         bi = sh->dev[i].toread;
3630                         sh->dev[i].toread = NULL;
3631                         spin_unlock_irq(&sh->stripe_lock);
3632                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3633                                 wake_up(&conf->wait_for_overlap);
3634                         if (bi)
3635                                 s->to_read--;
3636                         while (bi && bi->bi_iter.bi_sector <
3637                                sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3638                                 struct bio *nextbi =
3639                                         r5_next_bio(conf, bi, sh->dev[i].sector);
3640
3641                                 bio_io_error(bi);
3642                                 bi = nextbi;
3643                         }
3644                 }
3645                 if (bitmap_end)
3646                         md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3647                                            RAID5_STRIPE_SECTORS(conf), 0, 0);
3648                 /* If we were in the middle of a write the parity block might
3649                  * still be locked - so just clear all R5_LOCKED flags
3650                  */
3651                 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3652         }
3653         s->to_write = 0;
3654         s->written = 0;
3655
3656         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3657                 if (atomic_dec_and_test(&conf->pending_full_writes))
3658                         md_wakeup_thread(conf->mddev->thread);
3659 }
3660
3661 static void
3662 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3663                    struct stripe_head_state *s)
3664 {
3665         int abort = 0;
3666         int i;
3667
3668         BUG_ON(sh->batch_head);
3669         clear_bit(STRIPE_SYNCING, &sh->state);
3670         if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3671                 wake_up(&conf->wait_for_overlap);
3672         s->syncing = 0;
3673         s->replacing = 0;
3674         /* There is nothing more to do for sync/check/repair.
3675          * Don't even need to abort as that is handled elsewhere
3676          * if needed, and not always wanted e.g. if there is a known
3677          * bad block here.
3678          * For recover/replace we need to record a bad block on all
3679          * non-sync devices, or abort the recovery
3680          */
3681         if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3682                 /* During recovery devices cannot be removed, so
3683                  * locking and refcounting of rdevs is not needed
3684                  */
3685                 rcu_read_lock();
3686                 for (i = 0; i < conf->raid_disks; i++) {
3687                         struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
3688                         if (rdev
3689                             && !test_bit(Faulty, &rdev->flags)
3690                             && !test_bit(In_sync, &rdev->flags)
3691                             && !rdev_set_badblocks(rdev, sh->sector,
3692                                                    RAID5_STRIPE_SECTORS(conf), 0))
3693                                 abort = 1;
3694                         rdev = rcu_dereference(conf->disks[i].replacement);
3695                         if (rdev
3696                             && !test_bit(Faulty, &rdev->flags)
3697                             && !test_bit(In_sync, &rdev->flags)
3698                             && !rdev_set_badblocks(rdev, sh->sector,
3699                                                    RAID5_STRIPE_SECTORS(conf), 0))
3700                                 abort = 1;
3701                 }
3702                 rcu_read_unlock();
3703                 if (abort)
3704                         conf->recovery_disabled =
3705                                 conf->mddev->recovery_disabled;
3706         }
3707         md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), !abort);
3708 }
3709
3710 static int want_replace(struct stripe_head *sh, int disk_idx)
3711 {
3712         struct md_rdev *rdev;
3713         int rv = 0;
3714
3715         rcu_read_lock();
3716         rdev = rcu_dereference(sh->raid_conf->disks[disk_idx].replacement);
3717         if (rdev
3718             && !test_bit(Faulty, &rdev->flags)
3719             && !test_bit(In_sync, &rdev->flags)
3720             && (rdev->recovery_offset <= sh->sector
3721                 || rdev->mddev->recovery_cp <= sh->sector))
3722                 rv = 1;
3723         rcu_read_unlock();
3724         return rv;
3725 }
3726
3727 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3728                            int disk_idx, int disks)
3729 {
3730         struct r5dev *dev = &sh->dev[disk_idx];
3731         struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3732                                   &sh->dev[s->failed_num[1]] };
3733         int i;
3734         bool force_rcw = (sh->raid_conf->rmw_level == PARITY_DISABLE_RMW);
3735
3736
3737         if (test_bit(R5_LOCKED, &dev->flags) ||
3738             test_bit(R5_UPTODATE, &dev->flags))
3739                 /* No point reading this as we already have it or have
3740                  * decided to get it.
3741                  */
3742                 return 0;
3743
3744         if (dev->toread ||
3745             (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3746                 /* We need this block to directly satisfy a request */
3747                 return 1;
3748
3749         if (s->syncing || s->expanding ||
3750             (s->replacing && want_replace(sh, disk_idx)))
3751                 /* When syncing, or expanding we read everything.
3752                  * When replacing, we need the replaced block.
3753                  */
3754                 return 1;
3755
3756         if ((s->failed >= 1 && fdev[0]->toread) ||
3757             (s->failed >= 2 && fdev[1]->toread))
3758                 /* If we want to read from a failed device, then
3759                  * we need to actually read every other device.
3760                  */
3761                 return 1;
3762
3763         /* Sometimes neither read-modify-write nor reconstruct-write
3764          * cycles can work.  In those cases we read every block we
3765          * can.  Then the parity-update is certain to have enough to
3766          * work with.
3767          * This can only be a problem when we need to write something,
3768          * and some device has failed.  If either of those tests
3769          * fail we need look no further.
3770          */
3771         if (!s->failed || !s->to_write)
3772                 return 0;
3773
3774         if (test_bit(R5_Insync, &dev->flags) &&
3775             !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3776                 /* Pre-reads at not permitted until after short delay
3777                  * to gather multiple requests.  However if this
3778                  * device is no Insync, the block could only be computed
3779                  * and there is no need to delay that.
3780                  */
3781                 return 0;
3782
3783         for (i = 0; i < s->failed && i < 2; i++) {
3784                 if (fdev[i]->towrite &&
3785                     !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3786                     !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3787                         /* If we have a partial write to a failed
3788                          * device, then we will need to reconstruct
3789                          * the content of that device, so all other
3790                          * devices must be read.
3791                          */
3792                         return 1;
3793
3794                 if (s->failed >= 2 &&
3795                     (fdev[i]->towrite ||
3796                      s->failed_num[i] == sh->pd_idx ||
3797                      s->failed_num[i] == sh->qd_idx) &&
3798                     !test_bit(R5_UPTODATE, &fdev[i]->flags))
3799                         /* In max degraded raid6, If the failed disk is P, Q,
3800                          * or we want to read the failed disk, we need to do
3801                          * reconstruct-write.
3802                          */
3803                         force_rcw = true;
3804         }
3805
3806         /* If we are forced to do a reconstruct-write, because parity
3807          * cannot be trusted and we are currently recovering it, there
3808          * is extra need to be careful.
3809          * If one of the devices that we would need to read, because
3810          * it is not being overwritten (and maybe not written at all)
3811          * is missing/faulty, then we need to read everything we can.
3812          */
3813         if (!force_rcw &&
3814             sh->sector < sh->raid_conf->mddev->recovery_cp)
3815                 /* reconstruct-write isn't being forced */
3816                 return 0;
3817         for (i = 0; i < s->failed && i < 2; i++) {
3818                 if (s->failed_num[i] != sh->pd_idx &&
3819                     s->failed_num[i] != sh->qd_idx &&
3820                     !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3821                     !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3822                         return 1;
3823         }
3824
3825         return 0;
3826 }
3827
3828 /* fetch_block - checks the given member device to see if its data needs
3829  * to be read or computed to satisfy a request.
3830  *
3831  * Returns 1 when no more member devices need to be checked, otherwise returns
3832  * 0 to tell the loop in handle_stripe_fill to continue
3833  */
3834 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3835                        int disk_idx, int disks)
3836 {
3837         struct r5dev *dev = &sh->dev[disk_idx];
3838
3839         /* is the data in this block needed, and can we get it? */
3840         if (need_this_block(sh, s, disk_idx, disks)) {
3841                 /* we would like to get this block, possibly by computing it,
3842                  * otherwise read it if the backing disk is insync
3843                  */
3844                 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3845                 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3846                 BUG_ON(sh->batch_head);
3847
3848                 /*
3849                  * In the raid6 case if the only non-uptodate disk is P
3850                  * then we already trusted P to compute the other failed
3851                  * drives. It is safe to compute rather than re-read P.
3852                  * In other cases we only compute blocks from failed
3853                  * devices, otherwise check/repair might fail to detect
3854                  * a real inconsistency.
3855                  */
3856
3857                 if ((s->uptodate == disks - 1) &&
3858                     ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3859                     (s->failed && (disk_idx == s->failed_num[0] ||
3860                                    disk_idx == s->failed_num[1])))) {
3861                         /* have disk failed, and we're requested to fetch it;
3862                          * do compute it
3863                          */
3864                         pr_debug("Computing stripe %llu block %d\n",
3865                                (unsigned long long)sh->sector, disk_idx);
3866                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3867                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3868                         set_bit(R5_Wantcompute, &dev->flags);
3869                         sh->ops.target = disk_idx;
3870                         sh->ops.target2 = -1; /* no 2nd target */
3871                         s->req_compute = 1;
3872                         /* Careful: from this point on 'uptodate' is in the eye
3873                          * of raid_run_ops which services 'compute' operations
3874                          * before writes. R5_Wantcompute flags a block that will
3875                          * be R5_UPTODATE by the time it is needed for a
3876                          * subsequent operation.
3877                          */
3878                         s->uptodate++;
3879                         return 1;
3880                 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3881                         /* Computing 2-failure is *very* expensive; only
3882                          * do it if failed >= 2
3883                          */
3884                         int other;
3885                         for (other = disks; other--; ) {
3886                                 if (other == disk_idx)
3887                                         continue;
3888                                 if (!test_bit(R5_UPTODATE,
3889                                       &sh->dev[other].flags))
3890                                         break;
3891                         }
3892                         BUG_ON(other < 0);
3893                         pr_debug("Computing stripe %llu blocks %d,%d\n",
3894                                (unsigned long long)sh->sector,
3895                                disk_idx, other);
3896                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3897                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3898                         set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3899                         set_bit(R5_Wantcompute, &sh->dev[other].flags);
3900                         sh->ops.target = disk_idx;
3901                         sh->ops.target2 = other;
3902                         s->uptodate += 2;
3903                         s->req_compute = 1;
3904                         return 1;
3905                 } else if (test_bit(R5_Insync, &dev->flags)) {
3906                         set_bit(R5_LOCKED, &dev->flags);
3907                         set_bit(R5_Wantread, &dev->flags);
3908                         s->locked++;
3909                         pr_debug("Reading block %d (sync=%d)\n",
3910                                 disk_idx, s->syncing);
3911                 }
3912         }
3913
3914         return 0;
3915 }
3916
3917 /*
3918  * handle_stripe_fill - read or compute data to satisfy pending requests.
3919  */
3920 static void handle_stripe_fill(struct stripe_head *sh,
3921                                struct stripe_head_state *s,
3922                                int disks)
3923 {
3924         int i;
3925
3926         /* look for blocks to read/compute, skip this if a compute
3927          * is already in flight, or if the stripe contents are in the
3928          * midst of changing due to a write
3929          */
3930         if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3931             !sh->reconstruct_state) {
3932
3933                 /*
3934                  * For degraded stripe with data in journal, do not handle
3935                  * read requests yet, instead, flush the stripe to raid
3936                  * disks first, this avoids handling complex rmw of write
3937                  * back cache (prexor with orig_page, and then xor with
3938                  * page) in the read path
3939                  */
3940                 if (s->to_read && s->injournal && s->failed) {
3941                         if (test_bit(STRIPE_R5C_CACHING, &sh->state))
3942                                 r5c_make_stripe_write_out(sh);
3943                         goto out;
3944                 }
3945
3946                 for (i = disks; i--; )
3947                         if (fetch_block(sh, s, i, disks))
3948                                 break;
3949         }
3950 out:
3951         set_bit(STRIPE_HANDLE, &sh->state);
3952 }
3953
3954 static void break_stripe_batch_list(struct stripe_head *head_sh,
3955                                     unsigned long handle_flags);
3956 /* handle_stripe_clean_event
3957  * any written block on an uptodate or failed drive can be returned.
3958  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3959  * never LOCKED, so we don't need to test 'failed' directly.
3960  */
3961 static void handle_stripe_clean_event(struct r5conf *conf,
3962         struct stripe_head *sh, int disks)
3963 {
3964         int i;
3965         struct r5dev *dev;
3966         int discard_pending = 0;
3967         struct stripe_head *head_sh = sh;
3968         bool do_endio = false;
3969
3970         for (i = disks; i--; )
3971                 if (sh->dev[i].written) {
3972                         dev = &sh->dev[i];
3973                         if (!test_bit(R5_LOCKED, &dev->flags) &&
3974                             (test_bit(R5_UPTODATE, &dev->flags) ||
3975                              test_bit(R5_Discard, &dev->flags) ||
3976                              test_bit(R5_SkipCopy, &dev->flags))) {
3977                                 /* We can return any write requests */
3978                                 struct bio *wbi, *wbi2;
3979                                 pr_debug("Return write for disc %d\n", i);
3980                                 if (test_and_clear_bit(R5_Discard, &dev->flags))
3981                                         clear_bit(R5_UPTODATE, &dev->flags);
3982                                 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3983                                         WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3984                                 }
3985                                 do_endio = true;
3986
3987 returnbi:
3988                                 dev->page = dev->orig_page;
3989                                 wbi = dev->written;
3990                                 dev->written = NULL;
3991                                 while (wbi && wbi->bi_iter.bi_sector <
3992                                         dev->sector + RAID5_STRIPE_SECTORS(conf)) {
3993                                         wbi2 = r5_next_bio(conf, wbi, dev->sector);
3994                                         md_write_end(conf->mddev);
3995                                         bio_endio(wbi);
3996                                         wbi = wbi2;
3997                                 }
3998                                 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3999                                                    RAID5_STRIPE_SECTORS(conf),
4000                                                    !test_bit(STRIPE_DEGRADED, &sh->state),
4001                                                    0);
4002                                 if (head_sh->batch_head) {
4003                                         sh = list_first_entry(&sh->batch_list,
4004                                                               struct stripe_head,
4005                                                               batch_list);
4006                                         if (sh != head_sh) {
4007                                                 dev = &sh->dev[i];
4008                                                 goto returnbi;
4009                                         }
4010                                 }
4011                                 sh = head_sh;
4012                                 dev = &sh->dev[i];
4013                         } else if (test_bit(R5_Discard, &dev->flags))
4014                                 discard_pending = 1;
4015                 }
4016
4017         log_stripe_write_finished(sh);
4018
4019         if (!discard_pending &&
4020             test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
4021                 int hash;
4022                 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
4023                 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4024                 if (sh->qd_idx >= 0) {
4025                         clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
4026                         clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
4027                 }
4028                 /* now that discard is done we can proceed with any sync */
4029                 clear_bit(STRIPE_DISCARD, &sh->state);
4030                 /*
4031                  * SCSI discard will change some bio fields and the stripe has
4032                  * no updated data, so remove it from hash list and the stripe
4033                  * will be reinitialized
4034                  */
4035 unhash:
4036                 hash = sh->hash_lock_index;
4037                 spin_lock_irq(conf->hash_locks + hash);
4038                 remove_hash(sh);
4039                 spin_unlock_irq(conf->hash_locks + hash);
4040                 if (head_sh->batch_head) {
4041                         sh = list_first_entry(&sh->batch_list,
4042                                               struct stripe_head, batch_list);
4043                         if (sh != head_sh)
4044                                         goto unhash;
4045                 }
4046                 sh = head_sh;
4047
4048                 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
4049                         set_bit(STRIPE_HANDLE, &sh->state);
4050
4051         }
4052
4053         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
4054                 if (atomic_dec_and_test(&conf->pending_full_writes))
4055                         md_wakeup_thread(conf->mddev->thread);
4056
4057         if (head_sh->batch_head && do_endio)
4058                 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
4059 }
4060
4061 /*
4062  * For RMW in write back cache, we need extra page in prexor to store the
4063  * old data. This page is stored in dev->orig_page.
4064  *
4065  * This function checks whether we have data for prexor. The exact logic
4066  * is:
4067  *       R5_UPTODATE && (!R5_InJournal || R5_OrigPageUPTDODATE)
4068  */
4069 static inline bool uptodate_for_rmw(struct r5dev *dev)
4070 {
4071         return (test_bit(R5_UPTODATE, &dev->flags)) &&
4072                 (!test_bit(R5_InJournal, &dev->flags) ||
4073                  test_bit(R5_OrigPageUPTDODATE, &dev->flags));
4074 }
4075
4076 static int handle_stripe_dirtying(struct r5conf *conf,
4077                                   struct stripe_head *sh,
4078                                   struct stripe_head_state *s,
4079                                   int disks)
4080 {
4081         int rmw = 0, rcw = 0, i;
4082         sector_t recovery_cp = conf->mddev->recovery_cp;
4083
4084         /* Check whether resync is now happening or should start.
4085          * If yes, then the array is dirty (after unclean shutdown or
4086          * initial creation), so parity in some stripes might be inconsistent.
4087          * In this case, we need to always do reconstruct-write, to ensure
4088          * that in case of drive failure or read-error correction, we
4089          * generate correct data from the parity.
4090          */
4091         if (conf->rmw_level == PARITY_DISABLE_RMW ||
4092             (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
4093              s->failed == 0)) {
4094                 /* Calculate the real rcw later - for now make it
4095                  * look like rcw is cheaper
4096                  */
4097                 rcw = 1; rmw = 2;
4098                 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
4099                          conf->rmw_level, (unsigned long long)recovery_cp,
4100                          (unsigned long long)sh->sector);
4101         } else for (i = disks; i--; ) {
4102                 /* would I have to read this buffer for read_modify_write */
4103                 struct r5dev *dev = &sh->dev[i];
4104                 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
4105                      i == sh->pd_idx || i == sh->qd_idx ||
4106                      test_bit(R5_InJournal, &dev->flags)) &&
4107                     !test_bit(R5_LOCKED, &dev->flags) &&
4108                     !(uptodate_for_rmw(dev) ||
4109                       test_bit(R5_Wantcompute, &dev->flags))) {
4110                         if (test_bit(R5_Insync, &dev->flags))
4111                                 rmw++;
4112                         else
4113                                 rmw += 2*disks;  /* cannot read it */
4114                 }
4115                 /* Would I have to read this buffer for reconstruct_write */
4116                 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
4117                     i != sh->pd_idx && i != sh->qd_idx &&
4118                     !test_bit(R5_LOCKED, &dev->flags) &&
4119                     !(test_bit(R5_UPTODATE, &dev->flags) ||
4120                       test_bit(R5_Wantcompute, &dev->flags))) {
4121                         if (test_bit(R5_Insync, &dev->flags))
4122                                 rcw++;
4123                         else
4124                                 rcw += 2*disks;
4125                 }
4126         }
4127
4128         pr_debug("for sector %llu state 0x%lx, rmw=%d rcw=%d\n",
4129                  (unsigned long long)sh->sector, sh->state, rmw, rcw);
4130         set_bit(STRIPE_HANDLE, &sh->state);
4131         if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_PREFER_RMW)) && rmw > 0) {
4132                 /* prefer read-modify-write, but need to get some data */
4133                 if (conf->mddev->queue)
4134                         blk_add_trace_msg(conf->mddev->queue,
4135                                           "raid5 rmw %llu %d",
4136                                           (unsigned long long)sh->sector, rmw);
4137                 for (i = disks; i--; ) {
4138                         struct r5dev *dev = &sh->dev[i];
4139                         if (test_bit(R5_InJournal, &dev->flags) &&
4140                             dev->page == dev->orig_page &&
4141                             !test_bit(R5_LOCKED, &sh->dev[sh->pd_idx].flags)) {
4142                                 /* alloc page for prexor */
4143                                 struct page *p = alloc_page(GFP_NOIO);
4144
4145                                 if (p) {
4146                                         dev->orig_page = p;
4147                                         continue;
4148                                 }
4149
4150                                 /*
4151                                  * alloc_page() failed, try use
4152                                  * disk_info->extra_page
4153                                  */
4154                                 if (!test_and_set_bit(R5C_EXTRA_PAGE_IN_USE,
4155                                                       &conf->cache_state)) {
4156                                         r5c_use_extra_page(sh);
4157                                         break;
4158                                 }
4159
4160                                 /* extra_page in use, add to delayed_list */
4161                                 set_bit(STRIPE_DELAYED, &sh->state);
4162                                 s->waiting_extra_page = 1;
4163                                 return -EAGAIN;
4164                         }
4165                 }
4166
4167                 for (i = disks; i--; ) {
4168                         struct r5dev *dev = &sh->dev[i];
4169                         if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
4170                              i == sh->pd_idx || i == sh->qd_idx ||
4171                              test_bit(R5_InJournal, &dev->flags)) &&
4172                             !test_bit(R5_LOCKED, &dev->flags) &&
4173                             !(uptodate_for_rmw(dev) ||
4174                               test_bit(R5_Wantcompute, &dev->flags)) &&
4175                             test_bit(R5_Insync, &dev->flags)) {
4176                                 if (test_bit(STRIPE_PREREAD_ACTIVE,
4177                                              &sh->state)) {
4178                                         pr_debug("Read_old block %d for r-m-w\n",
4179                                                  i);
4180                                         set_bit(R5_LOCKED, &dev->flags);
4181                                         set_bit(R5_Wantread, &dev->flags);
4182                                         s->locked++;
4183                                 } else
4184                                         set_bit(STRIPE_DELAYED, &sh->state);
4185                         }
4186                 }
4187         }
4188         if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_PREFER_RMW)) && rcw > 0) {
4189                 /* want reconstruct write, but need to get some data */
4190                 int qread =0;
4191                 rcw = 0;
4192                 for (i = disks; i--; ) {
4193                         struct r5dev *dev = &sh->dev[i];
4194                         if (!test_bit(R5_OVERWRITE, &dev->flags) &&
4195                             i != sh->pd_idx && i != sh->qd_idx &&
4196                             !test_bit(R5_LOCKED, &dev->flags) &&
4197                             !(test_bit(R5_UPTODATE, &dev->flags) ||
4198                               test_bit(R5_Wantcompute, &dev->flags))) {
4199                                 rcw++;
4200                                 if (test_bit(R5_Insync, &dev->flags) &&
4201                                     test_bit(STRIPE_PREREAD_ACTIVE,
4202                                              &sh->state)) {
4203                                         pr_debug("Read_old block "
4204                                                 "%d for Reconstruct\n", i);
4205                                         set_bit(R5_LOCKED, &dev->flags);
4206                                         set_bit(R5_Wantread, &dev->flags);
4207                                         s->locked++;
4208                                         qread++;
4209                                 } else
4210                                         set_bit(STRIPE_DELAYED, &sh->state);
4211                         }
4212                 }
4213                 if (rcw && conf->mddev->queue)
4214                         blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
4215                                           (unsigned long long)sh->sector,
4216                                           rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
4217         }
4218
4219         if (rcw > disks && rmw > disks &&
4220             !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4221                 set_bit(STRIPE_DELAYED, &sh->state);
4222
4223         /* now if nothing is locked, and if we have enough data,
4224          * we can start a write request
4225          */
4226         /* since handle_stripe can be called at any time we need to handle the
4227          * case where a compute block operation has been submitted and then a
4228          * subsequent call wants to start a write request.  raid_run_ops only
4229          * handles the case where compute block and reconstruct are requested
4230          * simultaneously.  If this is not the case then new writes need to be
4231          * held off until the compute completes.
4232          */
4233         if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
4234             (s->locked == 0 && (rcw == 0 || rmw == 0) &&
4235              !test_bit(STRIPE_BIT_DELAY, &sh->state)))
4236                 schedule_reconstruction(sh, s, rcw == 0, 0);
4237         return 0;
4238 }
4239
4240 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
4241                                 struct stripe_head_state *s, int disks)
4242 {
4243         struct r5dev *dev = NULL;
4244
4245         BUG_ON(sh->batch_head);
4246         set_bit(STRIPE_HANDLE, &sh->state);
4247
4248         switch (sh->check_state) {
4249         case check_state_idle:
4250                 /* start a new check operation if there are no failures */
4251                 if (s->failed == 0) {
4252                         BUG_ON(s->uptodate != disks);
4253                         sh->check_state = check_state_run;
4254                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
4255                         clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4256                         s->uptodate--;
4257                         break;
4258                 }
4259                 dev = &sh->dev[s->failed_num[0]];
4260                 fallthrough;
4261         case check_state_compute_result:
4262                 sh->check_state = check_state_idle;
4263                 if (!dev)
4264                         dev = &sh->dev[sh->pd_idx];
4265
4266                 /* check that a write has not made the stripe insync */
4267                 if (test_bit(STRIPE_INSYNC, &sh->state))
4268                         break;
4269
4270                 /* either failed parity check, or recovery is happening */
4271                 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
4272                 BUG_ON(s->uptodate != disks);
4273
4274                 set_bit(R5_LOCKED, &dev->flags);
4275                 s->locked++;
4276                 set_bit(R5_Wantwrite, &dev->flags);
4277
4278                 clear_bit(STRIPE_DEGRADED, &sh->state);
4279                 set_bit(STRIPE_INSYNC, &sh->state);
4280                 break;
4281         case check_state_run:
4282                 break; /* we will be called again upon completion */
4283         case check_state_check_result:
4284                 sh->check_state = check_state_idle;
4285
4286                 /* if a failure occurred during the check operation, leave
4287                  * STRIPE_INSYNC not set and let the stripe be handled again
4288                  */
4289                 if (s->failed)
4290                         break;
4291
4292                 /* handle a successful check operation, if parity is correct
4293                  * we are done.  Otherwise update the mismatch count and repair
4294                  * parity if !MD_RECOVERY_CHECK
4295                  */
4296                 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
4297                         /* parity is correct (on disc,
4298                          * not in buffer any more)
4299                          */
4300                         set_bit(STRIPE_INSYNC, &sh->state);
4301                 else {
4302                         atomic64_add(RAID5_STRIPE_SECTORS(conf), &conf->mddev->resync_mismatches);
4303                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4304                                 /* don't try to repair!! */
4305                                 set_bit(STRIPE_INSYNC, &sh->state);
4306                                 pr_warn_ratelimited("%s: mismatch sector in range "
4307                                                     "%llu-%llu\n", mdname(conf->mddev),
4308                                                     (unsigned long long) sh->sector,
4309                                                     (unsigned long long) sh->sector +
4310                                                     RAID5_STRIPE_SECTORS(conf));
4311                         } else {
4312                                 sh->check_state = check_state_compute_run;
4313                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4314                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4315                                 set_bit(R5_Wantcompute,
4316                                         &sh->dev[sh->pd_idx].flags);
4317                                 sh->ops.target = sh->pd_idx;
4318                                 sh->ops.target2 = -1;
4319                                 s->uptodate++;
4320                         }
4321                 }
4322                 break;
4323         case check_state_compute_run:
4324                 break;
4325         default:
4326                 pr_err("%s: unknown check_state: %d sector: %llu\n",
4327                        __func__, sh->check_state,
4328                        (unsigned long long) sh->sector);
4329                 BUG();
4330         }
4331 }
4332
4333 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
4334                                   struct stripe_head_state *s,
4335                                   int disks)
4336 {
4337         int pd_idx = sh->pd_idx;
4338         int qd_idx = sh->qd_idx;
4339         struct r5dev *dev;
4340
4341         BUG_ON(sh->batch_head);
4342         set_bit(STRIPE_HANDLE, &sh->state);
4343
4344         BUG_ON(s->failed > 2);
4345
4346         /* Want to check and possibly repair P and Q.
4347          * However there could be one 'failed' device, in which
4348          * case we can only check one of them, possibly using the
4349          * other to generate missing data
4350          */
4351
4352         switch (sh->check_state) {
4353         case check_state_idle:
4354                 /* start a new check operation if there are < 2 failures */
4355                 if (s->failed == s->q_failed) {
4356                         /* The only possible failed device holds Q, so it
4357                          * makes sense to check P (If anything else were failed,
4358                          * we would have used P to recreate it).
4359                          */
4360                         sh->check_state = check_state_run;
4361                 }
4362                 if (!s->q_failed && s->failed < 2) {
4363                         /* Q is not failed, and we didn't use it to generate
4364                          * anything, so it makes sense to check it
4365                          */
4366                         if (sh->check_state == check_state_run)
4367                                 sh->check_state = check_state_run_pq;
4368                         else
4369                                 sh->check_state = check_state_run_q;
4370                 }
4371
4372                 /* discard potentially stale zero_sum_result */
4373                 sh->ops.zero_sum_result = 0;
4374
4375                 if (sh->check_state == check_state_run) {
4376                         /* async_xor_zero_sum destroys the contents of P */
4377                         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
4378                         s->uptodate--;
4379                 }
4380                 if (sh->check_state >= check_state_run &&
4381                     sh->check_state <= check_state_run_pq) {
4382                         /* async_syndrome_zero_sum preserves P and Q, so
4383                          * no need to mark them !uptodate here
4384                          */
4385                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
4386                         break;
4387                 }
4388
4389                 /* we have 2-disk failure */
4390                 BUG_ON(s->failed != 2);
4391                 fallthrough;
4392         case check_state_compute_result:
4393                 sh->check_state = check_state_idle;
4394
4395                 /* check that a write has not made the stripe insync */
4396                 if (test_bit(STRIPE_INSYNC, &sh->state))
4397                         break;
4398
4399                 /* now write out any block on a failed drive,
4400                  * or P or Q if they were recomputed
4401                  */
4402                 dev = NULL;
4403                 if (s->failed == 2) {
4404                         dev = &sh->dev[s->failed_num[1]];
4405                         s->locked++;
4406                         set_bit(R5_LOCKED, &dev->flags);
4407                         set_bit(R5_Wantwrite, &dev->flags);
4408                 }
4409                 if (s->failed >= 1) {
4410                         dev = &sh->dev[s->failed_num[0]];
4411                         s->locked++;
4412                         set_bit(R5_LOCKED, &dev->flags);
4413                         set_bit(R5_Wantwrite, &dev->flags);
4414                 }
4415                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4416                         dev = &sh->dev[pd_idx];
4417                         s->locked++;
4418                         set_bit(R5_LOCKED, &dev->flags);
4419                         set_bit(R5_Wantwrite, &dev->flags);
4420                 }
4421                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4422                         dev = &sh->dev[qd_idx];
4423                         s->locked++;
4424                         set_bit(R5_LOCKED, &dev->flags);
4425                         set_bit(R5_Wantwrite, &dev->flags);
4426                 }
4427                 if (WARN_ONCE(dev && !test_bit(R5_UPTODATE, &dev->flags),
4428                               "%s: disk%td not up to date\n",
4429                               mdname(conf->mddev),
4430                               dev - (struct r5dev *) &sh->dev)) {
4431                         clear_bit(R5_LOCKED, &dev->flags);
4432                         clear_bit(R5_Wantwrite, &dev->flags);
4433                         s->locked--;
4434                 }
4435                 clear_bit(STRIPE_DEGRADED, &sh->state);
4436
4437                 set_bit(STRIPE_INSYNC, &sh->state);
4438                 break;
4439         case check_state_run:
4440         case check_state_run_q:
4441         case check_state_run_pq:
4442                 break; /* we will be called again upon completion */
4443         case check_state_check_result:
4444                 sh->check_state = check_state_idle;
4445
4446                 /* handle a successful check operation, if parity is correct
4447                  * we are done.  Otherwise update the mismatch count and repair
4448                  * parity if !MD_RECOVERY_CHECK
4449                  */
4450                 if (sh->ops.zero_sum_result == 0) {
4451                         /* both parities are correct */
4452                         if (!s->failed)
4453                                 set_bit(STRIPE_INSYNC, &sh->state);
4454                         else {
4455                                 /* in contrast to the raid5 case we can validate
4456                                  * parity, but still have a failure to write
4457                                  * back
4458                                  */
4459                                 sh->check_state = check_state_compute_result;
4460                                 /* Returning at this point means that we may go
4461                                  * off and bring p and/or q uptodate again so
4462                                  * we make sure to check zero_sum_result again
4463                                  * to verify if p or q need writeback
4464                                  */
4465                         }
4466                 } else {
4467                         atomic64_add(RAID5_STRIPE_SECTORS(conf), &conf->mddev->resync_mismatches);
4468                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4469                                 /* don't try to repair!! */
4470                                 set_bit(STRIPE_INSYNC, &sh->state);
4471                                 pr_warn_ratelimited("%s: mismatch sector in range "
4472                                                     "%llu-%llu\n", mdname(conf->mddev),
4473                                                     (unsigned long long) sh->sector,
4474                                                     (unsigned long long) sh->sector +
4475                                                     RAID5_STRIPE_SECTORS(conf));
4476                         } else {
4477                                 int *target = &sh->ops.target;
4478
4479                                 sh->ops.target = -1;
4480                                 sh->ops.target2 = -1;
4481                                 sh->check_state = check_state_compute_run;
4482                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4483                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4484                                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4485                                         set_bit(R5_Wantcompute,
4486                                                 &sh->dev[pd_idx].flags);
4487                                         *target = pd_idx;
4488                                         target = &sh->ops.target2;
4489                                         s->uptodate++;
4490                                 }
4491                                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4492                                         set_bit(R5_Wantcompute,
4493                                                 &sh->dev[qd_idx].flags);
4494                                         *target = qd_idx;
4495                                         s->uptodate++;
4496                                 }
4497                         }
4498                 }
4499                 break;
4500         case check_state_compute_run:
4501                 break;
4502         default:
4503                 pr_warn("%s: unknown check_state: %d sector: %llu\n",
4504                         __func__, sh->check_state,
4505                         (unsigned long long) sh->sector);
4506                 BUG();
4507         }
4508 }
4509
4510 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
4511 {
4512         int i;
4513
4514         /* We have read all the blocks in this stripe and now we need to
4515          * copy some of them into a target stripe for expand.
4516          */
4517         struct dma_async_tx_descriptor *tx = NULL;
4518         BUG_ON(sh->batch_head);
4519         clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4520         for (i = 0; i < sh->disks; i++)
4521                 if (i != sh->pd_idx && i != sh->qd_idx) {
4522                         int dd_idx, j;
4523                         struct stripe_head *sh2;
4524                         struct async_submit_ctl submit;
4525
4526                         sector_t bn = raid5_compute_blocknr(sh, i, 1);
4527                         sector_t s = raid5_compute_sector(conf, bn, 0,
4528                                                           &dd_idx, NULL);
4529                         sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
4530                         if (sh2 == NULL)
4531                                 /* so far only the early blocks of this stripe
4532                                  * have been requested.  When later blocks
4533                                  * get requested, we will try again
4534                                  */
4535                                 continue;
4536                         if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
4537                            test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
4538                                 /* must have already done this block */
4539                                 raid5_release_stripe(sh2);
4540                                 continue;
4541                         }
4542
4543                         /* place all the copies on one channel */
4544                         init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
4545                         tx = async_memcpy(sh2->dev[dd_idx].page,
4546                                           sh->dev[i].page, sh2->dev[dd_idx].offset,
4547                                           sh->dev[i].offset, RAID5_STRIPE_SIZE(conf),
4548                                           &submit);
4549
4550                         set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
4551                         set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4552                         for (j = 0; j < conf->raid_disks; j++)
4553                                 if (j != sh2->pd_idx &&
4554                                     j != sh2->qd_idx &&
4555                                     !test_bit(R5_Expanded, &sh2->dev[j].flags))
4556                                         break;
4557                         if (j == conf->raid_disks) {
4558                                 set_bit(STRIPE_EXPAND_READY, &sh2->state);
4559                                 set_bit(STRIPE_HANDLE, &sh2->state);
4560                         }
4561                         raid5_release_stripe(sh2);
4562
4563                 }
4564         /* done submitting copies, wait for them to complete */
4565         async_tx_quiesce(&tx);
4566 }
4567
4568 /*
4569  * handle_stripe - do things to a stripe.
4570  *
4571  * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4572  * state of various bits to see what needs to be done.
4573  * Possible results:
4574  *    return some read requests which now have data
4575  *    return some write requests which are safely on storage
4576  *    schedule a read on some buffers
4577  *    schedule a write of some buffers
4578  *    return confirmation of parity correctness
4579  *
4580  */
4581
4582 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4583 {
4584         struct r5conf *conf = sh->raid_conf;
4585         int disks = sh->disks;
4586         struct r5dev *dev;
4587         int i;
4588         int do_recovery = 0;
4589
4590         memset(s, 0, sizeof(*s));
4591
4592         s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4593         s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4594         s->failed_num[0] = -1;
4595         s->failed_num[1] = -1;
4596         s->log_failed = r5l_log_disk_error(conf);
4597
4598         /* Now to look around and see what can be done */
4599         rcu_read_lock();
4600         for (i=disks; i--; ) {
4601                 struct md_rdev *rdev;
4602                 sector_t first_bad;
4603                 int bad_sectors;
4604                 int is_bad = 0;
4605
4606                 dev = &sh->dev[i];
4607
4608                 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4609                          i, dev->flags,
4610                          dev->toread, dev->towrite, dev->written);
4611                 /* maybe we can reply to a read
4612                  *
4613                  * new wantfill requests are only permitted while
4614                  * ops_complete_biofill is guaranteed to be inactive
4615                  */
4616                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4617                     !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4618                         set_bit(R5_Wantfill, &dev->flags);
4619
4620                 /* now count some things */
4621                 if (test_bit(R5_LOCKED, &dev->flags))
4622                         s->locked++;
4623                 if (test_bit(R5_UPTODATE, &dev->flags))
4624                         s->uptodate++;
4625                 if (test_bit(R5_Wantcompute, &dev->flags)) {
4626                         s->compute++;
4627                         BUG_ON(s->compute > 2);
4628                 }
4629
4630                 if (test_bit(R5_Wantfill, &dev->flags))
4631                         s->to_fill++;
4632                 else if (dev->toread)
4633                         s->to_read++;
4634                 if (dev->towrite) {
4635                         s->to_write++;
4636                         if (!test_bit(R5_OVERWRITE, &dev->flags))
4637                                 s->non_overwrite++;
4638                 }
4639                 if (dev->written)
4640                         s->written++;
4641                 /* Prefer to use the replacement for reads, but only
4642                  * if it is recovered enough and has no bad blocks.
4643                  */
4644                 rdev = rcu_dereference(conf->disks[i].replacement);
4645                 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4646                     rdev->recovery_offset >= sh->sector + RAID5_STRIPE_SECTORS(conf) &&
4647                     !is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
4648                                  &first_bad, &bad_sectors))
4649                         set_bit(R5_ReadRepl, &dev->flags);
4650                 else {
4651                         if (rdev && !test_bit(Faulty, &rdev->flags))
4652                                 set_bit(R5_NeedReplace, &dev->flags);
4653                         else
4654                                 clear_bit(R5_NeedReplace, &dev->flags);
4655                         rdev = rcu_dereference(conf->disks[i].rdev);
4656                         clear_bit(R5_ReadRepl, &dev->flags);
4657                 }
4658                 if (rdev && test_bit(Faulty, &rdev->flags))
4659                         rdev = NULL;
4660                 if (rdev) {
4661                         is_bad = is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
4662                                              &first_bad, &bad_sectors);
4663                         if (s->blocked_rdev == NULL
4664                             && (test_bit(Blocked, &rdev->flags)
4665                                 || is_bad < 0)) {
4666                                 if (is_bad < 0)
4667                                         set_bit(BlockedBadBlocks,
4668                                                 &rdev->flags);
4669                                 s->blocked_rdev = rdev;
4670                                 atomic_inc(&rdev->nr_pending);
4671                         }
4672                 }
4673                 clear_bit(R5_Insync, &dev->flags);
4674                 if (!rdev)
4675                         /* Not in-sync */;
4676                 else if (is_bad) {
4677                         /* also not in-sync */
4678                         if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4679                             test_bit(R5_UPTODATE, &dev->flags)) {
4680                                 /* treat as in-sync, but with a read error
4681                                  * which we can now try to correct
4682                                  */
4683                                 set_bit(R5_Insync, &dev->flags);
4684                                 set_bit(R5_ReadError, &dev->flags);
4685                         }
4686                 } else if (test_bit(In_sync, &rdev->flags))
4687                         set_bit(R5_Insync, &dev->flags);
4688                 else if (sh->sector + RAID5_STRIPE_SECTORS(conf) <= rdev->recovery_offset)
4689                         /* in sync if before recovery_offset */
4690                         set_bit(R5_Insync, &dev->flags);
4691                 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4692                          test_bit(R5_Expanded, &dev->flags))
4693                         /* If we've reshaped into here, we assume it is Insync.
4694                          * We will shortly update recovery_offset to make
4695                          * it official.
4696                          */
4697                         set_bit(R5_Insync, &dev->flags);
4698
4699                 if (test_bit(R5_WriteError, &dev->flags)) {
4700                         /* This flag does not apply to '.replacement'
4701                          * only to .rdev, so make sure to check that*/
4702                         struct md_rdev *rdev2 = rcu_dereference(
4703                                 conf->disks[i].rdev);
4704                         if (rdev2 == rdev)
4705                                 clear_bit(R5_Insync, &dev->flags);
4706                         if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4707                                 s->handle_bad_blocks = 1;
4708                                 atomic_inc(&rdev2->nr_pending);
4709                         } else
4710                                 clear_bit(R5_WriteError, &dev->flags);
4711                 }
4712                 if (test_bit(R5_MadeGood, &dev->flags)) {
4713                         /* This flag does not apply to '.replacement'
4714                          * only to .rdev, so make sure to check that*/
4715                         struct md_rdev *rdev2 = rcu_dereference(
4716                                 conf->disks[i].rdev);
4717                         if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4718                                 s->handle_bad_blocks = 1;
4719                                 atomic_inc(&rdev2->nr_pending);
4720                         } else
4721                                 clear_bit(R5_MadeGood, &dev->flags);
4722                 }
4723                 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4724                         struct md_rdev *rdev2 = rcu_dereference(
4725                                 conf->disks[i].replacement);
4726                         if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4727                                 s->handle_bad_blocks = 1;
4728                                 atomic_inc(&rdev2->nr_pending);
4729                         } else
4730                                 clear_bit(R5_MadeGoodRepl, &dev->flags);
4731                 }
4732                 if (!test_bit(R5_Insync, &dev->flags)) {
4733                         /* The ReadError flag will just be confusing now */
4734                         clear_bit(R5_ReadError, &dev->flags);
4735                         clear_bit(R5_ReWrite, &dev->flags);
4736                 }
4737                 if (test_bit(R5_ReadError, &dev->flags))
4738                         clear_bit(R5_Insync, &dev->flags);
4739                 if (!test_bit(R5_Insync, &dev->flags)) {
4740                         if (s->failed < 2)
4741                                 s->failed_num[s->failed] = i;
4742                         s->failed++;
4743                         if (rdev && !test_bit(Faulty, &rdev->flags))
4744                                 do_recovery = 1;
4745                         else if (!rdev) {
4746                                 rdev = rcu_dereference(
4747                                     conf->disks[i].replacement);
4748                                 if (rdev && !test_bit(Faulty, &rdev->flags))
4749                                         do_recovery = 1;
4750                         }
4751                 }
4752
4753                 if (test_bit(R5_InJournal, &dev->flags))
4754                         s->injournal++;
4755                 if (test_bit(R5_InJournal, &dev->flags) && dev->written)
4756                         s->just_cached++;
4757         }
4758         if (test_bit(STRIPE_SYNCING, &sh->state)) {
4759                 /* If there is a failed device being replaced,
4760                  *     we must be recovering.
4761                  * else if we are after recovery_cp, we must be syncing
4762                  * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4763                  * else we can only be replacing
4764                  * sync and recovery both need to read all devices, and so
4765                  * use the same flag.
4766                  */
4767                 if (do_recovery ||
4768                     sh->sector >= conf->mddev->recovery_cp ||
4769                     test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4770                         s->syncing = 1;
4771                 else
4772                         s->replacing = 1;
4773         }
4774         rcu_read_unlock();
4775 }
4776
4777 /*
4778  * Return '1' if this is a member of batch, or '0' if it is a lone stripe or
4779  * a head which can now be handled.
4780  */
4781 static int clear_batch_ready(struct stripe_head *sh)
4782 {
4783         struct stripe_head *tmp;
4784         if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4785                 return (sh->batch_head && sh->batch_head != sh);
4786         spin_lock(&sh->stripe_lock);
4787         if (!sh->batch_head) {
4788                 spin_unlock(&sh->stripe_lock);
4789                 return 0;
4790         }
4791
4792         /*
4793          * this stripe could be added to a batch list before we check
4794          * BATCH_READY, skips it
4795          */
4796         if (sh->batch_head != sh) {
4797                 spin_unlock(&sh->stripe_lock);
4798                 return 1;
4799         }
4800         spin_lock(&sh->batch_lock);
4801         list_for_each_entry(tmp, &sh->batch_list, batch_list)
4802                 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4803         spin_unlock(&sh->batch_lock);
4804         spin_unlock(&sh->stripe_lock);
4805
4806         /*
4807          * BATCH_READY is cleared, no new stripes can be added.
4808          * batch_list can be accessed without lock
4809          */
4810         return 0;
4811 }
4812
4813 static void break_stripe_batch_list(struct stripe_head *head_sh,
4814                                     unsigned long handle_flags)
4815 {
4816         struct stripe_head *sh, *next;
4817         int i;
4818         int do_wakeup = 0;
4819
4820         list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4821
4822                 list_del_init(&sh->batch_list);
4823
4824                 WARN_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4825                                           (1 << STRIPE_SYNCING) |
4826                                           (1 << STRIPE_REPLACED) |
4827                                           (1 << STRIPE_DELAYED) |
4828                                           (1 << STRIPE_BIT_DELAY) |
4829                                           (1 << STRIPE_FULL_WRITE) |
4830                                           (1 << STRIPE_BIOFILL_RUN) |
4831                                           (1 << STRIPE_COMPUTE_RUN)  |
4832                                           (1 << STRIPE_DISCARD) |
4833                                           (1 << STRIPE_BATCH_READY) |
4834                                           (1 << STRIPE_BATCH_ERR) |
4835                                           (1 << STRIPE_BITMAP_PENDING)),
4836                         "stripe state: %lx\n", sh->state);
4837                 WARN_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4838                                               (1 << STRIPE_REPLACED)),
4839                         "head stripe state: %lx\n", head_sh->state);
4840
4841                 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4842                                             (1 << STRIPE_PREREAD_ACTIVE) |
4843                                             (1 << STRIPE_DEGRADED) |
4844                                             (1 << STRIPE_ON_UNPLUG_LIST)),
4845                               head_sh->state & (1 << STRIPE_INSYNC));
4846
4847                 sh->check_state = head_sh->check_state;
4848                 sh->reconstruct_state = head_sh->reconstruct_state;
4849                 spin_lock_irq(&sh->stripe_lock);
4850                 sh->batch_head = NULL;
4851                 spin_unlock_irq(&sh->stripe_lock);
4852                 for (i = 0; i < sh->disks; i++) {
4853                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4854                                 do_wakeup = 1;
4855                         sh->dev[i].flags = head_sh->dev[i].flags &
4856                                 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4857                 }
4858                 if (handle_flags == 0 ||
4859                     sh->state & handle_flags)
4860                         set_bit(STRIPE_HANDLE, &sh->state);
4861                 raid5_release_stripe(sh);
4862         }
4863         spin_lock_irq(&head_sh->stripe_lock);
4864         head_sh->batch_head = NULL;
4865         spin_unlock_irq(&head_sh->stripe_lock);
4866         for (i = 0; i < head_sh->disks; i++)
4867                 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4868                         do_wakeup = 1;
4869         if (head_sh->state & handle_flags)
4870                 set_bit(STRIPE_HANDLE, &head_sh->state);
4871
4872         if (do_wakeup)
4873                 wake_up(&head_sh->raid_conf->wait_for_overlap);
4874 }
4875
4876 static void handle_stripe(struct stripe_head *sh)
4877 {
4878         struct stripe_head_state s;
4879         struct r5conf *conf = sh->raid_conf;
4880         int i;
4881         int prexor;
4882         int disks = sh->disks;
4883         struct r5dev *pdev, *qdev;
4884
4885         clear_bit(STRIPE_HANDLE, &sh->state);
4886
4887         /*
4888          * handle_stripe should not continue handle the batched stripe, only
4889          * the head of batch list or lone stripe can continue. Otherwise we
4890          * could see break_stripe_batch_list warns about the STRIPE_ACTIVE
4891          * is set for the batched stripe.
4892          */
4893         if (clear_batch_ready(sh))
4894                 return;
4895
4896         if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4897                 /* already being handled, ensure it gets handled
4898                  * again when current action finishes */
4899                 set_bit(STRIPE_HANDLE, &sh->state);
4900                 return;
4901         }
4902
4903         if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4904                 break_stripe_batch_list(sh, 0);
4905
4906         if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4907                 spin_lock(&sh->stripe_lock);
4908                 /*
4909                  * Cannot process 'sync' concurrently with 'discard'.
4910                  * Flush data in r5cache before 'sync'.
4911                  */
4912                 if (!test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state) &&
4913                     !test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) &&
4914                     !test_bit(STRIPE_DISCARD, &sh->state) &&
4915                     test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4916                         set_bit(STRIPE_SYNCING, &sh->state);
4917                         clear_bit(STRIPE_INSYNC, &sh->state);
4918                         clear_bit(STRIPE_REPLACED, &sh->state);
4919                 }
4920                 spin_unlock(&sh->stripe_lock);
4921         }
4922         clear_bit(STRIPE_DELAYED, &sh->state);
4923
4924         pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4925                 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4926                (unsigned long long)sh->sector, sh->state,
4927                atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4928                sh->check_state, sh->reconstruct_state);
4929
4930         analyse_stripe(sh, &s);
4931
4932         if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4933                 goto finish;
4934
4935         if (s.handle_bad_blocks ||
4936             test_bit(MD_SB_CHANGE_PENDING, &conf->mddev->sb_flags)) {
4937                 set_bit(STRIPE_HANDLE, &sh->state);
4938                 goto finish;
4939         }
4940
4941         if (unlikely(s.blocked_rdev)) {
4942                 if (s.syncing || s.expanding || s.expanded ||
4943                     s.replacing || s.to_write || s.written) {
4944                         set_bit(STRIPE_HANDLE, &sh->state);
4945                         goto finish;
4946                 }
4947                 /* There is nothing for the blocked_rdev to block */
4948                 rdev_dec_pending(s.blocked_rdev, conf->mddev);
4949                 s.blocked_rdev = NULL;
4950         }
4951
4952         if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4953                 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4954                 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4955         }
4956
4957         pr_debug("locked=%d uptodate=%d to_read=%d"
4958                " to_write=%d failed=%d failed_num=%d,%d\n",
4959                s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4960                s.failed_num[0], s.failed_num[1]);
4961         /*
4962          * check if the array has lost more than max_degraded devices and,
4963          * if so, some requests might need to be failed.
4964          *
4965          * When journal device failed (log_failed), we will only process
4966          * the stripe if there is data need write to raid disks
4967          */
4968         if (s.failed > conf->max_degraded ||
4969             (s.log_failed && s.injournal == 0)) {
4970                 sh->check_state = 0;
4971                 sh->reconstruct_state = 0;
4972                 break_stripe_batch_list(sh, 0);
4973                 if (s.to_read+s.to_write+s.written)
4974                         handle_failed_stripe(conf, sh, &s, disks);
4975                 if (s.syncing + s.replacing)
4976                         handle_failed_sync(conf, sh, &s);
4977         }
4978
4979         /* Now we check to see if any write operations have recently
4980          * completed
4981          */
4982         prexor = 0;
4983         if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4984                 prexor = 1;
4985         if (sh->reconstruct_state == reconstruct_state_drain_result ||
4986             sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4987                 sh->reconstruct_state = reconstruct_state_idle;
4988
4989                 /* All the 'written' buffers and the parity block are ready to
4990                  * be written back to disk
4991                  */
4992                 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4993                        !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4994                 BUG_ON(sh->qd_idx >= 0 &&
4995                        !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4996                        !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4997                 for (i = disks; i--; ) {
4998                         struct r5dev *dev = &sh->dev[i];
4999                         if (test_bit(R5_LOCKED, &dev->flags) &&
5000                                 (i == sh->pd_idx || i == sh->qd_idx ||
5001                                  dev->written || test_bit(R5_InJournal,
5002                                                           &dev->flags))) {
5003                                 pr_debug("Writing block %d\n", i);
5004                                 set_bit(R5_Wantwrite, &dev->flags);
5005                                 if (prexor)
5006                                         continue;
5007                                 if (s.failed > 1)
5008                                         continue;
5009                                 if (!test_bit(R5_Insync, &dev->flags) ||
5010                                     ((i == sh->pd_idx || i == sh->qd_idx)  &&
5011                                      s.failed == 0))
5012                                         set_bit(STRIPE_INSYNC, &sh->state);
5013                         }
5014                 }
5015                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5016                         s.dec_preread_active = 1;
5017         }
5018
5019         /*
5020          * might be able to return some write requests if the parity blocks
5021          * are safe, or on a failed drive
5022          */
5023         pdev = &sh->dev[sh->pd_idx];
5024         s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
5025                 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
5026         qdev = &sh->dev[sh->qd_idx];
5027         s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
5028                 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
5029                 || conf->level < 6;
5030
5031         if (s.written &&
5032             (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
5033                              && !test_bit(R5_LOCKED, &pdev->flags)
5034                              && (test_bit(R5_UPTODATE, &pdev->flags) ||
5035                                  test_bit(R5_Discard, &pdev->flags))))) &&
5036             (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
5037                              && !test_bit(R5_LOCKED, &qdev->flags)
5038                              && (test_bit(R5_UPTODATE, &qdev->flags) ||
5039                                  test_bit(R5_Discard, &qdev->flags))))))
5040                 handle_stripe_clean_event(conf, sh, disks);
5041
5042         if (s.just_cached)
5043                 r5c_handle_cached_data_endio(conf, sh, disks);
5044         log_stripe_write_finished(sh);
5045
5046         /* Now we might consider reading some blocks, either to check/generate
5047          * parity, or to satisfy requests
5048          * or to load a block that is being partially written.
5049          */
5050         if (s.to_read || s.non_overwrite
5051             || (s.to_write && s.failed)
5052             || (s.syncing && (s.uptodate + s.compute < disks))
5053             || s.replacing
5054             || s.expanding)
5055                 handle_stripe_fill(sh, &s, disks);
5056
5057         /*
5058          * When the stripe finishes full journal write cycle (write to journal
5059          * and raid disk), this is the clean up procedure so it is ready for
5060          * next operation.
5061          */
5062         r5c_finish_stripe_write_out(conf, sh, &s);
5063
5064         /*
5065          * Now to consider new write requests, cache write back and what else,
5066          * if anything should be read.  We do not handle new writes when:
5067          * 1/ A 'write' operation (copy+xor) is already in flight.
5068          * 2/ A 'check' operation is in flight, as it may clobber the parity
5069          *    block.
5070          * 3/ A r5c cache log write is in flight.
5071          */
5072
5073         if (!sh->reconstruct_state && !sh->check_state && !sh->log_io) {
5074                 if (!r5c_is_writeback(conf->log)) {
5075                         if (s.to_write)
5076                                 handle_stripe_dirtying(conf, sh, &s, disks);
5077                 } else { /* write back cache */
5078                         int ret = 0;
5079
5080                         /* First, try handle writes in caching phase */
5081                         if (s.to_write)
5082                                 ret = r5c_try_caching_write(conf, sh, &s,
5083                                                             disks);
5084                         /*
5085                          * If caching phase failed: ret == -EAGAIN
5086                          *    OR
5087                          * stripe under reclaim: !caching && injournal
5088                          *
5089                          * fall back to handle_stripe_dirtying()
5090                          */
5091                         if (ret == -EAGAIN ||
5092                             /* stripe under reclaim: !caching && injournal */
5093                             (!test_bit(STRIPE_R5C_CACHING, &sh->state) &&
5094                              s.injournal > 0)) {
5095                                 ret = handle_stripe_dirtying(conf, sh, &s,
5096                                                              disks);
5097                                 if (ret == -EAGAIN)
5098                                         goto finish;
5099                         }
5100                 }
5101         }
5102
5103         /* maybe we need to check and possibly fix the parity for this stripe
5104          * Any reads will already have been scheduled, so we just see if enough
5105          * data is available.  The parity check is held off while parity
5106          * dependent operations are in flight.
5107          */
5108         if (sh->check_state ||
5109             (s.syncing && s.locked == 0 &&
5110              !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
5111              !test_bit(STRIPE_INSYNC, &sh->state))) {
5112                 if (conf->level == 6)
5113                         handle_parity_checks6(conf, sh, &s, disks);
5114                 else
5115                         handle_parity_checks5(conf, sh, &s, disks);
5116         }
5117
5118         if ((s.replacing || s.syncing) && s.locked == 0
5119             && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
5120             && !test_bit(STRIPE_REPLACED, &sh->state)) {
5121                 /* Write out to replacement devices where possible */
5122                 for (i = 0; i < conf->raid_disks; i++)
5123                         if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
5124                                 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
5125                                 set_bit(R5_WantReplace, &sh->dev[i].flags);
5126                                 set_bit(R5_LOCKED, &sh->dev[i].flags);
5127                                 s.locked++;
5128                         }
5129                 if (s.replacing)
5130                         set_bit(STRIPE_INSYNC, &sh->state);
5131                 set_bit(STRIPE_REPLACED, &sh->state);
5132         }
5133         if ((s.syncing || s.replacing) && s.locked == 0 &&
5134             !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
5135             test_bit(STRIPE_INSYNC, &sh->state)) {
5136                 md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), 1);
5137                 clear_bit(STRIPE_SYNCING, &sh->state);
5138                 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
5139                         wake_up(&conf->wait_for_overlap);
5140         }
5141
5142         /* If the failed drives are just a ReadError, then we might need
5143          * to progress the repair/check process
5144          */
5145         if (s.failed <= conf->max_degraded && !conf->mddev->ro)
5146                 for (i = 0; i < s.failed; i++) {
5147                         struct r5dev *dev = &sh->dev[s.failed_num[i]];
5148                         if (test_bit(R5_ReadError, &dev->flags)
5149                             && !test_bit(R5_LOCKED, &dev->flags)
5150                             && test_bit(R5_UPTODATE, &dev->flags)
5151                                 ) {
5152                                 if (!test_bit(R5_ReWrite, &dev->flags)) {
5153                                         set_bit(R5_Wantwrite, &dev->flags);
5154                                         set_bit(R5_ReWrite, &dev->flags);
5155                                 } else
5156                                         /* let's read it back */
5157                                         set_bit(R5_Wantread, &dev->flags);
5158                                 set_bit(R5_LOCKED, &dev->flags);
5159                                 s.locked++;
5160                         }
5161                 }
5162
5163         /* Finish reconstruct operations initiated by the expansion process */
5164         if (sh->reconstruct_state == reconstruct_state_result) {
5165                 struct stripe_head *sh_src
5166                         = raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
5167                 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
5168                         /* sh cannot be written until sh_src has been read.
5169                          * so arrange for sh to be delayed a little
5170                          */
5171                         set_bit(STRIPE_DELAYED, &sh->state);
5172                         set_bit(STRIPE_HANDLE, &sh->state);
5173                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
5174                                               &sh_src->state))
5175                                 atomic_inc(&conf->preread_active_stripes);
5176                         raid5_release_stripe(sh_src);
5177                         goto finish;
5178                 }
5179                 if (sh_src)
5180                         raid5_release_stripe(sh_src);
5181
5182                 sh->reconstruct_state = reconstruct_state_idle;
5183                 clear_bit(STRIPE_EXPANDING, &sh->state);
5184                 for (i = conf->raid_disks; i--; ) {
5185                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
5186                         set_bit(R5_LOCKED, &sh->dev[i].flags);
5187                         s.locked++;
5188                 }
5189         }
5190
5191         if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
5192             !sh->reconstruct_state) {
5193                 /* Need to write out all blocks after computing parity */
5194                 sh->disks = conf->raid_disks;
5195                 stripe_set_idx(sh->sector, conf, 0, sh);
5196                 schedule_reconstruction(sh, &s, 1, 1);
5197         } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
5198                 clear_bit(STRIPE_EXPAND_READY, &sh->state);
5199                 atomic_dec(&conf->reshape_stripes);
5200                 wake_up(&conf->wait_for_overlap);
5201                 md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), 1);
5202         }
5203
5204         if (s.expanding && s.locked == 0 &&
5205             !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
5206                 handle_stripe_expansion(conf, sh);
5207
5208 finish:
5209         /* wait for this device to become unblocked */
5210         if (unlikely(s.blocked_rdev)) {
5211                 if (conf->mddev->external)
5212                         md_wait_for_blocked_rdev(s.blocked_rdev,
5213                                                  conf->mddev);
5214                 else
5215                         /* Internal metadata will immediately
5216                          * be written by raid5d, so we don't
5217                          * need to wait here.
5218                          */
5219                         rdev_dec_pending(s.blocked_rdev,
5220                                          conf->mddev);
5221         }
5222
5223         if (s.handle_bad_blocks)
5224                 for (i = disks; i--; ) {
5225                         struct md_rdev *rdev;
5226                         struct r5dev *dev = &sh->dev[i];
5227                         if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
5228                                 /* We own a safe reference to the rdev */
5229                                 rdev = conf->disks[i].rdev;
5230                                 if (!rdev_set_badblocks(rdev, sh->sector,
5231                                                         RAID5_STRIPE_SECTORS(conf), 0))
5232                                         md_error(conf->mddev, rdev);
5233                                 rdev_dec_pending(rdev, conf->mddev);
5234                         }
5235                         if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
5236                                 rdev = conf->disks[i].rdev;
5237                                 rdev_clear_badblocks(rdev, sh->sector,
5238                                                      RAID5_STRIPE_SECTORS(conf), 0);
5239                                 rdev_dec_pending(rdev, conf->mddev);
5240                         }
5241                         if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
5242                                 rdev = conf->disks[i].replacement;
5243                                 if (!rdev)
5244                                         /* rdev have been moved down */
5245                                         rdev = conf->disks[i].rdev;
5246                                 rdev_clear_badblocks(rdev, sh->sector,
5247                                                      RAID5_STRIPE_SECTORS(conf), 0);
5248                                 rdev_dec_pending(rdev, conf->mddev);
5249                         }
5250                 }
5251
5252         if (s.ops_request)
5253                 raid_run_ops(sh, s.ops_request);
5254
5255         ops_run_io(sh, &s);
5256
5257         if (s.dec_preread_active) {
5258                 /* We delay this until after ops_run_io so that if make_request
5259                  * is waiting on a flush, it won't continue until the writes
5260                  * have actually been submitted.
5261                  */
5262                 atomic_dec(&conf->preread_active_stripes);
5263                 if (atomic_read(&conf->preread_active_stripes) <
5264                     IO_THRESHOLD)
5265                         md_wakeup_thread(conf->mddev->thread);
5266         }
5267
5268         clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
5269 }
5270
5271 static void raid5_activate_delayed(struct r5conf *conf)
5272 {
5273         if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
5274                 while (!list_empty(&conf->delayed_list)) {
5275                         struct list_head *l = conf->delayed_list.next;
5276                         struct stripe_head *sh;
5277                         sh = list_entry(l, struct stripe_head, lru);
5278                         list_del_init(l);
5279                         clear_bit(STRIPE_DELAYED, &sh->state);
5280                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5281                                 atomic_inc(&conf->preread_active_stripes);
5282                         list_add_tail(&sh->lru, &conf->hold_list);
5283                         raid5_wakeup_stripe_thread(sh);
5284                 }
5285         }
5286 }
5287
5288 static void activate_bit_delay(struct r5conf *conf,
5289         struct list_head *temp_inactive_list)
5290 {
5291         /* device_lock is held */
5292         struct list_head head;
5293         list_add(&head, &conf->bitmap_list);
5294         list_del_init(&conf->bitmap_list);
5295         while (!list_empty(&head)) {
5296                 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
5297                 int hash;
5298                 list_del_init(&sh->lru);
5299                 atomic_inc(&sh->count);
5300                 hash = sh->hash_lock_index;
5301                 __release_stripe(conf, sh, &temp_inactive_list[hash]);
5302         }
5303 }
5304
5305 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
5306 {
5307         struct r5conf *conf = mddev->private;
5308         sector_t sector = bio->bi_iter.bi_sector;
5309         unsigned int chunk_sectors;
5310         unsigned int bio_sectors = bio_sectors(bio);
5311
5312         WARN_ON_ONCE(bio->bi_partno);
5313
5314         chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
5315         return  chunk_sectors >=
5316                 ((sector & (chunk_sectors - 1)) + bio_sectors);
5317 }
5318
5319 /*
5320  *  add bio to the retry LIFO  ( in O(1) ... we are in interrupt )
5321  *  later sampled by raid5d.
5322  */
5323 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
5324 {
5325         unsigned long flags;
5326
5327         spin_lock_irqsave(&conf->device_lock, flags);
5328
5329         bi->bi_next = conf->retry_read_aligned_list;
5330         conf->retry_read_aligned_list = bi;
5331
5332         spin_unlock_irqrestore(&conf->device_lock, flags);
5333         md_wakeup_thread(conf->mddev->thread);
5334 }
5335
5336 static struct bio *remove_bio_from_retry(struct r5conf *conf,
5337                                          unsigned int *offset)
5338 {
5339         struct bio *bi;
5340
5341         bi = conf->retry_read_aligned;
5342         if (bi) {
5343                 *offset = conf->retry_read_offset;
5344                 conf->retry_read_aligned = NULL;
5345                 return bi;
5346         }
5347         bi = conf->retry_read_aligned_list;
5348         if(bi) {
5349                 conf->retry_read_aligned_list = bi->bi_next;
5350                 bi->bi_next = NULL;
5351                 *offset = 0;
5352         }
5353
5354         return bi;
5355 }
5356
5357 /*
5358  *  The "raid5_align_endio" should check if the read succeeded and if it
5359  *  did, call bio_endio on the original bio (having bio_put the new bio
5360  *  first).
5361  *  If the read failed..
5362  */
5363 static void raid5_align_endio(struct bio *bi)
5364 {
5365         struct bio* raid_bi  = bi->bi_private;
5366         struct mddev *mddev;
5367         struct r5conf *conf;
5368         struct md_rdev *rdev;
5369         blk_status_t error = bi->bi_status;
5370
5371         bio_put(bi);
5372
5373         rdev = (void*)raid_bi->bi_next;
5374         raid_bi->bi_next = NULL;
5375         mddev = rdev->mddev;
5376         conf = mddev->private;
5377
5378         rdev_dec_pending(rdev, conf->mddev);
5379
5380         if (!error) {
5381                 bio_endio(raid_bi);
5382                 if (atomic_dec_and_test(&conf->active_aligned_reads))
5383                         wake_up(&conf->wait_for_quiescent);
5384                 return;
5385         }
5386
5387         pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
5388
5389         add_bio_to_retry(raid_bi, conf);
5390 }
5391
5392 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
5393 {
5394         struct r5conf *conf = mddev->private;
5395         int dd_idx;
5396         struct bio* align_bi;
5397         struct md_rdev *rdev;
5398         sector_t end_sector;
5399
5400         if (!in_chunk_boundary(mddev, raid_bio)) {
5401                 pr_debug("%s: non aligned\n", __func__);
5402                 return 0;
5403         }
5404         /*
5405          * use bio_clone_fast to make a copy of the bio
5406          */
5407         align_bi = bio_clone_fast(raid_bio, GFP_NOIO, &mddev->bio_set);
5408         if (!align_bi)
5409                 return 0;
5410         /*
5411          *   set bi_end_io to a new function, and set bi_private to the
5412          *     original bio.
5413          */
5414         align_bi->bi_end_io  = raid5_align_endio;
5415         align_bi->bi_private = raid_bio;
5416         /*
5417          *      compute position
5418          */
5419         align_bi->bi_iter.bi_sector =
5420                 raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
5421                                      0, &dd_idx, NULL);
5422
5423         end_sector = bio_end_sector(align_bi);
5424         rcu_read_lock();
5425         rdev = rcu_dereference(conf->disks[dd_idx].replacement);
5426         if (!rdev || test_bit(Faulty, &rdev->flags) ||
5427             rdev->recovery_offset < end_sector) {
5428                 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
5429                 if (rdev &&
5430                     (test_bit(Faulty, &rdev->flags) ||
5431                     !(test_bit(In_sync, &rdev->flags) ||
5432                       rdev->recovery_offset >= end_sector)))
5433                         rdev = NULL;
5434         }
5435
5436         if (r5c_big_stripe_cached(conf, align_bi->bi_iter.bi_sector)) {
5437                 rcu_read_unlock();
5438                 bio_put(align_bi);
5439                 return 0;
5440         }
5441
5442         if (rdev) {
5443                 sector_t first_bad;
5444                 int bad_sectors;
5445
5446                 atomic_inc(&rdev->nr_pending);
5447                 rcu_read_unlock();
5448                 raid_bio->bi_next = (void*)rdev;
5449                 bio_set_dev(align_bi, rdev->bdev);
5450
5451                 if (is_badblock(rdev, align_bi->bi_iter.bi_sector,
5452                                 bio_sectors(align_bi),
5453                                 &first_bad, &bad_sectors)) {
5454                         bio_put(align_bi);
5455                         rdev_dec_pending(rdev, mddev);
5456                         return 0;
5457                 }
5458
5459                 /* No reshape active, so we can trust rdev->data_offset */
5460                 align_bi->bi_iter.bi_sector += rdev->data_offset;
5461
5462                 spin_lock_irq(&conf->device_lock);
5463                 wait_event_lock_irq(conf->wait_for_quiescent,
5464                                     conf->quiesce == 0,
5465                                     conf->device_lock);
5466                 atomic_inc(&conf->active_aligned_reads);
5467                 spin_unlock_irq(&conf->device_lock);
5468
5469                 if (mddev->gendisk)
5470                         trace_block_bio_remap(align_bi->bi_disk->queue,
5471                                               align_bi, disk_devt(mddev->gendisk),
5472                                               raid_bio->bi_iter.bi_sector);
5473                 submit_bio_noacct(align_bi);
5474                 return 1;
5475         } else {
5476                 rcu_read_unlock();
5477                 bio_put(align_bi);
5478                 return 0;
5479         }
5480 }
5481
5482 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
5483 {
5484         struct bio *split;
5485         sector_t sector = raid_bio->bi_iter.bi_sector;
5486         unsigned chunk_sects = mddev->chunk_sectors;
5487         unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
5488
5489         if (sectors < bio_sectors(raid_bio)) {
5490                 struct r5conf *conf = mddev->private;
5491                 split = bio_split(raid_bio, sectors, GFP_NOIO, &conf->bio_split);
5492                 bio_chain(split, raid_bio);
5493                 submit_bio_noacct(raid_bio);
5494                 raid_bio = split;
5495         }
5496
5497         if (!raid5_read_one_chunk(mddev, raid_bio))
5498                 return raid_bio;
5499
5500         return NULL;
5501 }
5502
5503 /* __get_priority_stripe - get the next stripe to process
5504  *
5505  * Full stripe writes are allowed to pass preread active stripes up until
5506  * the bypass_threshold is exceeded.  In general the bypass_count
5507  * increments when the handle_list is handled before the hold_list; however, it
5508  * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
5509  * stripe with in flight i/o.  The bypass_count will be reset when the
5510  * head of the hold_list has changed, i.e. the head was promoted to the
5511  * handle_list.
5512  */
5513 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
5514 {
5515         struct stripe_head *sh, *tmp;
5516         struct list_head *handle_list = NULL;
5517         struct r5worker_group *wg;
5518         bool second_try = !r5c_is_writeback(conf->log) &&
5519                 !r5l_log_disk_error(conf);
5520         bool try_loprio = test_bit(R5C_LOG_TIGHT, &conf->cache_state) ||
5521                 r5l_log_disk_error(conf);
5522
5523 again:
5524         wg = NULL;
5525         sh = NULL;
5526         if (conf->worker_cnt_per_group == 0) {
5527                 handle_list = try_loprio ? &conf->loprio_list :
5528                                         &conf->handle_list;
5529         } else if (group != ANY_GROUP) {
5530                 handle_list = try_loprio ? &conf->worker_groups[group].loprio_list :
5531                                 &conf->worker_groups[group].handle_list;
5532                 wg = &conf->worker_groups[group];
5533         } else {
5534                 int i;
5535                 for (i = 0; i < conf->group_cnt; i++) {
5536                         handle_list = try_loprio ? &conf->worker_groups[i].loprio_list :
5537                                 &conf->worker_groups[i].handle_list;
5538                         wg = &conf->worker_groups[i];
5539                         if (!list_empty(handle_list))
5540                                 break;
5541                 }
5542         }
5543
5544         pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
5545                   __func__,
5546                   list_empty(handle_list) ? "empty" : "busy",
5547                   list_empty(&conf->hold_list) ? "empty" : "busy",
5548                   atomic_read(&conf->pending_full_writes), conf->bypass_count);
5549
5550         if (!list_empty(handle_list)) {
5551                 sh = list_entry(handle_list->next, typeof(*sh), lru);
5552
5553                 if (list_empty(&conf->hold_list))
5554                         conf->bypass_count = 0;
5555                 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
5556                         if (conf->hold_list.next == conf->last_hold)
5557                                 conf->bypass_count++;
5558                         else {
5559                                 conf->last_hold = conf->hold_list.next;
5560                                 conf->bypass_count -= conf->bypass_threshold;
5561                                 if (conf->bypass_count < 0)
5562                                         conf->bypass_count = 0;
5563                         }
5564                 }
5565         } else if (!list_empty(&conf->hold_list) &&
5566                    ((conf->bypass_threshold &&
5567                      conf->bypass_count > conf->bypass_threshold) ||
5568                     atomic_read(&conf->pending_full_writes) == 0)) {
5569
5570                 list_for_each_entry(tmp, &conf->hold_list,  lru) {
5571                         if (conf->worker_cnt_per_group == 0 ||
5572                             group == ANY_GROUP ||
5573                             !cpu_online(tmp->cpu) ||
5574                             cpu_to_group(tmp->cpu) == group) {
5575                                 sh = tmp;
5576                                 break;
5577                         }
5578                 }
5579
5580                 if (sh) {
5581                         conf->bypass_count -= conf->bypass_threshold;
5582                         if (conf->bypass_count < 0)
5583                                 conf->bypass_count = 0;
5584                 }
5585                 wg = NULL;
5586         }
5587
5588         if (!sh) {
5589                 if (second_try)
5590                         return NULL;
5591                 second_try = true;
5592                 try_loprio = !try_loprio;
5593                 goto again;
5594         }
5595
5596         if (wg) {
5597                 wg->stripes_cnt--;
5598                 sh->group = NULL;
5599         }
5600         list_del_init(&sh->lru);
5601         BUG_ON(atomic_inc_return(&sh->count) != 1);
5602         return sh;
5603 }
5604
5605 struct raid5_plug_cb {
5606         struct blk_plug_cb      cb;
5607         struct list_head        list;
5608         struct list_head        temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5609 };
5610
5611 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5612 {
5613         struct raid5_plug_cb *cb = container_of(
5614                 blk_cb, struct raid5_plug_cb, cb);
5615         struct stripe_head *sh;
5616         struct mddev *mddev = cb->cb.data;
5617         struct r5conf *conf = mddev->private;
5618         int cnt = 0;
5619         int hash;
5620
5621         if (cb->list.next && !list_empty(&cb->list)) {
5622                 spin_lock_irq(&conf->device_lock);
5623                 while (!list_empty(&cb->list)) {
5624                         sh = list_first_entry(&cb->list, struct stripe_head, lru);
5625                         list_del_init(&sh->lru);
5626                         /*
5627                          * avoid race release_stripe_plug() sees
5628                          * STRIPE_ON_UNPLUG_LIST clear but the stripe
5629                          * is still in our list
5630                          */
5631                         smp_mb__before_atomic();
5632                         clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5633                         /*
5634                          * STRIPE_ON_RELEASE_LIST could be set here. In that
5635                          * case, the count is always > 1 here
5636                          */
5637                         hash = sh->hash_lock_index;
5638                         __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5639                         cnt++;
5640                 }
5641                 spin_unlock_irq(&conf->device_lock);
5642         }
5643         release_inactive_stripe_list(conf, cb->temp_inactive_list,
5644                                      NR_STRIPE_HASH_LOCKS);
5645         if (mddev->queue)
5646                 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5647         kfree(cb);
5648 }
5649
5650 static void release_stripe_plug(struct mddev *mddev,
5651                                 struct stripe_head *sh)
5652 {
5653         struct blk_plug_cb *blk_cb = blk_check_plugged(
5654                 raid5_unplug, mddev,
5655                 sizeof(struct raid5_plug_cb));
5656         struct raid5_plug_cb *cb;
5657
5658         if (!blk_cb) {
5659                 raid5_release_stripe(sh);
5660                 return;
5661         }
5662
5663         cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5664
5665         if (cb->list.next == NULL) {
5666                 int i;
5667                 INIT_LIST_HEAD(&cb->list);
5668                 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5669                         INIT_LIST_HEAD(cb->temp_inactive_list + i);
5670         }
5671
5672         if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5673                 list_add_tail(&sh->lru, &cb->list);
5674         else
5675                 raid5_release_stripe(sh);
5676 }
5677
5678 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5679 {
5680         struct r5conf *conf = mddev->private;
5681         sector_t logical_sector, last_sector;
5682         struct stripe_head *sh;
5683         int stripe_sectors;
5684
5685         if (mddev->reshape_position != MaxSector)
5686                 /* Skip discard while reshape is happening */
5687                 return;
5688
5689         logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5690         last_sector = bio_end_sector(bi);
5691
5692         bi->bi_next = NULL;
5693
5694         stripe_sectors = conf->chunk_sectors *
5695                 (conf->raid_disks - conf->max_degraded);
5696         logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5697                                                stripe_sectors);
5698         sector_div(last_sector, stripe_sectors);
5699
5700         logical_sector *= conf->chunk_sectors;
5701         last_sector *= conf->chunk_sectors;
5702
5703         for (; logical_sector < last_sector;
5704              logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5705                 DEFINE_WAIT(w);
5706                 int d;
5707         again:
5708                 sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5709                 prepare_to_wait(&conf->wait_for_overlap, &w,
5710                                 TASK_UNINTERRUPTIBLE);
5711                 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5712                 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5713                         raid5_release_stripe(sh);
5714                         schedule();
5715                         goto again;
5716                 }
5717                 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5718                 spin_lock_irq(&sh->stripe_lock);
5719                 for (d = 0; d < conf->raid_disks; d++) {
5720                         if (d == sh->pd_idx || d == sh->qd_idx)
5721                                 continue;
5722                         if (sh->dev[d].towrite || sh->dev[d].toread) {
5723                                 set_bit(R5_Overlap, &sh->dev[d].flags);
5724                                 spin_unlock_irq(&sh->stripe_lock);
5725                                 raid5_release_stripe(sh);
5726                                 schedule();
5727                                 goto again;
5728                         }
5729                 }
5730                 set_bit(STRIPE_DISCARD, &sh->state);
5731                 finish_wait(&conf->wait_for_overlap, &w);
5732                 sh->overwrite_disks = 0;
5733                 for (d = 0; d < conf->raid_disks; d++) {
5734                         if (d == sh->pd_idx || d == sh->qd_idx)
5735                                 continue;
5736                         sh->dev[d].towrite = bi;
5737                         set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5738                         bio_inc_remaining(bi);
5739                         md_write_inc(mddev, bi);
5740                         sh->overwrite_disks++;
5741                 }
5742                 spin_unlock_irq(&sh->stripe_lock);
5743                 if (conf->mddev->bitmap) {
5744                         for (d = 0;
5745                              d < conf->raid_disks - conf->max_degraded;
5746                              d++)
5747                                 md_bitmap_startwrite(mddev->bitmap,
5748                                                      sh->sector,
5749                                                      RAID5_STRIPE_SECTORS(conf),
5750                                                      0);
5751                         sh->bm_seq = conf->seq_flush + 1;
5752                         set_bit(STRIPE_BIT_DELAY, &sh->state);
5753                 }
5754
5755                 set_bit(STRIPE_HANDLE, &sh->state);
5756                 clear_bit(STRIPE_DELAYED, &sh->state);
5757                 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5758                         atomic_inc(&conf->preread_active_stripes);
5759                 release_stripe_plug(mddev, sh);
5760         }
5761
5762         bio_endio(bi);
5763 }
5764
5765 static bool raid5_make_request(struct mddev *mddev, struct bio * bi)
5766 {
5767         struct r5conf *conf = mddev->private;
5768         int dd_idx;
5769         sector_t new_sector;
5770         sector_t logical_sector, last_sector;
5771         struct stripe_head *sh;
5772         const int rw = bio_data_dir(bi);
5773         DEFINE_WAIT(w);
5774         bool do_prepare;
5775         bool do_flush = false;
5776
5777         if (unlikely(bi->bi_opf & REQ_PREFLUSH)) {
5778                 int ret = log_handle_flush_request(conf, bi);
5779
5780                 if (ret == 0)
5781                         return true;
5782                 if (ret == -ENODEV) {
5783                         if (md_flush_request(mddev, bi))
5784                                 return true;
5785                 }
5786                 /* ret == -EAGAIN, fallback */
5787                 /*
5788                  * if r5l_handle_flush_request() didn't clear REQ_PREFLUSH,
5789                  * we need to flush journal device
5790                  */
5791                 do_flush = bi->bi_opf & REQ_PREFLUSH;
5792         }
5793
5794         if (!md_write_start(mddev, bi))
5795                 return false;
5796         /*
5797          * If array is degraded, better not do chunk aligned read because
5798          * later we might have to read it again in order to reconstruct
5799          * data on failed drives.
5800          */
5801         if (rw == READ && mddev->degraded == 0 &&
5802             mddev->reshape_position == MaxSector) {
5803                 bi = chunk_aligned_read(mddev, bi);
5804                 if (!bi)
5805                         return true;
5806         }
5807
5808         if (unlikely(bio_op(bi) == REQ_OP_DISCARD)) {
5809                 make_discard_request(mddev, bi);
5810                 md_write_end(mddev);
5811                 return true;
5812         }
5813
5814         logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5815         last_sector = bio_end_sector(bi);
5816         bi->bi_next = NULL;
5817
5818         prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5819         for (; logical_sector < last_sector; logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5820                 int previous;
5821                 int seq;
5822
5823                 do_prepare = false;
5824         retry:
5825                 seq = read_seqcount_begin(&conf->gen_lock);
5826                 previous = 0;
5827                 if (do_prepare)
5828                         prepare_to_wait(&conf->wait_for_overlap, &w,
5829                                 TASK_UNINTERRUPTIBLE);
5830                 if (unlikely(conf->reshape_progress != MaxSector)) {
5831                         /* spinlock is needed as reshape_progress may be
5832                          * 64bit on a 32bit platform, and so it might be
5833                          * possible to see a half-updated value
5834                          * Of course reshape_progress could change after
5835                          * the lock is dropped, so once we get a reference
5836                          * to the stripe that we think it is, we will have
5837                          * to check again.
5838                          */
5839                         spin_lock_irq(&conf->device_lock);
5840                         if (mddev->reshape_backwards
5841                             ? logical_sector < conf->reshape_progress
5842                             : logical_sector >= conf->reshape_progress) {
5843                                 previous = 1;
5844                         } else {
5845                                 if (mddev->reshape_backwards
5846                                     ? logical_sector < conf->reshape_safe
5847                                     : logical_sector >= conf->reshape_safe) {
5848                                         spin_unlock_irq(&conf->device_lock);
5849                                         schedule();
5850                                         do_prepare = true;
5851                                         goto retry;
5852                                 }
5853                         }
5854                         spin_unlock_irq(&conf->device_lock);
5855                 }
5856
5857                 new_sector = raid5_compute_sector(conf, logical_sector,
5858                                                   previous,
5859                                                   &dd_idx, NULL);
5860                 pr_debug("raid456: raid5_make_request, sector %llu logical %llu\n",
5861                         (unsigned long long)new_sector,
5862                         (unsigned long long)logical_sector);
5863
5864                 sh = raid5_get_active_stripe(conf, new_sector, previous,
5865                                        (bi->bi_opf & REQ_RAHEAD), 0);
5866                 if (sh) {
5867                         if (unlikely(previous)) {
5868                                 /* expansion might have moved on while waiting for a
5869                                  * stripe, so we must do the range check again.
5870                                  * Expansion could still move past after this
5871                                  * test, but as we are holding a reference to
5872                                  * 'sh', we know that if that happens,
5873                                  *  STRIPE_EXPANDING will get set and the expansion
5874                                  * won't proceed until we finish with the stripe.
5875                                  */
5876                                 int must_retry = 0;
5877                                 spin_lock_irq(&conf->device_lock);
5878                                 if (mddev->reshape_backwards
5879                                     ? logical_sector >= conf->reshape_progress
5880                                     : logical_sector < conf->reshape_progress)
5881                                         /* mismatch, need to try again */
5882                                         must_retry = 1;
5883                                 spin_unlock_irq(&conf->device_lock);
5884                                 if (must_retry) {
5885                                         raid5_release_stripe(sh);
5886                                         schedule();
5887                                         do_prepare = true;
5888                                         goto retry;
5889                                 }
5890                         }
5891                         if (read_seqcount_retry(&conf->gen_lock, seq)) {
5892                                 /* Might have got the wrong stripe_head
5893                                  * by accident
5894                                  */
5895                                 raid5_release_stripe(sh);
5896                                 goto retry;
5897                         }
5898
5899                         if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5900                             !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5901                                 /* Stripe is busy expanding or
5902                                  * add failed due to overlap.  Flush everything
5903                                  * and wait a while
5904                                  */
5905                                 md_wakeup_thread(mddev->thread);
5906                                 raid5_release_stripe(sh);
5907                                 schedule();
5908                                 do_prepare = true;
5909                                 goto retry;
5910                         }
5911                         if (do_flush) {
5912                                 set_bit(STRIPE_R5C_PREFLUSH, &sh->state);
5913                                 /* we only need flush for one stripe */
5914                                 do_flush = false;
5915                         }
5916
5917                         set_bit(STRIPE_HANDLE, &sh->state);
5918                         clear_bit(STRIPE_DELAYED, &sh->state);
5919                         if ((!sh->batch_head || sh == sh->batch_head) &&
5920                             (bi->bi_opf & REQ_SYNC) &&
5921                             !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5922                                 atomic_inc(&conf->preread_active_stripes);
5923                         release_stripe_plug(mddev, sh);
5924                 } else {
5925                         /* cannot get stripe for read-ahead, just give-up */
5926                         bi->bi_status = BLK_STS_IOERR;
5927                         break;
5928                 }
5929         }
5930         finish_wait(&conf->wait_for_overlap, &w);
5931
5932         if (rw == WRITE)
5933                 md_write_end(mddev);
5934         bio_endio(bi);
5935         return true;
5936 }
5937
5938 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5939
5940 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5941 {
5942         /* reshaping is quite different to recovery/resync so it is
5943          * handled quite separately ... here.
5944          *
5945          * On each call to sync_request, we gather one chunk worth of
5946          * destination stripes and flag them as expanding.
5947          * Then we find all the source stripes and request reads.
5948          * As the reads complete, handle_stripe will copy the data
5949          * into the destination stripe and release that stripe.
5950          */
5951         struct r5conf *conf = mddev->private;
5952         struct stripe_head *sh;
5953         struct md_rdev *rdev;
5954         sector_t first_sector, last_sector;
5955         int raid_disks = conf->previous_raid_disks;
5956         int data_disks = raid_disks - conf->max_degraded;
5957         int new_data_disks = conf->raid_disks - conf->max_degraded;
5958         int i;
5959         int dd_idx;
5960         sector_t writepos, readpos, safepos;
5961         sector_t stripe_addr;
5962         int reshape_sectors;
5963         struct list_head stripes;
5964         sector_t retn;
5965
5966         if (sector_nr == 0) {
5967                 /* If restarting in the middle, skip the initial sectors */
5968                 if (mddev->reshape_backwards &&
5969                     conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5970                         sector_nr = raid5_size(mddev, 0, 0)
5971                                 - conf->reshape_progress;
5972                 } else if (mddev->reshape_backwards &&
5973                            conf->reshape_progress == MaxSector) {
5974                         /* shouldn't happen, but just in case, finish up.*/
5975                         sector_nr = MaxSector;
5976                 } else if (!mddev->reshape_backwards &&
5977                            conf->reshape_progress > 0)
5978                         sector_nr = conf->reshape_progress;
5979                 sector_div(sector_nr, new_data_disks);
5980                 if (sector_nr) {
5981                         mddev->curr_resync_completed = sector_nr;
5982                         sysfs_notify_dirent_safe(mddev->sysfs_completed);
5983                         *skipped = 1;
5984                         retn = sector_nr;
5985                         goto finish;
5986                 }
5987         }
5988
5989         /* We need to process a full chunk at a time.
5990          * If old and new chunk sizes differ, we need to process the
5991          * largest of these
5992          */
5993
5994         reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5995
5996         /* We update the metadata at least every 10 seconds, or when
5997          * the data about to be copied would over-write the source of
5998          * the data at the front of the range.  i.e. one new_stripe
5999          * along from reshape_progress new_maps to after where
6000          * reshape_safe old_maps to
6001          */
6002         writepos = conf->reshape_progress;
6003         sector_div(writepos, new_data_disks);
6004         readpos = conf->reshape_progress;
6005         sector_div(readpos, data_disks);
6006         safepos = conf->reshape_safe;
6007         sector_div(safepos, data_disks);
6008         if (mddev->reshape_backwards) {
6009                 BUG_ON(writepos < reshape_sectors);
6010                 writepos -= reshape_sectors;
6011                 readpos += reshape_sectors;
6012                 safepos += reshape_sectors;
6013         } else {
6014                 writepos += reshape_sectors;
6015                 /* readpos and safepos are worst-case calculations.
6016                  * A negative number is overly pessimistic, and causes
6017                  * obvious problems for unsigned storage.  So clip to 0.
6018                  */
6019                 readpos -= min_t(sector_t, reshape_sectors, readpos);
6020                 safepos -= min_t(sector_t, reshape_sectors, safepos);
6021         }
6022
6023         /* Having calculated the 'writepos' possibly use it
6024          * to set 'stripe_addr' which is where we will write to.
6025          */
6026         if (mddev->reshape_backwards) {
6027                 BUG_ON(conf->reshape_progress == 0);
6028                 stripe_addr = writepos;
6029                 BUG_ON((mddev->dev_sectors &
6030                         ~((sector_t)reshape_sectors - 1))
6031                        - reshape_sectors - stripe_addr
6032                        != sector_nr);
6033         } else {
6034                 BUG_ON(writepos != sector_nr + reshape_sectors);
6035                 stripe_addr = sector_nr;
6036         }
6037
6038         /* 'writepos' is the most advanced device address we might write.
6039          * 'readpos' is the least advanced device address we might read.
6040          * 'safepos' is the least address recorded in the metadata as having
6041          *     been reshaped.
6042          * If there is a min_offset_diff, these are adjusted either by
6043          * increasing the safepos/readpos if diff is negative, or
6044          * increasing writepos if diff is positive.
6045          * If 'readpos' is then behind 'writepos', there is no way that we can
6046          * ensure safety in the face of a crash - that must be done by userspace
6047          * making a backup of the data.  So in that case there is no particular
6048          * rush to update metadata.
6049          * Otherwise if 'safepos' is behind 'writepos', then we really need to
6050          * update the metadata to advance 'safepos' to match 'readpos' so that
6051          * we can be safe in the event of a crash.
6052          * So we insist on updating metadata if safepos is behind writepos and
6053          * readpos is beyond writepos.
6054          * In any case, update the metadata every 10 seconds.
6055          * Maybe that number should be configurable, but I'm not sure it is
6056          * worth it.... maybe it could be a multiple of safemode_delay???
6057          */
6058         if (conf->min_offset_diff < 0) {
6059                 safepos += -conf->min_offset_diff;
6060                 readpos += -conf->min_offset_diff;
6061         } else
6062                 writepos += conf->min_offset_diff;
6063
6064         if ((mddev->reshape_backwards
6065              ? (safepos > writepos && readpos < writepos)
6066              : (safepos < writepos && readpos > writepos)) ||
6067             time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
6068                 /* Cannot proceed until we've updated the superblock... */
6069                 wait_event(conf->wait_for_overlap,
6070                            atomic_read(&conf->reshape_stripes)==0
6071                            || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6072                 if (atomic_read(&conf->reshape_stripes) != 0)
6073                         return 0;
6074                 mddev->reshape_position = conf->reshape_progress;
6075                 mddev->curr_resync_completed = sector_nr;
6076                 if (!mddev->reshape_backwards)
6077                         /* Can update recovery_offset */
6078                         rdev_for_each(rdev, mddev)
6079                                 if (rdev->raid_disk >= 0 &&
6080                                     !test_bit(Journal, &rdev->flags) &&
6081                                     !test_bit(In_sync, &rdev->flags) &&
6082                                     rdev->recovery_offset < sector_nr)
6083                                         rdev->recovery_offset = sector_nr;
6084
6085                 conf->reshape_checkpoint = jiffies;
6086                 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6087                 md_wakeup_thread(mddev->thread);
6088                 wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
6089                            test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6090                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6091                         return 0;
6092                 spin_lock_irq(&conf->device_lock);
6093                 conf->reshape_safe = mddev->reshape_position;
6094                 spin_unlock_irq(&conf->device_lock);
6095                 wake_up(&conf->wait_for_overlap);
6096                 sysfs_notify_dirent_safe(mddev->sysfs_completed);
6097         }
6098
6099         INIT_LIST_HEAD(&stripes);
6100         for (i = 0; i < reshape_sectors; i += RAID5_STRIPE_SECTORS(conf)) {
6101                 int j;
6102                 int skipped_disk = 0;
6103                 sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
6104                 set_bit(STRIPE_EXPANDING, &sh->state);
6105                 atomic_inc(&conf->reshape_stripes);
6106                 /* If any of this stripe is beyond the end of the old
6107                  * array, then we need to zero those blocks
6108                  */
6109                 for (j=sh->disks; j--;) {
6110                         sector_t s;
6111                         if (j == sh->pd_idx)
6112                                 continue;
6113                         if (conf->level == 6 &&
6114                             j == sh->qd_idx)
6115                                 continue;
6116                         s = raid5_compute_blocknr(sh, j, 0);
6117                         if (s < raid5_size(mddev, 0, 0)) {
6118                                 skipped_disk = 1;
6119                                 continue;
6120                         }
6121                         memset(page_address(sh->dev[j].page), 0, RAID5_STRIPE_SIZE(conf));
6122                         set_bit(R5_Expanded, &sh->dev[j].flags);
6123                         set_bit(R5_UPTODATE, &sh->dev[j].flags);
6124                 }
6125                 if (!skipped_disk) {
6126                         set_bit(STRIPE_EXPAND_READY, &sh->state);
6127                         set_bit(STRIPE_HANDLE, &sh->state);
6128                 }
6129                 list_add(&sh->lru, &stripes);
6130         }
6131         spin_lock_irq(&conf->device_lock);
6132         if (mddev->reshape_backwards)
6133                 conf->reshape_progress -= reshape_sectors * new_data_disks;
6134         else
6135                 conf->reshape_progress += reshape_sectors * new_data_disks;
6136         spin_unlock_irq(&conf->device_lock);
6137         /* Ok, those stripe are ready. We can start scheduling
6138          * reads on the source stripes.
6139          * The source stripes are determined by mapping the first and last
6140          * block on the destination stripes.
6141          */
6142         first_sector =
6143                 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
6144                                      1, &dd_idx, NULL);
6145         last_sector =
6146                 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
6147                                             * new_data_disks - 1),
6148                                      1, &dd_idx, NULL);
6149         if (last_sector >= mddev->dev_sectors)
6150                 last_sector = mddev->dev_sectors - 1;
6151         while (first_sector <= last_sector) {
6152                 sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
6153                 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
6154                 set_bit(STRIPE_HANDLE, &sh->state);
6155                 raid5_release_stripe(sh);
6156                 first_sector += RAID5_STRIPE_SECTORS(conf);
6157         }
6158         /* Now that the sources are clearly marked, we can release
6159          * the destination stripes
6160          */
6161         while (!list_empty(&stripes)) {
6162                 sh = list_entry(stripes.next, struct stripe_head, lru);
6163                 list_del_init(&sh->lru);
6164                 raid5_release_stripe(sh);
6165         }
6166         /* If this takes us to the resync_max point where we have to pause,
6167          * then we need to write out the superblock.
6168          */
6169         sector_nr += reshape_sectors;
6170         retn = reshape_sectors;
6171 finish:
6172         if (mddev->curr_resync_completed > mddev->resync_max ||
6173             (sector_nr - mddev->curr_resync_completed) * 2
6174             >= mddev->resync_max - mddev->curr_resync_completed) {
6175                 /* Cannot proceed until we've updated the superblock... */
6176                 wait_event(conf->wait_for_overlap,
6177                            atomic_read(&conf->reshape_stripes) == 0
6178                            || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6179                 if (atomic_read(&conf->reshape_stripes) != 0)
6180                         goto ret;
6181                 mddev->reshape_position = conf->reshape_progress;
6182                 mddev->curr_resync_completed = sector_nr;
6183                 if (!mddev->reshape_backwards)
6184                         /* Can update recovery_offset */
6185                         rdev_for_each(rdev, mddev)
6186                                 if (rdev->raid_disk >= 0 &&
6187                                     !test_bit(Journal, &rdev->flags) &&
6188                                     !test_bit(In_sync, &rdev->flags) &&
6189                                     rdev->recovery_offset < sector_nr)
6190                                         rdev->recovery_offset = sector_nr;
6191                 conf->reshape_checkpoint = jiffies;
6192                 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6193                 md_wakeup_thread(mddev->thread);
6194                 wait_event(mddev->sb_wait,
6195                            !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)
6196                            || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6197                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6198                         goto ret;
6199                 spin_lock_irq(&conf->device_lock);
6200                 conf->reshape_safe = mddev->reshape_position;
6201                 spin_unlock_irq(&conf->device_lock);
6202                 wake_up(&conf->wait_for_overlap);
6203                 sysfs_notify_dirent_safe(mddev->sysfs_completed);
6204         }
6205 ret:
6206         return retn;
6207 }
6208
6209 static inline sector_t raid5_sync_request(struct mddev *mddev, sector_t sector_nr,
6210                                           int *skipped)
6211 {
6212         struct r5conf *conf = mddev->private;
6213         struct stripe_head *sh;
6214         sector_t max_sector = mddev->dev_sectors;
6215         sector_t sync_blocks;
6216         int still_degraded = 0;
6217         int i;
6218
6219         if (sector_nr >= max_sector) {
6220                 /* just being told to finish up .. nothing much to do */
6221
6222                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
6223                         end_reshape(conf);
6224                         return 0;
6225                 }
6226
6227                 if (mddev->curr_resync < max_sector) /* aborted */
6228                         md_bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
6229                                            &sync_blocks, 1);
6230                 else /* completed sync */
6231                         conf->fullsync = 0;
6232                 md_bitmap_close_sync(mddev->bitmap);
6233
6234                 return 0;
6235         }
6236
6237         /* Allow raid5_quiesce to complete */
6238         wait_event(conf->wait_for_overlap, conf->quiesce != 2);
6239
6240         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6241                 return reshape_request(mddev, sector_nr, skipped);
6242
6243         /* No need to check resync_max as we never do more than one
6244          * stripe, and as resync_max will always be on a chunk boundary,
6245          * if the check in md_do_sync didn't fire, there is no chance
6246          * of overstepping resync_max here
6247          */
6248
6249         /* if there is too many failed drives and we are trying
6250          * to resync, then assert that we are finished, because there is
6251          * nothing we can do.
6252          */
6253         if (mddev->degraded >= conf->max_degraded &&
6254             test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6255                 sector_t rv = mddev->dev_sectors - sector_nr;
6256                 *skipped = 1;
6257                 return rv;
6258         }
6259         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
6260             !conf->fullsync &&
6261             !md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
6262             sync_blocks >= RAID5_STRIPE_SECTORS(conf)) {
6263                 /* we can skip this block, and probably more */
6264                 do_div(sync_blocks, RAID5_STRIPE_SECTORS(conf));
6265                 *skipped = 1;
6266                 /* keep things rounded to whole stripes */
6267                 return sync_blocks * RAID5_STRIPE_SECTORS(conf);
6268         }
6269
6270         md_bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
6271
6272         sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
6273         if (sh == NULL) {
6274                 sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
6275                 /* make sure we don't swamp the stripe cache if someone else
6276                  * is trying to get access
6277                  */
6278                 schedule_timeout_uninterruptible(1);
6279         }
6280         /* Need to check if array will still be degraded after recovery/resync
6281          * Note in case of > 1 drive failures it's possible we're rebuilding
6282          * one drive while leaving another faulty drive in array.
6283          */
6284         rcu_read_lock();
6285         for (i = 0; i < conf->raid_disks; i++) {
6286                 struct md_rdev *rdev = READ_ONCE(conf->disks[i].rdev);
6287
6288                 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
6289                         still_degraded = 1;
6290         }
6291         rcu_read_unlock();
6292
6293         md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
6294
6295         set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
6296         set_bit(STRIPE_HANDLE, &sh->state);
6297
6298         raid5_release_stripe(sh);
6299
6300         return RAID5_STRIPE_SECTORS(conf);
6301 }
6302
6303 static int  retry_aligned_read(struct r5conf *conf, struct bio *raid_bio,
6304                                unsigned int offset)
6305 {
6306         /* We may not be able to submit a whole bio at once as there
6307          * may not be enough stripe_heads available.
6308          * We cannot pre-allocate enough stripe_heads as we may need
6309          * more than exist in the cache (if we allow ever large chunks).
6310          * So we do one stripe head at a time and record in
6311          * ->bi_hw_segments how many have been done.
6312          *
6313          * We *know* that this entire raid_bio is in one chunk, so
6314          * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
6315          */
6316         struct stripe_head *sh;
6317         int dd_idx;
6318         sector_t sector, logical_sector, last_sector;
6319         int scnt = 0;
6320         int handled = 0;
6321
6322         logical_sector = raid_bio->bi_iter.bi_sector &
6323                 ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
6324         sector = raid5_compute_sector(conf, logical_sector,
6325                                       0, &dd_idx, NULL);
6326         last_sector = bio_end_sector(raid_bio);
6327
6328         for (; logical_sector < last_sector;
6329              logical_sector += RAID5_STRIPE_SECTORS(conf),
6330                      sector += RAID5_STRIPE_SECTORS(conf),
6331                      scnt++) {
6332
6333                 if (scnt < offset)
6334                         /* already done this stripe */
6335                         continue;
6336
6337                 sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
6338
6339                 if (!sh) {
6340                         /* failed to get a stripe - must wait */
6341                         conf->retry_read_aligned = raid_bio;
6342                         conf->retry_read_offset = scnt;
6343                         return handled;
6344                 }
6345
6346                 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
6347                         raid5_release_stripe(sh);
6348                         conf->retry_read_aligned = raid_bio;
6349                         conf->retry_read_offset = scnt;
6350                         return handled;
6351                 }
6352
6353                 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
6354                 handle_stripe(sh);
6355                 raid5_release_stripe(sh);
6356                 handled++;
6357         }
6358
6359         bio_endio(raid_bio);
6360
6361         if (atomic_dec_and_test(&conf->active_aligned_reads))
6362                 wake_up(&conf->wait_for_quiescent);
6363         return handled;
6364 }
6365
6366 static int handle_active_stripes(struct r5conf *conf, int group,
6367                                  struct r5worker *worker,
6368                                  struct list_head *temp_inactive_list)
6369                 __releases(&conf->device_lock)
6370                 __acquires(&conf->device_lock)
6371 {
6372         struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
6373         int i, batch_size = 0, hash;
6374         bool release_inactive = false;
6375
6376         while (batch_size < MAX_STRIPE_BATCH &&
6377                         (sh = __get_priority_stripe(conf, group)) != NULL)
6378                 batch[batch_size++] = sh;
6379
6380         if (batch_size == 0) {
6381                 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6382                         if (!list_empty(temp_inactive_list + i))
6383                                 break;
6384                 if (i == NR_STRIPE_HASH_LOCKS) {
6385                         spin_unlock_irq(&conf->device_lock);
6386                         log_flush_stripe_to_raid(conf);
6387                         spin_lock_irq(&conf->device_lock);
6388                         return batch_size;
6389                 }
6390                 release_inactive = true;
6391         }
6392         spin_unlock_irq(&conf->device_lock);
6393
6394         release_inactive_stripe_list(conf, temp_inactive_list,
6395                                      NR_STRIPE_HASH_LOCKS);
6396
6397         r5l_flush_stripe_to_raid(conf->log);
6398         if (release_inactive) {
6399                 spin_lock_irq(&conf->device_lock);
6400                 return 0;
6401         }
6402
6403         for (i = 0; i < batch_size; i++)
6404                 handle_stripe(batch[i]);
6405         log_write_stripe_run(conf);
6406
6407         cond_resched();
6408
6409         spin_lock_irq(&conf->device_lock);
6410         for (i = 0; i < batch_size; i++) {
6411                 hash = batch[i]->hash_lock_index;
6412                 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
6413         }
6414         return batch_size;
6415 }
6416
6417 static void raid5_do_work(struct work_struct *work)
6418 {
6419         struct r5worker *worker = container_of(work, struct r5worker, work);
6420         struct r5worker_group *group = worker->group;
6421         struct r5conf *conf = group->conf;
6422         struct mddev *mddev = conf->mddev;
6423         int group_id = group - conf->worker_groups;
6424         int handled;
6425         struct blk_plug plug;
6426
6427         pr_debug("+++ raid5worker active\n");
6428
6429         blk_start_plug(&plug);
6430         handled = 0;
6431         spin_lock_irq(&conf->device_lock);
6432         while (1) {
6433                 int batch_size, released;
6434
6435                 released = release_stripe_list(conf, worker->temp_inactive_list);
6436
6437                 batch_size = handle_active_stripes(conf, group_id, worker,
6438                                                    worker->temp_inactive_list);
6439                 worker->working = false;
6440                 if (!batch_size && !released)
6441                         break;
6442                 handled += batch_size;
6443                 wait_event_lock_irq(mddev->sb_wait,
6444                         !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6445                         conf->device_lock);
6446         }
6447         pr_debug("%d stripes handled\n", handled);
6448
6449         spin_unlock_irq(&conf->device_lock);
6450
6451         flush_deferred_bios(conf);
6452
6453         r5l_flush_stripe_to_raid(conf->log);
6454
6455         async_tx_issue_pending_all();
6456         blk_finish_plug(&plug);
6457
6458         pr_debug("--- raid5worker inactive\n");
6459 }
6460
6461 /*
6462  * This is our raid5 kernel thread.
6463  *
6464  * We scan the hash table for stripes which can be handled now.
6465  * During the scan, completed stripes are saved for us by the interrupt
6466  * handler, so that they will not have to wait for our next wakeup.
6467  */
6468 static void raid5d(struct md_thread *thread)
6469 {
6470         struct mddev *mddev = thread->mddev;
6471         struct r5conf *conf = mddev->private;
6472         int handled;
6473         struct blk_plug plug;
6474
6475         pr_debug("+++ raid5d active\n");
6476
6477         md_check_recovery(mddev);
6478
6479         blk_start_plug(&plug);
6480         handled = 0;
6481         spin_lock_irq(&conf->device_lock);
6482         while (1) {
6483                 struct bio *bio;
6484                 int batch_size, released;
6485                 unsigned int offset;
6486
6487                 released = release_stripe_list(conf, conf->temp_inactive_list);
6488                 if (released)
6489                         clear_bit(R5_DID_ALLOC, &conf->cache_state);
6490
6491                 if (
6492                     !list_empty(&conf->bitmap_list)) {
6493                         /* Now is a good time to flush some bitmap updates */
6494                         conf->seq_flush++;
6495                         spin_unlock_irq(&conf->device_lock);
6496                         md_bitmap_unplug(mddev->bitmap);
6497                         spin_lock_irq(&conf->device_lock);
6498                         conf->seq_write = conf->seq_flush;
6499                         activate_bit_delay(conf, conf->temp_inactive_list);
6500                 }
6501                 raid5_activate_delayed(conf);
6502
6503                 while ((bio = remove_bio_from_retry(conf, &offset))) {
6504                         int ok;
6505                         spin_unlock_irq(&conf->device_lock);
6506                         ok = retry_aligned_read(conf, bio, offset);
6507                         spin_lock_irq(&conf->device_lock);
6508                         if (!ok)
6509                                 break;
6510                         handled++;
6511                 }
6512
6513                 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
6514                                                    conf->temp_inactive_list);
6515                 if (!batch_size && !released)
6516                         break;
6517                 handled += batch_size;
6518
6519                 if (mddev->sb_flags & ~(1 << MD_SB_CHANGE_PENDING)) {
6520                         spin_unlock_irq(&conf->device_lock);
6521                         md_check_recovery(mddev);
6522                         spin_lock_irq(&conf->device_lock);
6523
6524                         /*
6525                          * Waiting on MD_SB_CHANGE_PENDING below may deadlock
6526                          * seeing md_check_recovery() is needed to clear
6527                          * the flag when using mdmon.
6528                          */
6529                         continue;
6530                 }
6531
6532                 wait_event_lock_irq(mddev->sb_wait,
6533                         !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6534                         conf->device_lock);
6535         }
6536         pr_debug("%d stripes handled\n", handled);
6537
6538         spin_unlock_irq(&conf->device_lock);
6539         if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
6540             mutex_trylock(&conf->cache_size_mutex)) {
6541                 grow_one_stripe(conf, __GFP_NOWARN);
6542                 /* Set flag even if allocation failed.  This helps
6543                  * slow down allocation requests when mem is short
6544                  */
6545                 set_bit(R5_DID_ALLOC, &conf->cache_state);
6546                 mutex_unlock(&conf->cache_size_mutex);
6547         }
6548
6549         flush_deferred_bios(conf);
6550
6551         r5l_flush_stripe_to_raid(conf->log);
6552
6553         async_tx_issue_pending_all();
6554         blk_finish_plug(&plug);
6555
6556         pr_debug("--- raid5d inactive\n");
6557 }
6558
6559 static ssize_t
6560 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
6561 {
6562         struct r5conf *conf;
6563         int ret = 0;
6564         spin_lock(&mddev->lock);
6565         conf = mddev->private;
6566         if (conf)
6567                 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
6568         spin_unlock(&mddev->lock);
6569         return ret;
6570 }
6571
6572 int
6573 raid5_set_cache_size(struct mddev *mddev, int size)
6574 {
6575         int result = 0;
6576         struct r5conf *conf = mddev->private;
6577
6578         if (size <= 16 || size > 32768)
6579                 return -EINVAL;
6580
6581         conf->min_nr_stripes = size;
6582         mutex_lock(&conf->cache_size_mutex);
6583         while (size < conf->max_nr_stripes &&
6584                drop_one_stripe(conf))
6585                 ;
6586         mutex_unlock(&conf->cache_size_mutex);
6587
6588         md_allow_write(mddev);
6589
6590         mutex_lock(&conf->cache_size_mutex);
6591         while (size > conf->max_nr_stripes)
6592                 if (!grow_one_stripe(conf, GFP_KERNEL)) {
6593                         conf->min_nr_stripes = conf->max_nr_stripes;
6594                         result = -ENOMEM;
6595                         break;
6596                 }
6597         mutex_unlock(&conf->cache_size_mutex);
6598
6599         return result;
6600 }
6601 EXPORT_SYMBOL(raid5_set_cache_size);
6602
6603 static ssize_t
6604 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6605 {
6606         struct r5conf *conf;
6607         unsigned long new;
6608         int err;
6609
6610         if (len >= PAGE_SIZE)
6611                 return -EINVAL;
6612         if (kstrtoul(page, 10, &new))
6613                 return -EINVAL;
6614         err = mddev_lock(mddev);
6615         if (err)
6616                 return err;
6617         conf = mddev->private;
6618         if (!conf)
6619                 err = -ENODEV;
6620         else
6621                 err = raid5_set_cache_size(mddev, new);
6622         mddev_unlock(mddev);
6623
6624         return err ?: len;
6625 }
6626
6627 static struct md_sysfs_entry
6628 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6629                                 raid5_show_stripe_cache_size,
6630                                 raid5_store_stripe_cache_size);
6631
6632 static ssize_t
6633 raid5_show_rmw_level(struct mddev  *mddev, char *page)
6634 {
6635         struct r5conf *conf = mddev->private;
6636         if (conf)
6637                 return sprintf(page, "%d\n", conf->rmw_level);
6638         else
6639                 return 0;
6640 }
6641
6642 static ssize_t
6643 raid5_store_rmw_level(struct mddev  *mddev, const char *page, size_t len)
6644 {
6645         struct r5conf *conf = mddev->private;
6646         unsigned long new;
6647
6648         if (!conf)
6649                 return -ENODEV;
6650
6651         if (len >= PAGE_SIZE)
6652                 return -EINVAL;
6653
6654         if (kstrtoul(page, 10, &new))
6655                 return -EINVAL;
6656
6657         if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6658                 return -EINVAL;
6659
6660         if (new != PARITY_DISABLE_RMW &&
6661             new != PARITY_ENABLE_RMW &&
6662             new != PARITY_PREFER_RMW)
6663                 return -EINVAL;
6664
6665         conf->rmw_level = new;
6666         return len;
6667 }
6668
6669 static struct md_sysfs_entry
6670 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6671                          raid5_show_rmw_level,
6672                          raid5_store_rmw_level);
6673
6674 static ssize_t
6675 raid5_show_stripe_size(struct mddev  *mddev, char *page)
6676 {
6677         struct r5conf *conf;
6678         int ret = 0;
6679
6680         spin_lock(&mddev->lock);
6681         conf = mddev->private;
6682         if (conf)
6683                 ret = sprintf(page, "%lu\n", RAID5_STRIPE_SIZE(conf));
6684         spin_unlock(&mddev->lock);
6685         return ret;
6686 }
6687
6688 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
6689 static ssize_t
6690 raid5_store_stripe_size(struct mddev  *mddev, const char *page, size_t len)
6691 {
6692         struct r5conf *conf;
6693         unsigned long new;
6694         int err;
6695         int size;
6696
6697         if (len >= PAGE_SIZE)
6698                 return -EINVAL;
6699         if (kstrtoul(page, 10, &new))
6700                 return -EINVAL;
6701
6702         /*
6703          * The value should not be bigger than PAGE_SIZE. It requires to
6704          * be multiple of DEFAULT_STRIPE_SIZE and the value should be power
6705          * of two.
6706          */
6707         if (new % DEFAULT_STRIPE_SIZE != 0 ||
6708                         new > PAGE_SIZE || new == 0 ||
6709                         new != roundup_pow_of_two(new))
6710                 return -EINVAL;
6711
6712         err = mddev_lock(mddev);
6713         if (err)
6714                 return err;
6715
6716         conf = mddev->private;
6717         if (!conf) {
6718                 err = -ENODEV;
6719                 goto out_unlock;
6720         }
6721
6722         if (new == conf->stripe_size)
6723                 goto out_unlock;
6724
6725         pr_debug("md/raid: change stripe_size from %lu to %lu\n",
6726                         conf->stripe_size, new);
6727
6728         if (mddev->sync_thread ||
6729                 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6730                 mddev->reshape_position != MaxSector ||
6731                 mddev->sysfs_active) {
6732                 err = -EBUSY;
6733                 goto out_unlock;
6734         }
6735
6736         mddev_suspend(mddev);
6737         mutex_lock(&conf->cache_size_mutex);
6738         size = conf->max_nr_stripes;
6739
6740         shrink_stripes(conf);
6741
6742         conf->stripe_size = new;
6743         conf->stripe_shift = ilog2(new) - 9;
6744         conf->stripe_sectors = new >> 9;
6745         if (grow_stripes(conf, size)) {
6746                 pr_warn("md/raid:%s: couldn't allocate buffers\n",
6747                                 mdname(mddev));
6748                 err = -ENOMEM;
6749         }
6750         mutex_unlock(&conf->cache_size_mutex);
6751         mddev_resume(mddev);
6752
6753 out_unlock:
6754         mddev_unlock(mddev);
6755         return err ?: len;
6756 }
6757
6758 static struct md_sysfs_entry
6759 raid5_stripe_size = __ATTR(stripe_size, 0644,
6760                          raid5_show_stripe_size,
6761                          raid5_store_stripe_size);
6762 #else
6763 static struct md_sysfs_entry
6764 raid5_stripe_size = __ATTR(stripe_size, 0444,
6765                          raid5_show_stripe_size,
6766                          NULL);
6767 #endif
6768
6769 static ssize_t
6770 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6771 {
6772         struct r5conf *conf;
6773         int ret = 0;
6774         spin_lock(&mddev->lock);
6775         conf = mddev->private;
6776         if (conf)
6777                 ret = sprintf(page, "%d\n", conf->bypass_threshold);
6778         spin_unlock(&mddev->lock);
6779         return ret;
6780 }
6781
6782 static ssize_t
6783 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6784 {
6785         struct r5conf *conf;
6786         unsigned long new;
6787         int err;
6788
6789         if (len >= PAGE_SIZE)
6790                 return -EINVAL;
6791         if (kstrtoul(page, 10, &new))
6792                 return -EINVAL;
6793
6794         err = mddev_lock(mddev);
6795         if (err)
6796                 return err;
6797         conf = mddev->private;
6798         if (!conf)
6799                 err = -ENODEV;
6800         else if (new > conf->min_nr_stripes)
6801                 err = -EINVAL;
6802         else
6803                 conf->bypass_threshold = new;
6804         mddev_unlock(mddev);
6805         return err ?: len;
6806 }
6807
6808 static struct md_sysfs_entry
6809 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6810                                         S_IRUGO | S_IWUSR,
6811                                         raid5_show_preread_threshold,
6812                                         raid5_store_preread_threshold);
6813
6814 static ssize_t
6815 raid5_show_skip_copy(struct mddev *mddev, char *page)
6816 {
6817         struct r5conf *conf;
6818         int ret = 0;
6819         spin_lock(&mddev->lock);
6820         conf = mddev->private;
6821         if (conf)
6822                 ret = sprintf(page, "%d\n", conf->skip_copy);
6823         spin_unlock(&mddev->lock);
6824         return ret;
6825 }
6826
6827 static ssize_t
6828 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6829 {
6830         struct r5conf *conf;
6831         unsigned long new;
6832         int err;
6833
6834         if (len >= PAGE_SIZE)
6835                 return -EINVAL;
6836         if (kstrtoul(page, 10, &new))
6837                 return -EINVAL;
6838         new = !!new;
6839
6840         err = mddev_lock(mddev);
6841         if (err)
6842                 return err;
6843         conf = mddev->private;
6844         if (!conf)
6845                 err = -ENODEV;
6846         else if (new != conf->skip_copy) {
6847                 struct request_queue *q = mddev->queue;
6848
6849                 mddev_suspend(mddev);
6850                 conf->skip_copy = new;
6851                 if (new)
6852                         blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, q);
6853                 else
6854                         blk_queue_flag_clear(QUEUE_FLAG_STABLE_WRITES, q);
6855                 mddev_resume(mddev);
6856         }
6857         mddev_unlock(mddev);
6858         return err ?: len;
6859 }
6860
6861 static struct md_sysfs_entry
6862 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6863                                         raid5_show_skip_copy,
6864                                         raid5_store_skip_copy);
6865
6866 static ssize_t
6867 stripe_cache_active_show(struct mddev *mddev, char *page)
6868 {
6869         struct r5conf *conf = mddev->private;
6870         if (conf)
6871                 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6872         else
6873                 return 0;
6874 }
6875
6876 static struct md_sysfs_entry
6877 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6878
6879 static ssize_t
6880 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6881 {
6882         struct r5conf *conf;
6883         int ret = 0;
6884         spin_lock(&mddev->lock);
6885         conf = mddev->private;
6886         if (conf)
6887                 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6888         spin_unlock(&mddev->lock);
6889         return ret;
6890 }
6891
6892 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6893                                int *group_cnt,
6894                                struct r5worker_group **worker_groups);
6895 static ssize_t
6896 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6897 {
6898         struct r5conf *conf;
6899         unsigned int new;
6900         int err;
6901         struct r5worker_group *new_groups, *old_groups;
6902         int group_cnt;
6903
6904         if (len >= PAGE_SIZE)
6905                 return -EINVAL;
6906         if (kstrtouint(page, 10, &new))
6907                 return -EINVAL;
6908         /* 8192 should be big enough */
6909         if (new > 8192)
6910                 return -EINVAL;
6911
6912         err = mddev_lock(mddev);
6913         if (err)
6914                 return err;
6915         conf = mddev->private;
6916         if (!conf)
6917                 err = -ENODEV;
6918         else if (new != conf->worker_cnt_per_group) {
6919                 mddev_suspend(mddev);
6920
6921                 old_groups = conf->worker_groups;
6922                 if (old_groups)
6923                         flush_workqueue(raid5_wq);
6924
6925                 err = alloc_thread_groups(conf, new, &group_cnt, &new_groups);
6926                 if (!err) {
6927                         spin_lock_irq(&conf->device_lock);
6928                         conf->group_cnt = group_cnt;
6929                         conf->worker_cnt_per_group = new;
6930                         conf->worker_groups = new_groups;
6931                         spin_unlock_irq(&conf->device_lock);
6932
6933                         if (old_groups)
6934                                 kfree(old_groups[0].workers);
6935                         kfree(old_groups);
6936                 }
6937                 mddev_resume(mddev);
6938         }
6939         mddev_unlock(mddev);
6940
6941         return err ?: len;
6942 }
6943
6944 static struct md_sysfs_entry
6945 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6946                                 raid5_show_group_thread_cnt,
6947                                 raid5_store_group_thread_cnt);
6948
6949 static struct attribute *raid5_attrs[] =  {
6950         &raid5_stripecache_size.attr,
6951         &raid5_stripecache_active.attr,
6952         &raid5_preread_bypass_threshold.attr,
6953         &raid5_group_thread_cnt.attr,
6954         &raid5_skip_copy.attr,
6955         &raid5_rmw_level.attr,
6956         &raid5_stripe_size.attr,
6957         &r5c_journal_mode.attr,
6958         &ppl_write_hint.attr,
6959         NULL,
6960 };
6961 static struct attribute_group raid5_attrs_group = {
6962         .name = NULL,
6963         .attrs = raid5_attrs,
6964 };
6965
6966 static int alloc_thread_groups(struct r5conf *conf, int cnt, int *group_cnt,
6967                                struct r5worker_group **worker_groups)
6968 {
6969         int i, j, k;
6970         ssize_t size;
6971         struct r5worker *workers;
6972
6973         if (cnt == 0) {
6974                 *group_cnt = 0;
6975                 *worker_groups = NULL;
6976                 return 0;
6977         }
6978         *group_cnt = num_possible_nodes();
6979         size = sizeof(struct r5worker) * cnt;
6980         workers = kcalloc(size, *group_cnt, GFP_NOIO);
6981         *worker_groups = kcalloc(*group_cnt, sizeof(struct r5worker_group),
6982                                  GFP_NOIO);
6983         if (!*worker_groups || !workers) {
6984                 kfree(workers);
6985                 kfree(*worker_groups);
6986                 return -ENOMEM;
6987         }
6988
6989         for (i = 0; i < *group_cnt; i++) {
6990                 struct r5worker_group *group;
6991
6992                 group = &(*worker_groups)[i];
6993                 INIT_LIST_HEAD(&group->handle_list);
6994                 INIT_LIST_HEAD(&group->loprio_list);
6995                 group->conf = conf;
6996                 group->workers = workers + i * cnt;
6997
6998                 for (j = 0; j < cnt; j++) {
6999                         struct r5worker *worker = group->workers + j;
7000                         worker->group = group;
7001                         INIT_WORK(&worker->work, raid5_do_work);
7002
7003                         for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
7004                                 INIT_LIST_HEAD(worker->temp_inactive_list + k);
7005                 }
7006         }
7007
7008         return 0;
7009 }
7010
7011 static void free_thread_groups(struct r5conf *conf)
7012 {
7013         if (conf->worker_groups)
7014                 kfree(conf->worker_groups[0].workers);
7015         kfree(conf->worker_groups);
7016         conf->worker_groups = NULL;
7017 }
7018
7019 static sector_t
7020 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
7021 {
7022         struct r5conf *conf = mddev->private;
7023
7024         if (!sectors)
7025                 sectors = mddev->dev_sectors;
7026         if (!raid_disks)
7027                 /* size is defined by the smallest of previous and new size */
7028                 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
7029
7030         sectors &= ~((sector_t)conf->chunk_sectors - 1);
7031         sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
7032         return sectors * (raid_disks - conf->max_degraded);
7033 }
7034
7035 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7036 {
7037         safe_put_page(percpu->spare_page);
7038         percpu->spare_page = NULL;
7039         kvfree(percpu->scribble);
7040         percpu->scribble = NULL;
7041 }
7042
7043 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7044 {
7045         if (conf->level == 6 && !percpu->spare_page) {
7046                 percpu->spare_page = alloc_page(GFP_KERNEL);
7047                 if (!percpu->spare_page)
7048                         return -ENOMEM;
7049         }
7050
7051         if (scribble_alloc(percpu,
7052                            max(conf->raid_disks,
7053                                conf->previous_raid_disks),
7054                            max(conf->chunk_sectors,
7055                                conf->prev_chunk_sectors)
7056                            / RAID5_STRIPE_SECTORS(conf))) {
7057                 free_scratch_buffer(conf, percpu);
7058                 return -ENOMEM;
7059         }
7060
7061         return 0;
7062 }
7063
7064 static int raid456_cpu_dead(unsigned int cpu, struct hlist_node *node)
7065 {
7066         struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7067
7068         free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
7069         return 0;
7070 }
7071
7072 static void raid5_free_percpu(struct r5conf *conf)
7073 {
7074         if (!conf->percpu)
7075                 return;
7076
7077         cpuhp_state_remove_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7078         free_percpu(conf->percpu);
7079 }
7080
7081 static void free_conf(struct r5conf *conf)
7082 {
7083         int i;
7084
7085         log_exit(conf);
7086
7087         unregister_shrinker(&conf->shrinker);
7088         free_thread_groups(conf);
7089         shrink_stripes(conf);
7090         raid5_free_percpu(conf);
7091         for (i = 0; i < conf->pool_size; i++)
7092                 if (conf->disks[i].extra_page)
7093                         put_page(conf->disks[i].extra_page);
7094         kfree(conf->disks);
7095         bioset_exit(&conf->bio_split);
7096         kfree(conf->stripe_hashtbl);
7097         kfree(conf->pending_data);
7098         kfree(conf);
7099 }
7100
7101 static int raid456_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
7102 {
7103         struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7104         struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
7105
7106         if (alloc_scratch_buffer(conf, percpu)) {
7107                 pr_warn("%s: failed memory allocation for cpu%u\n",
7108                         __func__, cpu);
7109                 return -ENOMEM;
7110         }
7111         return 0;
7112 }
7113
7114 static int raid5_alloc_percpu(struct r5conf *conf)
7115 {
7116         int err = 0;
7117
7118         conf->percpu = alloc_percpu(struct raid5_percpu);
7119         if (!conf->percpu)
7120                 return -ENOMEM;
7121
7122         err = cpuhp_state_add_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7123         if (!err) {
7124                 conf->scribble_disks = max(conf->raid_disks,
7125                         conf->previous_raid_disks);
7126                 conf->scribble_sectors = max(conf->chunk_sectors,
7127                         conf->prev_chunk_sectors);
7128         }
7129         return err;
7130 }
7131
7132 static unsigned long raid5_cache_scan(struct shrinker *shrink,
7133                                       struct shrink_control *sc)
7134 {
7135         struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7136         unsigned long ret = SHRINK_STOP;
7137
7138         if (mutex_trylock(&conf->cache_size_mutex)) {
7139                 ret= 0;
7140                 while (ret < sc->nr_to_scan &&
7141                        conf->max_nr_stripes > conf->min_nr_stripes) {
7142                         if (drop_one_stripe(conf) == 0) {
7143                                 ret = SHRINK_STOP;
7144                                 break;
7145                         }
7146                         ret++;
7147                 }
7148                 mutex_unlock(&conf->cache_size_mutex);
7149         }
7150         return ret;
7151 }
7152
7153 static unsigned long raid5_cache_count(struct shrinker *shrink,
7154                                        struct shrink_control *sc)
7155 {
7156         struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7157
7158         if (conf->max_nr_stripes < conf->min_nr_stripes)
7159                 /* unlikely, but not impossible */
7160                 return 0;
7161         return conf->max_nr_stripes - conf->min_nr_stripes;
7162 }
7163
7164 static struct r5conf *setup_conf(struct mddev *mddev)
7165 {
7166         struct r5conf *conf;
7167         int raid_disk, memory, max_disks;
7168         struct md_rdev *rdev;
7169         struct disk_info *disk;
7170         char pers_name[6];
7171         int i;
7172         int group_cnt;
7173         struct r5worker_group *new_group;
7174         int ret;
7175
7176         if (mddev->new_level != 5
7177             && mddev->new_level != 4
7178             && mddev->new_level != 6) {
7179                 pr_warn("md/raid:%s: raid level not set to 4/5/6 (%d)\n",
7180                         mdname(mddev), mddev->new_level);
7181                 return ERR_PTR(-EIO);
7182         }
7183         if ((mddev->new_level == 5
7184              && !algorithm_valid_raid5(mddev->new_layout)) ||
7185             (mddev->new_level == 6
7186              && !algorithm_valid_raid6(mddev->new_layout))) {
7187                 pr_warn("md/raid:%s: layout %d not supported\n",
7188                         mdname(mddev), mddev->new_layout);
7189                 return ERR_PTR(-EIO);
7190         }
7191         if (mddev->new_level == 6 && mddev->raid_disks < 4) {
7192                 pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n",
7193                         mdname(mddev), mddev->raid_disks);
7194                 return ERR_PTR(-EINVAL);
7195         }
7196
7197         if (!mddev->new_chunk_sectors ||
7198             (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
7199             !is_power_of_2(mddev->new_chunk_sectors)) {
7200                 pr_warn("md/raid:%s: invalid chunk size %d\n",
7201                         mdname(mddev), mddev->new_chunk_sectors << 9);
7202                 return ERR_PTR(-EINVAL);
7203         }
7204
7205         conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
7206         if (conf == NULL)
7207                 goto abort;
7208
7209 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
7210         conf->stripe_size = DEFAULT_STRIPE_SIZE;
7211         conf->stripe_shift = ilog2(DEFAULT_STRIPE_SIZE) - 9;
7212         conf->stripe_sectors = DEFAULT_STRIPE_SIZE >> 9;
7213 #endif
7214         INIT_LIST_HEAD(&conf->free_list);
7215         INIT_LIST_HEAD(&conf->pending_list);
7216         conf->pending_data = kcalloc(PENDING_IO_MAX,
7217                                      sizeof(struct r5pending_data),
7218                                      GFP_KERNEL);
7219         if (!conf->pending_data)
7220                 goto abort;
7221         for (i = 0; i < PENDING_IO_MAX; i++)
7222                 list_add(&conf->pending_data[i].sibling, &conf->free_list);
7223         /* Don't enable multi-threading by default*/
7224         if (!alloc_thread_groups(conf, 0, &group_cnt, &new_group)) {
7225                 conf->group_cnt = group_cnt;
7226                 conf->worker_cnt_per_group = 0;
7227                 conf->worker_groups = new_group;
7228         } else
7229                 goto abort;
7230         spin_lock_init(&conf->device_lock);
7231         seqcount_spinlock_init(&conf->gen_lock, &conf->device_lock);
7232         mutex_init(&conf->cache_size_mutex);
7233         init_waitqueue_head(&conf->wait_for_quiescent);
7234         init_waitqueue_head(&conf->wait_for_stripe);
7235         init_waitqueue_head(&conf->wait_for_overlap);
7236         INIT_LIST_HEAD(&conf->handle_list);
7237         INIT_LIST_HEAD(&conf->loprio_list);
7238         INIT_LIST_HEAD(&conf->hold_list);
7239         INIT_LIST_HEAD(&conf->delayed_list);
7240         INIT_LIST_HEAD(&conf->bitmap_list);
7241         init_llist_head(&conf->released_stripes);
7242         atomic_set(&conf->active_stripes, 0);
7243         atomic_set(&conf->preread_active_stripes, 0);
7244         atomic_set(&conf->active_aligned_reads, 0);
7245         spin_lock_init(&conf->pending_bios_lock);
7246         conf->batch_bio_dispatch = true;
7247         rdev_for_each(rdev, mddev) {
7248                 if (test_bit(Journal, &rdev->flags))
7249                         continue;
7250                 if (blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
7251                         conf->batch_bio_dispatch = false;
7252                         break;
7253                 }
7254         }
7255
7256         conf->bypass_threshold = BYPASS_THRESHOLD;
7257         conf->recovery_disabled = mddev->recovery_disabled - 1;
7258
7259         conf->raid_disks = mddev->raid_disks;
7260         if (mddev->reshape_position == MaxSector)
7261                 conf->previous_raid_disks = mddev->raid_disks;
7262         else
7263                 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
7264         max_disks = max(conf->raid_disks, conf->previous_raid_disks);
7265
7266         conf->disks = kcalloc(max_disks, sizeof(struct disk_info),
7267                               GFP_KERNEL);
7268
7269         if (!conf->disks)
7270                 goto abort;
7271
7272         for (i = 0; i < max_disks; i++) {
7273                 conf->disks[i].extra_page = alloc_page(GFP_KERNEL);
7274                 if (!conf->disks[i].extra_page)
7275                         goto abort;
7276         }
7277
7278         ret = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
7279         if (ret)
7280                 goto abort;
7281         conf->mddev = mddev;
7282
7283         if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
7284                 goto abort;
7285
7286         /* We init hash_locks[0] separately to that it can be used
7287          * as the reference lock in the spin_lock_nest_lock() call
7288          * in lock_all_device_hash_locks_irq in order to convince
7289          * lockdep that we know what we are doing.
7290          */
7291         spin_lock_init(conf->hash_locks);
7292         for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
7293                 spin_lock_init(conf->hash_locks + i);
7294
7295         for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7296                 INIT_LIST_HEAD(conf->inactive_list + i);
7297
7298         for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7299                 INIT_LIST_HEAD(conf->temp_inactive_list + i);
7300
7301         atomic_set(&conf->r5c_cached_full_stripes, 0);
7302         INIT_LIST_HEAD(&conf->r5c_full_stripe_list);
7303         atomic_set(&conf->r5c_cached_partial_stripes, 0);
7304         INIT_LIST_HEAD(&conf->r5c_partial_stripe_list);
7305         atomic_set(&conf->r5c_flushing_full_stripes, 0);
7306         atomic_set(&conf->r5c_flushing_partial_stripes, 0);
7307
7308         conf->level = mddev->new_level;
7309         conf->chunk_sectors = mddev->new_chunk_sectors;
7310         if (raid5_alloc_percpu(conf) != 0)
7311                 goto abort;
7312
7313         pr_debug("raid456: run(%s) called.\n", mdname(mddev));
7314
7315         rdev_for_each(rdev, mddev) {
7316                 raid_disk = rdev->raid_disk;
7317                 if (raid_disk >= max_disks
7318                     || raid_disk < 0 || test_bit(Journal, &rdev->flags))
7319                         continue;
7320                 disk = conf->disks + raid_disk;
7321
7322                 if (test_bit(Replacement, &rdev->flags)) {
7323                         if (disk->replacement)
7324                                 goto abort;
7325                         disk->replacement = rdev;
7326                 } else {
7327                         if (disk->rdev)
7328                                 goto abort;
7329                         disk->rdev = rdev;
7330                 }
7331
7332                 if (test_bit(In_sync, &rdev->flags)) {
7333                         char b[BDEVNAME_SIZE];
7334                         pr_info("md/raid:%s: device %s operational as raid disk %d\n",
7335                                 mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
7336                 } else if (rdev->saved_raid_disk != raid_disk)
7337                         /* Cannot rely on bitmap to complete recovery */
7338                         conf->fullsync = 1;
7339         }
7340
7341         conf->level = mddev->new_level;
7342         if (conf->level == 6) {
7343                 conf->max_degraded = 2;
7344                 if (raid6_call.xor_syndrome)
7345                         conf->rmw_level = PARITY_ENABLE_RMW;
7346                 else
7347                         conf->rmw_level = PARITY_DISABLE_RMW;
7348         } else {
7349                 conf->max_degraded = 1;
7350                 conf->rmw_level = PARITY_ENABLE_RMW;
7351         }
7352         conf->algorithm = mddev->new_layout;
7353         conf->reshape_progress = mddev->reshape_position;
7354         if (conf->reshape_progress != MaxSector) {
7355                 conf->prev_chunk_sectors = mddev->chunk_sectors;
7356                 conf->prev_algo = mddev->layout;
7357         } else {
7358                 conf->prev_chunk_sectors = conf->chunk_sectors;
7359                 conf->prev_algo = conf->algorithm;
7360         }
7361
7362         conf->min_nr_stripes = NR_STRIPES;
7363         if (mddev->reshape_position != MaxSector) {
7364                 int stripes = max_t(int,
7365                         ((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4,
7366                         ((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4);
7367                 conf->min_nr_stripes = max(NR_STRIPES, stripes);
7368                 if (conf->min_nr_stripes != NR_STRIPES)
7369                         pr_info("md/raid:%s: force stripe size %d for reshape\n",
7370                                 mdname(mddev), conf->min_nr_stripes);
7371         }
7372         memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
7373                  max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
7374         atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
7375         if (grow_stripes(conf, conf->min_nr_stripes)) {
7376                 pr_warn("md/raid:%s: couldn't allocate %dkB for buffers\n",
7377                         mdname(mddev), memory);
7378                 goto abort;
7379         } else
7380                 pr_debug("md/raid:%s: allocated %dkB\n", mdname(mddev), memory);
7381         /*
7382          * Losing a stripe head costs more than the time to refill it,
7383          * it reduces the queue depth and so can hurt throughput.
7384          * So set it rather large, scaled by number of devices.
7385          */
7386         conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
7387         conf->shrinker.scan_objects = raid5_cache_scan;
7388         conf->shrinker.count_objects = raid5_cache_count;
7389         conf->shrinker.batch = 128;
7390         conf->shrinker.flags = 0;
7391         if (register_shrinker(&conf->shrinker)) {
7392                 pr_warn("md/raid:%s: couldn't register shrinker.\n",
7393                         mdname(mddev));
7394                 goto abort;
7395         }
7396
7397         sprintf(pers_name, "raid%d", mddev->new_level);
7398         conf->thread = md_register_thread(raid5d, mddev, pers_name);
7399         if (!conf->thread) {
7400                 pr_warn("md/raid:%s: couldn't allocate thread.\n",
7401                         mdname(mddev));
7402                 goto abort;
7403         }
7404
7405         return conf;
7406
7407  abort:
7408         if (conf) {
7409                 free_conf(conf);
7410                 return ERR_PTR(-EIO);
7411         } else
7412                 return ERR_PTR(-ENOMEM);
7413 }
7414
7415 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
7416 {
7417         switch (algo) {
7418         case ALGORITHM_PARITY_0:
7419                 if (raid_disk < max_degraded)
7420                         return 1;
7421                 break;
7422         case ALGORITHM_PARITY_N:
7423                 if (raid_disk >= raid_disks - max_degraded)
7424                         return 1;
7425                 break;
7426         case ALGORITHM_PARITY_0_6:
7427                 if (raid_disk == 0 ||
7428                     raid_disk == raid_disks - 1)
7429                         return 1;
7430                 break;
7431         case ALGORITHM_LEFT_ASYMMETRIC_6:
7432         case ALGORITHM_RIGHT_ASYMMETRIC_6:
7433         case ALGORITHM_LEFT_SYMMETRIC_6:
7434         case ALGORITHM_RIGHT_SYMMETRIC_6:
7435                 if (raid_disk == raid_disks - 1)
7436                         return 1;
7437         }
7438         return 0;
7439 }
7440
7441 static void raid5_set_io_opt(struct r5conf *conf)
7442 {
7443         blk_queue_io_opt(conf->mddev->queue, (conf->chunk_sectors << 9) *
7444                          (conf->raid_disks - conf->max_degraded));
7445 }
7446
7447 static int raid5_run(struct mddev *mddev)
7448 {
7449         struct r5conf *conf;
7450         int working_disks = 0;
7451         int dirty_parity_disks = 0;
7452         struct md_rdev *rdev;
7453         struct md_rdev *journal_dev = NULL;
7454         sector_t reshape_offset = 0;
7455         int i;
7456         long long min_offset_diff = 0;
7457         int first = 1;
7458
7459         if (mddev_init_writes_pending(mddev) < 0)
7460                 return -ENOMEM;
7461
7462         if (mddev->recovery_cp != MaxSector)
7463                 pr_notice("md/raid:%s: not clean -- starting background reconstruction\n",
7464                           mdname(mddev));
7465
7466         rdev_for_each(rdev, mddev) {
7467                 long long diff;
7468
7469                 if (test_bit(Journal, &rdev->flags)) {
7470                         journal_dev = rdev;
7471                         continue;
7472                 }
7473                 if (rdev->raid_disk < 0)
7474                         continue;
7475                 diff = (rdev->new_data_offset - rdev->data_offset);
7476                 if (first) {
7477                         min_offset_diff = diff;
7478                         first = 0;
7479                 } else if (mddev->reshape_backwards &&
7480                          diff < min_offset_diff)
7481                         min_offset_diff = diff;
7482                 else if (!mddev->reshape_backwards &&
7483                          diff > min_offset_diff)
7484                         min_offset_diff = diff;
7485         }
7486
7487         if ((test_bit(MD_HAS_JOURNAL, &mddev->flags) || journal_dev) &&
7488             (mddev->bitmap_info.offset || mddev->bitmap_info.file)) {
7489                 pr_notice("md/raid:%s: array cannot have both journal and bitmap\n",
7490                           mdname(mddev));
7491                 return -EINVAL;
7492         }
7493
7494         if (mddev->reshape_position != MaxSector) {
7495                 /* Check that we can continue the reshape.
7496                  * Difficulties arise if the stripe we would write to
7497                  * next is at or after the stripe we would read from next.
7498                  * For a reshape that changes the number of devices, this
7499                  * is only possible for a very short time, and mdadm makes
7500                  * sure that time appears to have past before assembling
7501                  * the array.  So we fail if that time hasn't passed.
7502                  * For a reshape that keeps the number of devices the same
7503                  * mdadm must be monitoring the reshape can keeping the
7504                  * critical areas read-only and backed up.  It will start
7505                  * the array in read-only mode, so we check for that.
7506                  */
7507                 sector_t here_new, here_old;
7508                 int old_disks;
7509                 int max_degraded = (mddev->level == 6 ? 2 : 1);
7510                 int chunk_sectors;
7511                 int new_data_disks;
7512
7513                 if (journal_dev) {
7514                         pr_warn("md/raid:%s: don't support reshape with journal - aborting.\n",
7515                                 mdname(mddev));
7516                         return -EINVAL;
7517                 }
7518
7519                 if (mddev->new_level != mddev->level) {
7520                         pr_warn("md/raid:%s: unsupported reshape required - aborting.\n",
7521                                 mdname(mddev));
7522                         return -EINVAL;
7523                 }
7524                 old_disks = mddev->raid_disks - mddev->delta_disks;
7525                 /* reshape_position must be on a new-stripe boundary, and one
7526                  * further up in new geometry must map after here in old
7527                  * geometry.
7528                  * If the chunk sizes are different, then as we perform reshape
7529                  * in units of the largest of the two, reshape_position needs
7530                  * be a multiple of the largest chunk size times new data disks.
7531                  */
7532                 here_new = mddev->reshape_position;
7533                 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
7534                 new_data_disks = mddev->raid_disks - max_degraded;
7535                 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
7536                         pr_warn("md/raid:%s: reshape_position not on a stripe boundary\n",
7537                                 mdname(mddev));
7538                         return -EINVAL;
7539                 }
7540                 reshape_offset = here_new * chunk_sectors;
7541                 /* here_new is the stripe we will write to */
7542                 here_old = mddev->reshape_position;
7543                 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
7544                 /* here_old is the first stripe that we might need to read
7545                  * from */
7546                 if (mddev->delta_disks == 0) {
7547                         /* We cannot be sure it is safe to start an in-place
7548                          * reshape.  It is only safe if user-space is monitoring
7549                          * and taking constant backups.
7550                          * mdadm always starts a situation like this in
7551                          * readonly mode so it can take control before
7552                          * allowing any writes.  So just check for that.
7553                          */
7554                         if (abs(min_offset_diff) >= mddev->chunk_sectors &&
7555                             abs(min_offset_diff) >= mddev->new_chunk_sectors)
7556                                 /* not really in-place - so OK */;
7557                         else if (mddev->ro == 0) {
7558                                 pr_warn("md/raid:%s: in-place reshape must be started in read-only mode - aborting\n",
7559                                         mdname(mddev));
7560                                 return -EINVAL;
7561                         }
7562                 } else if (mddev->reshape_backwards
7563                     ? (here_new * chunk_sectors + min_offset_diff <=
7564                        here_old * chunk_sectors)
7565                     : (here_new * chunk_sectors >=
7566                        here_old * chunk_sectors + (-min_offset_diff))) {
7567                         /* Reading from the same stripe as writing to - bad */
7568                         pr_warn("md/raid:%s: reshape_position too early for auto-recovery - aborting.\n",
7569                                 mdname(mddev));
7570                         return -EINVAL;
7571                 }
7572                 pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev));
7573                 /* OK, we should be able to continue; */
7574         } else {
7575                 BUG_ON(mddev->level != mddev->new_level);
7576                 BUG_ON(mddev->layout != mddev->new_layout);
7577                 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
7578                 BUG_ON(mddev->delta_disks != 0);
7579         }
7580
7581         if (test_bit(MD_HAS_JOURNAL, &mddev->flags) &&
7582             test_bit(MD_HAS_PPL, &mddev->flags)) {
7583                 pr_warn("md/raid:%s: using journal device and PPL not allowed - disabling PPL\n",
7584                         mdname(mddev));
7585                 clear_bit(MD_HAS_PPL, &mddev->flags);
7586                 clear_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags);
7587         }
7588
7589         if (mddev->private == NULL)
7590                 conf = setup_conf(mddev);
7591         else
7592                 conf = mddev->private;
7593
7594         if (IS_ERR(conf))
7595                 return PTR_ERR(conf);
7596
7597         if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
7598                 if (!journal_dev) {
7599                         pr_warn("md/raid:%s: journal disk is missing, force array readonly\n",
7600                                 mdname(mddev));
7601                         mddev->ro = 1;
7602                         set_disk_ro(mddev->gendisk, 1);
7603                 } else if (mddev->recovery_cp == MaxSector)
7604                         set_bit(MD_JOURNAL_CLEAN, &mddev->flags);
7605         }
7606
7607         conf->min_offset_diff = min_offset_diff;
7608         mddev->thread = conf->thread;
7609         conf->thread = NULL;
7610         mddev->private = conf;
7611
7612         for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
7613              i++) {
7614                 rdev = conf->disks[i].rdev;
7615                 if (!rdev && conf->disks[i].replacement) {
7616                         /* The replacement is all we have yet */
7617                         rdev = conf->disks[i].replacement;
7618                         conf->disks[i].replacement = NULL;
7619                         clear_bit(Replacement, &rdev->flags);
7620                         conf->disks[i].rdev = rdev;
7621                 }
7622                 if (!rdev)
7623                         continue;
7624                 if (conf->disks[i].replacement &&
7625                     conf->reshape_progress != MaxSector) {
7626                         /* replacements and reshape simply do not mix. */
7627                         pr_warn("md: cannot handle concurrent replacement and reshape.\n");
7628                         goto abort;
7629                 }
7630                 if (test_bit(In_sync, &rdev->flags)) {
7631                         working_disks++;
7632                         continue;
7633                 }
7634                 /* This disc is not fully in-sync.  However if it
7635                  * just stored parity (beyond the recovery_offset),
7636                  * when we don't need to be concerned about the
7637                  * array being dirty.
7638                  * When reshape goes 'backwards', we never have
7639                  * partially completed devices, so we only need
7640                  * to worry about reshape going forwards.
7641                  */
7642                 /* Hack because v0.91 doesn't store recovery_offset properly. */
7643                 if (mddev->major_version == 0 &&
7644                     mddev->minor_version > 90)
7645                         rdev->recovery_offset = reshape_offset;
7646
7647                 if (rdev->recovery_offset < reshape_offset) {
7648                         /* We need to check old and new layout */
7649                         if (!only_parity(rdev->raid_disk,
7650                                          conf->algorithm,
7651                                          conf->raid_disks,
7652                                          conf->max_degraded))
7653                                 continue;
7654                 }
7655                 if (!only_parity(rdev->raid_disk,
7656                                  conf->prev_algo,
7657                                  conf->previous_raid_disks,
7658                                  conf->max_degraded))
7659                         continue;
7660                 dirty_parity_disks++;
7661         }
7662
7663         /*
7664          * 0 for a fully functional array, 1 or 2 for a degraded array.
7665          */
7666         mddev->degraded = raid5_calc_degraded(conf);
7667
7668         if (has_failed(conf)) {
7669                 pr_crit("md/raid:%s: not enough operational devices (%d/%d failed)\n",
7670                         mdname(mddev), mddev->degraded, conf->raid_disks);
7671                 goto abort;
7672         }
7673
7674         /* device size must be a multiple of chunk size */
7675         mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
7676         mddev->resync_max_sectors = mddev->dev_sectors;
7677
7678         if (mddev->degraded > dirty_parity_disks &&
7679             mddev->recovery_cp != MaxSector) {
7680                 if (test_bit(MD_HAS_PPL, &mddev->flags))
7681                         pr_crit("md/raid:%s: starting dirty degraded array with PPL.\n",
7682                                 mdname(mddev));
7683                 else if (mddev->ok_start_degraded)
7684                         pr_crit("md/raid:%s: starting dirty degraded array - data corruption possible.\n",
7685                                 mdname(mddev));
7686                 else {
7687                         pr_crit("md/raid:%s: cannot start dirty degraded array.\n",
7688                                 mdname(mddev));
7689                         goto abort;
7690                 }
7691         }
7692
7693         pr_info("md/raid:%s: raid level %d active with %d out of %d devices, algorithm %d\n",
7694                 mdname(mddev), conf->level,
7695                 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
7696                 mddev->new_layout);
7697
7698         print_raid5_conf(conf);
7699
7700         if (conf->reshape_progress != MaxSector) {
7701                 conf->reshape_safe = conf->reshape_progress;
7702                 atomic_set(&conf->reshape_stripes, 0);
7703                 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7704                 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7705                 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7706                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7707                 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7708                                                         "reshape");
7709                 if (!mddev->sync_thread)
7710                         goto abort;
7711         }
7712
7713         /* Ok, everything is just fine now */
7714         if (mddev->to_remove == &raid5_attrs_group)
7715                 mddev->to_remove = NULL;
7716         else if (mddev->kobj.sd &&
7717             sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
7718                 pr_warn("raid5: failed to create sysfs attributes for %s\n",
7719                         mdname(mddev));
7720         md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7721
7722         if (mddev->queue) {
7723                 int chunk_size;
7724                 /* read-ahead size must cover two whole stripes, which
7725                  * is 2 * (datadisks) * chunksize where 'n' is the
7726                  * number of raid devices
7727                  */
7728                 int data_disks = conf->previous_raid_disks - conf->max_degraded;
7729                 int stripe = data_disks *
7730                         ((mddev->chunk_sectors << 9) / PAGE_SIZE);
7731
7732                 chunk_size = mddev->chunk_sectors << 9;
7733                 blk_queue_io_min(mddev->queue, chunk_size);
7734                 raid5_set_io_opt(conf);
7735                 mddev->queue->limits.raid_partial_stripes_expensive = 1;
7736                 /*
7737                  * We can only discard a whole stripe. It doesn't make sense to
7738                  * discard data disk but write parity disk
7739                  */
7740                 stripe = stripe * PAGE_SIZE;
7741                 /* Round up to power of 2, as discard handling
7742                  * currently assumes that */
7743                 while ((stripe-1) & stripe)
7744                         stripe = (stripe | (stripe-1)) + 1;
7745                 mddev->queue->limits.discard_alignment = stripe;
7746                 mddev->queue->limits.discard_granularity = stripe;
7747
7748                 blk_queue_max_write_same_sectors(mddev->queue, 0);
7749                 blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
7750
7751                 rdev_for_each(rdev, mddev) {
7752                         disk_stack_limits(mddev->gendisk, rdev->bdev,
7753                                           rdev->data_offset << 9);
7754                         disk_stack_limits(mddev->gendisk, rdev->bdev,
7755                                           rdev->new_data_offset << 9);
7756                 }
7757
7758                 /*
7759                  * zeroing is required, otherwise data
7760                  * could be lost. Consider a scenario: discard a stripe
7761                  * (the stripe could be inconsistent if
7762                  * discard_zeroes_data is 0); write one disk of the
7763                  * stripe (the stripe could be inconsistent again
7764                  * depending on which disks are used to calculate
7765                  * parity); the disk is broken; The stripe data of this
7766                  * disk is lost.
7767                  *
7768                  * We only allow DISCARD if the sysadmin has confirmed that
7769                  * only safe devices are in use by setting a module parameter.
7770                  * A better idea might be to turn DISCARD into WRITE_ZEROES
7771                  * requests, as that is required to be safe.
7772                  */
7773                 if (devices_handle_discard_safely &&
7774                     mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7775                     mddev->queue->limits.discard_granularity >= stripe)
7776                         blk_queue_flag_set(QUEUE_FLAG_DISCARD,
7777                                                 mddev->queue);
7778                 else
7779                         blk_queue_flag_clear(QUEUE_FLAG_DISCARD,
7780                                                 mddev->queue);
7781
7782                 blk_queue_max_hw_sectors(mddev->queue, UINT_MAX);
7783         }
7784
7785         if (log_init(conf, journal_dev, raid5_has_ppl(conf)))
7786                 goto abort;
7787
7788         return 0;
7789 abort:
7790         md_unregister_thread(&mddev->thread);
7791         print_raid5_conf(conf);
7792         free_conf(conf);
7793         mddev->private = NULL;
7794         pr_warn("md/raid:%s: failed to run raid set.\n", mdname(mddev));
7795         return -EIO;
7796 }
7797
7798 static void raid5_free(struct mddev *mddev, void *priv)
7799 {
7800         struct r5conf *conf = priv;
7801
7802         free_conf(conf);
7803         mddev->to_remove = &raid5_attrs_group;
7804 }
7805
7806 static void raid5_status(struct seq_file *seq, struct mddev *mddev)
7807 {
7808         struct r5conf *conf = mddev->private;
7809         int i;
7810
7811         seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7812                 conf->chunk_sectors / 2, mddev->layout);
7813         seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7814         rcu_read_lock();
7815         for (i = 0; i < conf->raid_disks; i++) {
7816                 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
7817                 seq_printf (seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
7818         }
7819         rcu_read_unlock();
7820         seq_printf (seq, "]");
7821 }
7822
7823 static void print_raid5_conf (struct r5conf *conf)
7824 {
7825         int i;
7826         struct disk_info *tmp;
7827
7828         pr_debug("RAID conf printout:\n");
7829         if (!conf) {
7830                 pr_debug("(conf==NULL)\n");
7831                 return;
7832         }
7833         pr_debug(" --- level:%d rd:%d wd:%d\n", conf->level,
7834                conf->raid_disks,
7835                conf->raid_disks - conf->mddev->degraded);
7836
7837         for (i = 0; i < conf->raid_disks; i++) {
7838                 char b[BDEVNAME_SIZE];
7839                 tmp = conf->disks + i;
7840                 if (tmp->rdev)
7841                         pr_debug(" disk %d, o:%d, dev:%s\n",
7842                                i, !test_bit(Faulty, &tmp->rdev->flags),
7843                                bdevname(tmp->rdev->bdev, b));
7844         }
7845 }
7846
7847 static int raid5_spare_active(struct mddev *mddev)
7848 {
7849         int i;
7850         struct r5conf *conf = mddev->private;
7851         struct disk_info *tmp;
7852         int count = 0;
7853         unsigned long flags;
7854
7855         for (i = 0; i < conf->raid_disks; i++) {
7856                 tmp = conf->disks + i;
7857                 if (tmp->replacement
7858                     && tmp->replacement->recovery_offset == MaxSector
7859                     && !test_bit(Faulty, &tmp->replacement->flags)
7860                     && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7861                         /* Replacement has just become active. */
7862                         if (!tmp->rdev
7863                             || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7864                                 count++;
7865                         if (tmp->rdev) {
7866                                 /* Replaced device not technically faulty,
7867                                  * but we need to be sure it gets removed
7868                                  * and never re-added.
7869                                  */
7870                                 set_bit(Faulty, &tmp->rdev->flags);
7871                                 sysfs_notify_dirent_safe(
7872                                         tmp->rdev->sysfs_state);
7873                         }
7874                         sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7875                 } else if (tmp->rdev
7876                     && tmp->rdev->recovery_offset == MaxSector
7877                     && !test_bit(Faulty, &tmp->rdev->flags)
7878                     && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7879                         count++;
7880                         sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7881                 }
7882         }
7883         spin_lock_irqsave(&conf->device_lock, flags);
7884         mddev->degraded = raid5_calc_degraded(conf);
7885         spin_unlock_irqrestore(&conf->device_lock, flags);
7886         print_raid5_conf(conf);
7887         return count;
7888 }
7889
7890 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7891 {
7892         struct r5conf *conf = mddev->private;
7893         int err = 0;
7894         int number = rdev->raid_disk;
7895         struct md_rdev **rdevp;
7896         struct disk_info *p = conf->disks + number;
7897
7898         print_raid5_conf(conf);
7899         if (test_bit(Journal, &rdev->flags) && conf->log) {
7900                 /*
7901                  * we can't wait pending write here, as this is called in
7902                  * raid5d, wait will deadlock.
7903                  * neilb: there is no locking about new writes here,
7904                  * so this cannot be safe.
7905                  */
7906                 if (atomic_read(&conf->active_stripes) ||
7907                     atomic_read(&conf->r5c_cached_full_stripes) ||
7908                     atomic_read(&conf->r5c_cached_partial_stripes)) {
7909                         return -EBUSY;
7910                 }
7911                 log_exit(conf);
7912                 return 0;
7913         }
7914         if (rdev == p->rdev)
7915                 rdevp = &p->rdev;
7916         else if (rdev == p->replacement)
7917                 rdevp = &p->replacement;
7918         else
7919                 return 0;
7920
7921         if (number >= conf->raid_disks &&
7922             conf->reshape_progress == MaxSector)
7923                 clear_bit(In_sync, &rdev->flags);
7924
7925         if (test_bit(In_sync, &rdev->flags) ||
7926             atomic_read(&rdev->nr_pending)) {
7927                 err = -EBUSY;
7928                 goto abort;
7929         }
7930         /* Only remove non-faulty devices if recovery
7931          * isn't possible.
7932          */
7933         if (!test_bit(Faulty, &rdev->flags) &&
7934             mddev->recovery_disabled != conf->recovery_disabled &&
7935             !has_failed(conf) &&
7936             (!p->replacement || p->replacement == rdev) &&
7937             number < conf->raid_disks) {
7938                 err = -EBUSY;
7939                 goto abort;
7940         }
7941         *rdevp = NULL;
7942         if (!test_bit(RemoveSynchronized, &rdev->flags)) {
7943                 synchronize_rcu();
7944                 if (atomic_read(&rdev->nr_pending)) {
7945                         /* lost the race, try later */
7946                         err = -EBUSY;
7947                         *rdevp = rdev;
7948                 }
7949         }
7950         if (!err) {
7951                 err = log_modify(conf, rdev, false);
7952                 if (err)
7953                         goto abort;
7954         }
7955         if (p->replacement) {
7956                 /* We must have just cleared 'rdev' */
7957                 p->rdev = p->replacement;
7958                 clear_bit(Replacement, &p->replacement->flags);
7959                 smp_mb(); /* Make sure other CPUs may see both as identical
7960                            * but will never see neither - if they are careful
7961                            */
7962                 p->replacement = NULL;
7963
7964                 if (!err)
7965                         err = log_modify(conf, p->rdev, true);
7966         }
7967
7968         clear_bit(WantReplacement, &rdev->flags);
7969 abort:
7970
7971         print_raid5_conf(conf);
7972         return err;
7973 }
7974
7975 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7976 {
7977         struct r5conf *conf = mddev->private;
7978         int ret, err = -EEXIST;
7979         int disk;
7980         struct disk_info *p;
7981         int first = 0;
7982         int last = conf->raid_disks - 1;
7983
7984         if (test_bit(Journal, &rdev->flags)) {
7985                 if (conf->log)
7986                         return -EBUSY;
7987
7988                 rdev->raid_disk = 0;
7989                 /*
7990                  * The array is in readonly mode if journal is missing, so no
7991                  * write requests running. We should be safe
7992                  */
7993                 ret = log_init(conf, rdev, false);
7994                 if (ret)
7995                         return ret;
7996
7997                 ret = r5l_start(conf->log);
7998                 if (ret)
7999                         return ret;
8000
8001                 return 0;
8002         }
8003         if (mddev->recovery_disabled == conf->recovery_disabled)
8004                 return -EBUSY;
8005
8006         if (rdev->saved_raid_disk < 0 && has_failed(conf))
8007                 /* no point adding a device */
8008                 return -EINVAL;
8009
8010         if (rdev->raid_disk >= 0)
8011                 first = last = rdev->raid_disk;
8012
8013         /*
8014          * find the disk ... but prefer rdev->saved_raid_disk
8015          * if possible.
8016          */
8017         if (rdev->saved_raid_disk >= 0 &&
8018             rdev->saved_raid_disk >= first &&
8019             rdev->saved_raid_disk <= last &&
8020             conf->disks[rdev->saved_raid_disk].rdev == NULL)
8021                 first = rdev->saved_raid_disk;
8022
8023         for (disk = first; disk <= last; disk++) {
8024                 p = conf->disks + disk;
8025                 if (p->rdev == NULL) {
8026                         clear_bit(In_sync, &rdev->flags);
8027                         rdev->raid_disk = disk;
8028                         if (rdev->saved_raid_disk != disk)
8029                                 conf->fullsync = 1;
8030                         rcu_assign_pointer(p->rdev, rdev);
8031
8032                         err = log_modify(conf, rdev, true);
8033
8034                         goto out;
8035                 }
8036         }
8037         for (disk = first; disk <= last; disk++) {
8038                 p = conf->disks + disk;
8039                 if (test_bit(WantReplacement, &p->rdev->flags) &&
8040                     p->replacement == NULL) {
8041                         clear_bit(In_sync, &rdev->flags);
8042                         set_bit(Replacement, &rdev->flags);
8043                         rdev->raid_disk = disk;
8044                         err = 0;
8045                         conf->fullsync = 1;
8046                         rcu_assign_pointer(p->replacement, rdev);
8047                         break;
8048                 }
8049         }
8050 out:
8051         print_raid5_conf(conf);
8052         return err;
8053 }
8054
8055 static int raid5_resize(struct mddev *mddev, sector_t sectors)
8056 {
8057         /* no resync is happening, and there is enough space
8058          * on all devices, so we can resize.
8059          * We need to make sure resync covers any new space.
8060          * If the array is shrinking we should possibly wait until
8061          * any io in the removed space completes, but it hardly seems
8062          * worth it.
8063          */
8064         sector_t newsize;
8065         struct r5conf *conf = mddev->private;
8066
8067         if (raid5_has_log(conf) || raid5_has_ppl(conf))
8068                 return -EINVAL;
8069         sectors &= ~((sector_t)conf->chunk_sectors - 1);
8070         newsize = raid5_size(mddev, sectors, mddev->raid_disks);
8071         if (mddev->external_size &&
8072             mddev->array_sectors > newsize)
8073                 return -EINVAL;
8074         if (mddev->bitmap) {
8075                 int ret = md_bitmap_resize(mddev->bitmap, sectors, 0, 0);
8076                 if (ret)
8077                         return ret;
8078         }
8079         md_set_array_sectors(mddev, newsize);
8080         if (sectors > mddev->dev_sectors &&
8081             mddev->recovery_cp > mddev->dev_sectors) {
8082                 mddev->recovery_cp = mddev->dev_sectors;
8083                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8084         }
8085         mddev->dev_sectors = sectors;
8086         mddev->resync_max_sectors = sectors;
8087         return 0;
8088 }
8089
8090 static int check_stripe_cache(struct mddev *mddev)
8091 {
8092         /* Can only proceed if there are plenty of stripe_heads.
8093          * We need a minimum of one full stripe,, and for sensible progress
8094          * it is best to have about 4 times that.
8095          * If we require 4 times, then the default 256 4K stripe_heads will
8096          * allow for chunk sizes up to 256K, which is probably OK.
8097          * If the chunk size is greater, user-space should request more
8098          * stripe_heads first.
8099          */
8100         struct r5conf *conf = mddev->private;
8101         if (((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8102             > conf->min_nr_stripes ||
8103             ((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8104             > conf->min_nr_stripes) {
8105                 pr_warn("md/raid:%s: reshape: not enough stripes.  Needed %lu\n",
8106                         mdname(mddev),
8107                         ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
8108                          / RAID5_STRIPE_SIZE(conf))*4);
8109                 return 0;
8110         }
8111         return 1;
8112 }
8113
8114 static int check_reshape(struct mddev *mddev)
8115 {
8116         struct r5conf *conf = mddev->private;
8117
8118         if (raid5_has_log(conf) || raid5_has_ppl(conf))
8119                 return -EINVAL;
8120         if (mddev->delta_disks == 0 &&
8121             mddev->new_layout == mddev->layout &&
8122             mddev->new_chunk_sectors == mddev->chunk_sectors)
8123                 return 0; /* nothing to do */
8124         if (has_failed(conf))
8125                 return -EINVAL;
8126         if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
8127                 /* We might be able to shrink, but the devices must
8128                  * be made bigger first.
8129                  * For raid6, 4 is the minimum size.
8130                  * Otherwise 2 is the minimum
8131                  */
8132                 int min = 2;
8133                 if (mddev->level == 6)
8134                         min = 4;
8135                 if (mddev->raid_disks + mddev->delta_disks < min)
8136                         return -EINVAL;
8137         }
8138
8139         if (!check_stripe_cache(mddev))
8140                 return -ENOSPC;
8141
8142         if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
8143             mddev->delta_disks > 0)
8144                 if (resize_chunks(conf,
8145                                   conf->previous_raid_disks
8146                                   + max(0, mddev->delta_disks),
8147                                   max(mddev->new_chunk_sectors,
8148                                       mddev->chunk_sectors)
8149                             ) < 0)
8150                         return -ENOMEM;
8151
8152         if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
8153                 return 0; /* never bother to shrink */
8154         return resize_stripes(conf, (conf->previous_raid_disks
8155                                      + mddev->delta_disks));
8156 }
8157
8158 static int raid5_start_reshape(struct mddev *mddev)
8159 {
8160         struct r5conf *conf = mddev->private;
8161         struct md_rdev *rdev;
8162         int spares = 0;
8163         unsigned long flags;
8164
8165         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
8166                 return -EBUSY;
8167
8168         if (!check_stripe_cache(mddev))
8169                 return -ENOSPC;
8170
8171         if (has_failed(conf))
8172                 return -EINVAL;
8173
8174         rdev_for_each(rdev, mddev) {
8175                 if (!test_bit(In_sync, &rdev->flags)
8176                     && !test_bit(Faulty, &rdev->flags))
8177                         spares++;
8178         }
8179
8180         if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
8181                 /* Not enough devices even to make a degraded array
8182                  * of that size
8183                  */
8184                 return -EINVAL;
8185
8186         /* Refuse to reduce size of the array.  Any reductions in
8187          * array size must be through explicit setting of array_size
8188          * attribute.
8189          */
8190         if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
8191             < mddev->array_sectors) {
8192                 pr_warn("md/raid:%s: array size must be reduced before number of disks\n",
8193                         mdname(mddev));
8194                 return -EINVAL;
8195         }
8196
8197         atomic_set(&conf->reshape_stripes, 0);
8198         spin_lock_irq(&conf->device_lock);
8199         write_seqcount_begin(&conf->gen_lock);
8200         conf->previous_raid_disks = conf->raid_disks;
8201         conf->raid_disks += mddev->delta_disks;
8202         conf->prev_chunk_sectors = conf->chunk_sectors;
8203         conf->chunk_sectors = mddev->new_chunk_sectors;
8204         conf->prev_algo = conf->algorithm;
8205         conf->algorithm = mddev->new_layout;
8206         conf->generation++;
8207         /* Code that selects data_offset needs to see the generation update
8208          * if reshape_progress has been set - so a memory barrier needed.
8209          */
8210         smp_mb();
8211         if (mddev->reshape_backwards)
8212                 conf->reshape_progress = raid5_size(mddev, 0, 0);
8213         else
8214                 conf->reshape_progress = 0;
8215         conf->reshape_safe = conf->reshape_progress;
8216         write_seqcount_end(&conf->gen_lock);
8217         spin_unlock_irq(&conf->device_lock);
8218
8219         /* Now make sure any requests that proceeded on the assumption
8220          * the reshape wasn't running - like Discard or Read - have
8221          * completed.
8222          */
8223         mddev_suspend(mddev);
8224         mddev_resume(mddev);
8225
8226         /* Add some new drives, as many as will fit.
8227          * We know there are enough to make the newly sized array work.
8228          * Don't add devices if we are reducing the number of
8229          * devices in the array.  This is because it is not possible
8230          * to correctly record the "partially reconstructed" state of
8231          * such devices during the reshape and confusion could result.
8232          */
8233         if (mddev->delta_disks >= 0) {
8234                 rdev_for_each(rdev, mddev)
8235                         if (rdev->raid_disk < 0 &&
8236                             !test_bit(Faulty, &rdev->flags)) {
8237                                 if (raid5_add_disk(mddev, rdev) == 0) {
8238                                         if (rdev->raid_disk
8239                                             >= conf->previous_raid_disks)
8240                                                 set_bit(In_sync, &rdev->flags);
8241                                         else
8242                                                 rdev->recovery_offset = 0;
8243
8244                                         /* Failure here is OK */
8245                                         sysfs_link_rdev(mddev, rdev);
8246                                 }
8247                         } else if (rdev->raid_disk >= conf->previous_raid_disks
8248                                    && !test_bit(Faulty, &rdev->flags)) {
8249                                 /* This is a spare that was manually added */
8250                                 set_bit(In_sync, &rdev->flags);
8251                         }
8252
8253                 /* When a reshape changes the number of devices,
8254                  * ->degraded is measured against the larger of the
8255                  * pre and post number of devices.
8256                  */
8257                 spin_lock_irqsave(&conf->device_lock, flags);
8258                 mddev->degraded = raid5_calc_degraded(conf);
8259                 spin_unlock_irqrestore(&conf->device_lock, flags);
8260         }
8261         mddev->raid_disks = conf->raid_disks;
8262         mddev->reshape_position = conf->reshape_progress;
8263         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8264
8265         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8266         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8267         clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8268         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8269         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8270         mddev->sync_thread = md_register_thread(md_do_sync, mddev,
8271                                                 "reshape");
8272         if (!mddev->sync_thread) {
8273                 mddev->recovery = 0;
8274                 spin_lock_irq(&conf->device_lock);
8275                 write_seqcount_begin(&conf->gen_lock);
8276                 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
8277                 mddev->new_chunk_sectors =
8278                         conf->chunk_sectors = conf->prev_chunk_sectors;
8279                 mddev->new_layout = conf->algorithm = conf->prev_algo;
8280                 rdev_for_each(rdev, mddev)
8281                         rdev->new_data_offset = rdev->data_offset;
8282                 smp_wmb();
8283                 conf->generation --;
8284                 conf->reshape_progress = MaxSector;
8285                 mddev->reshape_position = MaxSector;
8286                 write_seqcount_end(&conf->gen_lock);
8287                 spin_unlock_irq(&conf->device_lock);
8288                 return -EAGAIN;
8289         }
8290         conf->reshape_checkpoint = jiffies;
8291         md_wakeup_thread(mddev->sync_thread);
8292         md_new_event(mddev);
8293         return 0;
8294 }
8295
8296 /* This is called from the reshape thread and should make any
8297  * changes needed in 'conf'
8298  */
8299 static void end_reshape(struct r5conf *conf)
8300 {
8301
8302         if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
8303                 struct md_rdev *rdev;
8304
8305                 spin_lock_irq(&conf->device_lock);
8306                 conf->previous_raid_disks = conf->raid_disks;
8307                 md_finish_reshape(conf->mddev);
8308                 smp_wmb();
8309                 conf->reshape_progress = MaxSector;
8310                 conf->mddev->reshape_position = MaxSector;
8311                 rdev_for_each(rdev, conf->mddev)
8312                         if (rdev->raid_disk >= 0 &&
8313                             !test_bit(Journal, &rdev->flags) &&
8314                             !test_bit(In_sync, &rdev->flags))
8315                                 rdev->recovery_offset = MaxSector;
8316                 spin_unlock_irq(&conf->device_lock);
8317                 wake_up(&conf->wait_for_overlap);
8318
8319                 if (conf->mddev->queue)
8320                         raid5_set_io_opt(conf);
8321         }
8322 }
8323
8324 /* This is called from the raid5d thread with mddev_lock held.
8325  * It makes config changes to the device.
8326  */
8327 static void raid5_finish_reshape(struct mddev *mddev)
8328 {
8329         struct r5conf *conf = mddev->private;
8330
8331         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8332
8333                 if (mddev->delta_disks <= 0) {
8334                         int d;
8335                         spin_lock_irq(&conf->device_lock);
8336                         mddev->degraded = raid5_calc_degraded(conf);
8337                         spin_unlock_irq(&conf->device_lock);
8338                         for (d = conf->raid_disks ;
8339                              d < conf->raid_disks - mddev->delta_disks;
8340                              d++) {
8341                                 struct md_rdev *rdev = conf->disks[d].rdev;
8342                                 if (rdev)
8343                                         clear_bit(In_sync, &rdev->flags);
8344                                 rdev = conf->disks[d].replacement;
8345                                 if (rdev)
8346                                         clear_bit(In_sync, &rdev->flags);
8347                         }
8348                 }
8349                 mddev->layout = conf->algorithm;
8350                 mddev->chunk_sectors = conf->chunk_sectors;
8351                 mddev->reshape_position = MaxSector;
8352                 mddev->delta_disks = 0;
8353                 mddev->reshape_backwards = 0;
8354         }
8355 }
8356
8357 static void raid5_quiesce(struct mddev *mddev, int quiesce)
8358 {
8359         struct r5conf *conf = mddev->private;
8360
8361         if (quiesce) {
8362                 /* stop all writes */
8363                 lock_all_device_hash_locks_irq(conf);
8364                 /* '2' tells resync/reshape to pause so that all
8365                  * active stripes can drain
8366                  */
8367                 r5c_flush_cache(conf, INT_MAX);
8368                 conf->quiesce = 2;
8369                 wait_event_cmd(conf->wait_for_quiescent,
8370                                     atomic_read(&conf->active_stripes) == 0 &&
8371                                     atomic_read(&conf->active_aligned_reads) == 0,
8372                                     unlock_all_device_hash_locks_irq(conf),
8373                                     lock_all_device_hash_locks_irq(conf));
8374                 conf->quiesce = 1;
8375                 unlock_all_device_hash_locks_irq(conf);
8376                 /* allow reshape to continue */
8377                 wake_up(&conf->wait_for_overlap);
8378         } else {
8379                 /* re-enable writes */
8380                 lock_all_device_hash_locks_irq(conf);
8381                 conf->quiesce = 0;
8382                 wake_up(&conf->wait_for_quiescent);
8383                 wake_up(&conf->wait_for_overlap);
8384                 unlock_all_device_hash_locks_irq(conf);
8385         }
8386         log_quiesce(conf, quiesce);
8387 }
8388
8389 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
8390 {
8391         struct r0conf *raid0_conf = mddev->private;
8392         sector_t sectors;
8393
8394         /* for raid0 takeover only one zone is supported */
8395         if (raid0_conf->nr_strip_zones > 1) {
8396                 pr_warn("md/raid:%s: cannot takeover raid0 with more than one zone.\n",
8397                         mdname(mddev));
8398                 return ERR_PTR(-EINVAL);
8399         }
8400
8401         sectors = raid0_conf->strip_zone[0].zone_end;
8402         sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
8403         mddev->dev_sectors = sectors;
8404         mddev->new_level = level;
8405         mddev->new_layout = ALGORITHM_PARITY_N;
8406         mddev->new_chunk_sectors = mddev->chunk_sectors;
8407         mddev->raid_disks += 1;
8408         mddev->delta_disks = 1;
8409         /* make sure it will be not marked as dirty */
8410         mddev->recovery_cp = MaxSector;
8411
8412         return setup_conf(mddev);
8413 }
8414
8415 static void *raid5_takeover_raid1(struct mddev *mddev)
8416 {
8417         int chunksect;
8418         void *ret;
8419
8420         if (mddev->raid_disks != 2 ||
8421             mddev->degraded > 1)
8422                 return ERR_PTR(-EINVAL);
8423
8424         /* Should check if there are write-behind devices? */
8425
8426         chunksect = 64*2; /* 64K by default */
8427
8428         /* The array must be an exact multiple of chunksize */
8429         while (chunksect && (mddev->array_sectors & (chunksect-1)))
8430                 chunksect >>= 1;
8431
8432         if ((chunksect<<9) < RAID5_STRIPE_SIZE((struct r5conf *)mddev->private))
8433                 /* array size does not allow a suitable chunk size */
8434                 return ERR_PTR(-EINVAL);
8435
8436         mddev->new_level = 5;
8437         mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
8438         mddev->new_chunk_sectors = chunksect;
8439
8440         ret = setup_conf(mddev);
8441         if (!IS_ERR(ret))
8442                 mddev_clear_unsupported_flags(mddev,
8443                         UNSUPPORTED_MDDEV_FLAGS);
8444         return ret;
8445 }
8446
8447 static void *raid5_takeover_raid6(struct mddev *mddev)
8448 {
8449         int new_layout;
8450
8451         switch (mddev->layout) {
8452         case ALGORITHM_LEFT_ASYMMETRIC_6:
8453                 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
8454                 break;
8455         case ALGORITHM_RIGHT_ASYMMETRIC_6:
8456                 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
8457                 break;
8458         case ALGORITHM_LEFT_SYMMETRIC_6:
8459                 new_layout = ALGORITHM_LEFT_SYMMETRIC;
8460                 break;
8461         case ALGORITHM_RIGHT_SYMMETRIC_6:
8462                 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
8463                 break;
8464         case ALGORITHM_PARITY_0_6:
8465                 new_layout = ALGORITHM_PARITY_0;
8466                 break;
8467         case ALGORITHM_PARITY_N:
8468                 new_layout = ALGORITHM_PARITY_N;
8469                 break;
8470         default:
8471                 return ERR_PTR(-EINVAL);
8472         }
8473         mddev->new_level = 5;
8474         mddev->new_layout = new_layout;
8475         mddev->delta_disks = -1;
8476         mddev->raid_disks -= 1;
8477         return setup_conf(mddev);
8478 }
8479
8480 static int raid5_check_reshape(struct mddev *mddev)
8481 {
8482         /* For a 2-drive array, the layout and chunk size can be changed
8483          * immediately as not restriping is needed.
8484          * For larger arrays we record the new value - after validation
8485          * to be used by a reshape pass.
8486          */
8487         struct r5conf *conf = mddev->private;
8488         int new_chunk = mddev->new_chunk_sectors;
8489
8490         if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
8491                 return -EINVAL;
8492         if (new_chunk > 0) {
8493                 if (!is_power_of_2(new_chunk))
8494                         return -EINVAL;
8495                 if (new_chunk < (PAGE_SIZE>>9))
8496                         return -EINVAL;
8497                 if (mddev->array_sectors & (new_chunk-1))
8498                         /* not factor of array size */
8499                         return -EINVAL;
8500         }
8501
8502         /* They look valid */
8503
8504         if (mddev->raid_disks == 2) {
8505                 /* can make the change immediately */
8506                 if (mddev->new_layout >= 0) {
8507                         conf->algorithm = mddev->new_layout;
8508                         mddev->layout = mddev->new_layout;
8509                 }
8510                 if (new_chunk > 0) {
8511                         conf->chunk_sectors = new_chunk ;
8512                         mddev->chunk_sectors = new_chunk;
8513                 }
8514                 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8515                 md_wakeup_thread(mddev->thread);
8516         }
8517         return check_reshape(mddev);
8518 }
8519
8520 static int raid6_check_reshape(struct mddev *mddev)
8521 {
8522         int new_chunk = mddev->new_chunk_sectors;
8523
8524         if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
8525                 return -EINVAL;
8526         if (new_chunk > 0) {
8527                 if (!is_power_of_2(new_chunk))
8528                         return -EINVAL;
8529                 if (new_chunk < (PAGE_SIZE >> 9))
8530                         return -EINVAL;
8531                 if (mddev->array_sectors & (new_chunk-1))
8532                         /* not factor of array size */
8533                         return -EINVAL;
8534         }
8535
8536         /* They look valid */
8537         return check_reshape(mddev);
8538 }
8539
8540 static void *raid5_takeover(struct mddev *mddev)
8541 {
8542         /* raid5 can take over:
8543          *  raid0 - if there is only one strip zone - make it a raid4 layout
8544          *  raid1 - if there are two drives.  We need to know the chunk size
8545          *  raid4 - trivial - just use a raid4 layout.
8546          *  raid6 - Providing it is a *_6 layout
8547          */
8548         if (mddev->level == 0)
8549                 return raid45_takeover_raid0(mddev, 5);
8550         if (mddev->level == 1)
8551                 return raid5_takeover_raid1(mddev);
8552         if (mddev->level == 4) {
8553                 mddev->new_layout = ALGORITHM_PARITY_N;
8554                 mddev->new_level = 5;
8555                 return setup_conf(mddev);
8556         }
8557         if (mddev->level == 6)
8558                 return raid5_takeover_raid6(mddev);
8559
8560         return ERR_PTR(-EINVAL);
8561 }
8562
8563 static void *raid4_takeover(struct mddev *mddev)
8564 {
8565         /* raid4 can take over:
8566          *  raid0 - if there is only one strip zone
8567          *  raid5 - if layout is right
8568          */
8569         if (mddev->level == 0)
8570                 return raid45_takeover_raid0(mddev, 4);
8571         if (mddev->level == 5 &&
8572             mddev->layout == ALGORITHM_PARITY_N) {
8573                 mddev->new_layout = 0;
8574                 mddev->new_level = 4;
8575                 return setup_conf(mddev);
8576         }
8577         return ERR_PTR(-EINVAL);
8578 }
8579
8580 static struct md_personality raid5_personality;
8581
8582 static void *raid6_takeover(struct mddev *mddev)
8583 {
8584         /* Currently can only take over a raid5.  We map the
8585          * personality to an equivalent raid6 personality
8586          * with the Q block at the end.
8587          */
8588         int new_layout;
8589
8590         if (mddev->pers != &raid5_personality)
8591                 return ERR_PTR(-EINVAL);
8592         if (mddev->degraded > 1)
8593                 return ERR_PTR(-EINVAL);
8594         if (mddev->raid_disks > 253)
8595                 return ERR_PTR(-EINVAL);
8596         if (mddev->raid_disks < 3)
8597                 return ERR_PTR(-EINVAL);
8598
8599         switch (mddev->layout) {
8600         case ALGORITHM_LEFT_ASYMMETRIC:
8601                 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
8602                 break;
8603         case ALGORITHM_RIGHT_ASYMMETRIC:
8604                 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
8605                 break;
8606         case ALGORITHM_LEFT_SYMMETRIC:
8607                 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
8608                 break;
8609         case ALGORITHM_RIGHT_SYMMETRIC:
8610                 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
8611                 break;
8612         case ALGORITHM_PARITY_0:
8613                 new_layout = ALGORITHM_PARITY_0_6;
8614                 break;
8615         case ALGORITHM_PARITY_N:
8616                 new_layout = ALGORITHM_PARITY_N;
8617                 break;
8618         default:
8619                 return ERR_PTR(-EINVAL);
8620         }
8621         mddev->new_level = 6;
8622         mddev->new_layout = new_layout;
8623         mddev->delta_disks = 1;
8624         mddev->raid_disks += 1;
8625         return setup_conf(mddev);
8626 }
8627
8628 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
8629 {
8630         struct r5conf *conf;
8631         int err;
8632
8633         err = mddev_lock(mddev);
8634         if (err)
8635                 return err;
8636         conf = mddev->private;
8637         if (!conf) {
8638                 mddev_unlock(mddev);
8639                 return -ENODEV;
8640         }
8641
8642         if (strncmp(buf, "ppl", 3) == 0) {
8643                 /* ppl only works with RAID 5 */
8644                 if (!raid5_has_ppl(conf) && conf->level == 5) {
8645                         err = log_init(conf, NULL, true);
8646                         if (!err) {
8647                                 err = resize_stripes(conf, conf->pool_size);
8648                                 if (err)
8649                                         log_exit(conf);
8650                         }
8651                 } else
8652                         err = -EINVAL;
8653         } else if (strncmp(buf, "resync", 6) == 0) {
8654                 if (raid5_has_ppl(conf)) {
8655                         mddev_suspend(mddev);
8656                         log_exit(conf);
8657                         mddev_resume(mddev);
8658                         err = resize_stripes(conf, conf->pool_size);
8659                 } else if (test_bit(MD_HAS_JOURNAL, &conf->mddev->flags) &&
8660                            r5l_log_disk_error(conf)) {
8661                         bool journal_dev_exists = false;
8662                         struct md_rdev *rdev;
8663
8664                         rdev_for_each(rdev, mddev)
8665                                 if (test_bit(Journal, &rdev->flags)) {
8666                                         journal_dev_exists = true;
8667                                         break;
8668                                 }
8669
8670                         if (!journal_dev_exists) {
8671                                 mddev_suspend(mddev);
8672                                 clear_bit(MD_HAS_JOURNAL, &mddev->flags);
8673                                 mddev_resume(mddev);
8674                         } else  /* need remove journal device first */
8675                                 err = -EBUSY;
8676                 } else
8677                         err = -EINVAL;
8678         } else {
8679                 err = -EINVAL;
8680         }
8681
8682         if (!err)
8683                 md_update_sb(mddev, 1);
8684
8685         mddev_unlock(mddev);
8686
8687         return err;
8688 }
8689
8690 static int raid5_start(struct mddev *mddev)
8691 {
8692         struct r5conf *conf = mddev->private;
8693
8694         return r5l_start(conf->log);
8695 }
8696
8697 static struct md_personality raid6_personality =
8698 {
8699         .name           = "raid6",
8700         .level          = 6,
8701         .owner          = THIS_MODULE,
8702         .make_request   = raid5_make_request,
8703         .run            = raid5_run,
8704         .start          = raid5_start,
8705         .free           = raid5_free,
8706         .status         = raid5_status,
8707         .error_handler  = raid5_error,
8708         .hot_add_disk   = raid5_add_disk,
8709         .hot_remove_disk= raid5_remove_disk,
8710         .spare_active   = raid5_spare_active,
8711         .sync_request   = raid5_sync_request,
8712         .resize         = raid5_resize,
8713         .size           = raid5_size,
8714         .check_reshape  = raid6_check_reshape,
8715         .start_reshape  = raid5_start_reshape,
8716         .finish_reshape = raid5_finish_reshape,
8717         .quiesce        = raid5_quiesce,
8718         .takeover       = raid6_takeover,
8719         .change_consistency_policy = raid5_change_consistency_policy,
8720 };
8721 static struct md_personality raid5_personality =
8722 {
8723         .name           = "raid5",
8724         .level          = 5,
8725         .owner          = THIS_MODULE,
8726         .make_request   = raid5_make_request,
8727         .run            = raid5_run,
8728         .start          = raid5_start,
8729         .free           = raid5_free,
8730         .status         = raid5_status,
8731         .error_handler  = raid5_error,
8732         .hot_add_disk   = raid5_add_disk,
8733         .hot_remove_disk= raid5_remove_disk,
8734         .spare_active   = raid5_spare_active,
8735         .sync_request   = raid5_sync_request,
8736         .resize         = raid5_resize,
8737         .size           = raid5_size,
8738         .check_reshape  = raid5_check_reshape,
8739         .start_reshape  = raid5_start_reshape,
8740         .finish_reshape = raid5_finish_reshape,
8741         .quiesce        = raid5_quiesce,
8742         .takeover       = raid5_takeover,
8743         .change_consistency_policy = raid5_change_consistency_policy,
8744 };
8745
8746 static struct md_personality raid4_personality =
8747 {
8748         .name           = "raid4",
8749         .level          = 4,
8750         .owner          = THIS_MODULE,
8751         .make_request   = raid5_make_request,
8752         .run            = raid5_run,
8753         .start          = raid5_start,
8754         .free           = raid5_free,
8755         .status         = raid5_status,
8756         .error_handler  = raid5_error,
8757         .hot_add_disk   = raid5_add_disk,
8758         .hot_remove_disk= raid5_remove_disk,
8759         .spare_active   = raid5_spare_active,
8760         .sync_request   = raid5_sync_request,
8761         .resize         = raid5_resize,
8762         .size           = raid5_size,
8763         .check_reshape  = raid5_check_reshape,
8764         .start_reshape  = raid5_start_reshape,
8765         .finish_reshape = raid5_finish_reshape,
8766         .quiesce        = raid5_quiesce,
8767         .takeover       = raid4_takeover,
8768         .change_consistency_policy = raid5_change_consistency_policy,
8769 };
8770
8771 static int __init raid5_init(void)
8772 {
8773         int ret;
8774
8775         raid5_wq = alloc_workqueue("raid5wq",
8776                 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
8777         if (!raid5_wq)
8778                 return -ENOMEM;
8779
8780         ret = cpuhp_setup_state_multi(CPUHP_MD_RAID5_PREPARE,
8781                                       "md/raid5:prepare",
8782                                       raid456_cpu_up_prepare,
8783                                       raid456_cpu_dead);
8784         if (ret) {
8785                 destroy_workqueue(raid5_wq);
8786                 return ret;
8787         }
8788         register_md_personality(&raid6_personality);
8789         register_md_personality(&raid5_personality);
8790         register_md_personality(&raid4_personality);
8791         return 0;
8792 }
8793
8794 static void raid5_exit(void)
8795 {
8796         unregister_md_personality(&raid6_personality);
8797         unregister_md_personality(&raid5_personality);
8798         unregister_md_personality(&raid4_personality);
8799         cpuhp_remove_multi_state(CPUHP_MD_RAID5_PREPARE);
8800         destroy_workqueue(raid5_wq);
8801 }
8802
8803 module_init(raid5_init);
8804 module_exit(raid5_exit);
8805 MODULE_LICENSE("GPL");
8806 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
8807 MODULE_ALIAS("md-personality-4"); /* RAID5 */
8808 MODULE_ALIAS("md-raid5");
8809 MODULE_ALIAS("md-raid4");
8810 MODULE_ALIAS("md-level-5");
8811 MODULE_ALIAS("md-level-4");
8812 MODULE_ALIAS("md-personality-8"); /* RAID6 */
8813 MODULE_ALIAS("md-raid6");
8814 MODULE_ALIAS("md-level-6");
8815
8816 /* This used to be two separate modules, they were: */
8817 MODULE_ALIAS("raid5");
8818 MODULE_ALIAS("raid6");