Revert "block: don't call into the driver for BLKROSET"
[platform/kernel/linux-rpi.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,
1228                                                 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,
1278                                                 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_light();
2222         percpu = per_cpu_ptr(conf->percpu, cpu);
2223         spin_lock(&percpu->lock);
2224         if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
2225                 ops_run_biofill(sh);
2226                 overlap_clear++;
2227         }
2228
2229         if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
2230                 if (level < 6)
2231                         tx = ops_run_compute5(sh, percpu);
2232                 else {
2233                         if (sh->ops.target2 < 0 || sh->ops.target < 0)
2234                                 tx = ops_run_compute6_1(sh, percpu);
2235                         else
2236                                 tx = ops_run_compute6_2(sh, percpu);
2237                 }
2238                 /* terminate the chain if reconstruct is not set to be run */
2239                 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
2240                         async_tx_ack(tx);
2241         }
2242
2243         if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
2244                 if (level < 6)
2245                         tx = ops_run_prexor5(sh, percpu, tx);
2246                 else
2247                         tx = ops_run_prexor6(sh, percpu, tx);
2248         }
2249
2250         if (test_bit(STRIPE_OP_PARTIAL_PARITY, &ops_request))
2251                 tx = ops_run_partial_parity(sh, percpu, tx);
2252
2253         if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
2254                 tx = ops_run_biodrain(sh, tx);
2255                 overlap_clear++;
2256         }
2257
2258         if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
2259                 if (level < 6)
2260                         ops_run_reconstruct5(sh, percpu, tx);
2261                 else
2262                         ops_run_reconstruct6(sh, percpu, tx);
2263         }
2264
2265         if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
2266                 if (sh->check_state == check_state_run)
2267                         ops_run_check_p(sh, percpu);
2268                 else if (sh->check_state == check_state_run_q)
2269                         ops_run_check_pq(sh, percpu, 0);
2270                 else if (sh->check_state == check_state_run_pq)
2271                         ops_run_check_pq(sh, percpu, 1);
2272                 else
2273                         BUG();
2274         }
2275
2276         if (overlap_clear && !sh->batch_head)
2277                 for (i = disks; i--; ) {
2278                         struct r5dev *dev = &sh->dev[i];
2279                         if (test_and_clear_bit(R5_Overlap, &dev->flags))
2280                                 wake_up(&sh->raid_conf->wait_for_overlap);
2281                 }
2282         spin_unlock(&percpu->lock);
2283         put_cpu_light();
2284 }
2285
2286 static void free_stripe(struct kmem_cache *sc, struct stripe_head *sh)
2287 {
2288 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2289         kfree(sh->pages);
2290 #endif
2291         if (sh->ppl_page)
2292                 __free_page(sh->ppl_page);
2293         kmem_cache_free(sc, sh);
2294 }
2295
2296 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp,
2297         int disks, struct r5conf *conf)
2298 {
2299         struct stripe_head *sh;
2300         int i;
2301
2302         sh = kmem_cache_zalloc(sc, gfp);
2303         if (sh) {
2304                 spin_lock_init(&sh->stripe_lock);
2305                 spin_lock_init(&sh->batch_lock);
2306                 INIT_LIST_HEAD(&sh->batch_list);
2307                 INIT_LIST_HEAD(&sh->lru);
2308                 INIT_LIST_HEAD(&sh->r5c);
2309                 INIT_LIST_HEAD(&sh->log_list);
2310                 atomic_set(&sh->count, 1);
2311                 sh->raid_conf = conf;
2312                 sh->log_start = MaxSector;
2313                 for (i = 0; i < disks; i++) {
2314                         struct r5dev *dev = &sh->dev[i];
2315
2316                         bio_init(&dev->req, &dev->vec, 1);
2317                         bio_init(&dev->rreq, &dev->rvec, 1);
2318                 }
2319
2320                 if (raid5_has_ppl(conf)) {
2321                         sh->ppl_page = alloc_page(gfp);
2322                         if (!sh->ppl_page) {
2323                                 free_stripe(sc, sh);
2324                                 return NULL;
2325                         }
2326                 }
2327 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2328                 if (init_stripe_shared_pages(sh, conf, disks)) {
2329                         free_stripe(sc, sh);
2330                         return NULL;
2331                 }
2332 #endif
2333         }
2334         return sh;
2335 }
2336 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2337 {
2338         struct stripe_head *sh;
2339
2340         sh = alloc_stripe(conf->slab_cache, gfp, conf->pool_size, conf);
2341         if (!sh)
2342                 return 0;
2343
2344         if (grow_buffers(sh, gfp)) {
2345                 shrink_buffers(sh);
2346                 free_stripe(conf->slab_cache, sh);
2347                 return 0;
2348         }
2349         sh->hash_lock_index =
2350                 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2351         /* we just created an active stripe so... */
2352         atomic_inc(&conf->active_stripes);
2353
2354         raid5_release_stripe(sh);
2355         conf->max_nr_stripes++;
2356         return 1;
2357 }
2358
2359 static int grow_stripes(struct r5conf *conf, int num)
2360 {
2361         struct kmem_cache *sc;
2362         size_t namelen = sizeof(conf->cache_name[0]);
2363         int devs = max(conf->raid_disks, conf->previous_raid_disks);
2364
2365         if (conf->mddev->gendisk)
2366                 snprintf(conf->cache_name[0], namelen,
2367                         "raid%d-%s", conf->level, mdname(conf->mddev));
2368         else
2369                 snprintf(conf->cache_name[0], namelen,
2370                         "raid%d-%p", conf->level, conf->mddev);
2371         snprintf(conf->cache_name[1], namelen, "%.27s-alt", conf->cache_name[0]);
2372
2373         conf->active_name = 0;
2374         sc = kmem_cache_create(conf->cache_name[conf->active_name],
2375                                sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2376                                0, 0, NULL);
2377         if (!sc)
2378                 return 1;
2379         conf->slab_cache = sc;
2380         conf->pool_size = devs;
2381         while (num--)
2382                 if (!grow_one_stripe(conf, GFP_KERNEL))
2383                         return 1;
2384
2385         return 0;
2386 }
2387
2388 /**
2389  * scribble_alloc - allocate percpu scribble buffer for required size
2390  *                  of the scribble region
2391  * @percpu: from for_each_present_cpu() of the caller
2392  * @num: total number of disks in the array
2393  * @cnt: scribble objs count for required size of the scribble region
2394  *
2395  * The scribble buffer size must be enough to contain:
2396  * 1/ a struct page pointer for each device in the array +2
2397  * 2/ room to convert each entry in (1) to its corresponding dma
2398  *    (dma_map_page()) or page (page_address()) address.
2399  *
2400  * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2401  * calculate over all devices (not just the data blocks), using zeros in place
2402  * of the P and Q blocks.
2403  */
2404 static int scribble_alloc(struct raid5_percpu *percpu,
2405                           int num, int cnt)
2406 {
2407         size_t obj_size =
2408                 sizeof(struct page *) * (num + 2) +
2409                 sizeof(addr_conv_t) * (num + 2) +
2410                 sizeof(unsigned int) * (num + 2);
2411         void *scribble;
2412
2413         /*
2414          * If here is in raid array suspend context, it is in memalloc noio
2415          * context as well, there is no potential recursive memory reclaim
2416          * I/Os with the GFP_KERNEL flag.
2417          */
2418         scribble = kvmalloc_array(cnt, obj_size, GFP_KERNEL);
2419         if (!scribble)
2420                 return -ENOMEM;
2421
2422         kvfree(percpu->scribble);
2423
2424         percpu->scribble = scribble;
2425         percpu->scribble_obj_size = obj_size;
2426         return 0;
2427 }
2428
2429 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2430 {
2431         unsigned long cpu;
2432         int err = 0;
2433
2434         /*
2435          * Never shrink. And mddev_suspend() could deadlock if this is called
2436          * from raid5d. In that case, scribble_disks and scribble_sectors
2437          * should equal to new_disks and new_sectors
2438          */
2439         if (conf->scribble_disks >= new_disks &&
2440             conf->scribble_sectors >= new_sectors)
2441                 return 0;
2442         mddev_suspend(conf->mddev);
2443         cpus_read_lock();
2444
2445         for_each_present_cpu(cpu) {
2446                 struct raid5_percpu *percpu;
2447
2448                 percpu = per_cpu_ptr(conf->percpu, cpu);
2449                 err = scribble_alloc(percpu, new_disks,
2450                                      new_sectors / RAID5_STRIPE_SECTORS(conf));
2451                 if (err)
2452                         break;
2453         }
2454
2455         cpus_read_unlock();
2456         mddev_resume(conf->mddev);
2457         if (!err) {
2458                 conf->scribble_disks = new_disks;
2459                 conf->scribble_sectors = new_sectors;
2460         }
2461         return err;
2462 }
2463
2464 static int resize_stripes(struct r5conf *conf, int newsize)
2465 {
2466         /* Make all the stripes able to hold 'newsize' devices.
2467          * New slots in each stripe get 'page' set to a new page.
2468          *
2469          * This happens in stages:
2470          * 1/ create a new kmem_cache and allocate the required number of
2471          *    stripe_heads.
2472          * 2/ gather all the old stripe_heads and transfer the pages across
2473          *    to the new stripe_heads.  This will have the side effect of
2474          *    freezing the array as once all stripe_heads have been collected,
2475          *    no IO will be possible.  Old stripe heads are freed once their
2476          *    pages have been transferred over, and the old kmem_cache is
2477          *    freed when all stripes are done.
2478          * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
2479          *    we simple return a failure status - no need to clean anything up.
2480          * 4/ allocate new pages for the new slots in the new stripe_heads.
2481          *    If this fails, we don't bother trying the shrink the
2482          *    stripe_heads down again, we just leave them as they are.
2483          *    As each stripe_head is processed the new one is released into
2484          *    active service.
2485          *
2486          * Once step2 is started, we cannot afford to wait for a write,
2487          * so we use GFP_NOIO allocations.
2488          */
2489         struct stripe_head *osh, *nsh;
2490         LIST_HEAD(newstripes);
2491         struct disk_info *ndisks;
2492         int err = 0;
2493         struct kmem_cache *sc;
2494         int i;
2495         int hash, cnt;
2496
2497         md_allow_write(conf->mddev);
2498
2499         /* Step 1 */
2500         sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2501                                sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2502                                0, 0, NULL);
2503         if (!sc)
2504                 return -ENOMEM;
2505
2506         /* Need to ensure auto-resizing doesn't interfere */
2507         mutex_lock(&conf->cache_size_mutex);
2508
2509         for (i = conf->max_nr_stripes; i; i--) {
2510                 nsh = alloc_stripe(sc, GFP_KERNEL, newsize, conf);
2511                 if (!nsh)
2512                         break;
2513
2514                 list_add(&nsh->lru, &newstripes);
2515         }
2516         if (i) {
2517                 /* didn't get enough, give up */
2518                 while (!list_empty(&newstripes)) {
2519                         nsh = list_entry(newstripes.next, struct stripe_head, lru);
2520                         list_del(&nsh->lru);
2521                         free_stripe(sc, nsh);
2522                 }
2523                 kmem_cache_destroy(sc);
2524                 mutex_unlock(&conf->cache_size_mutex);
2525                 return -ENOMEM;
2526         }
2527         /* Step 2 - Must use GFP_NOIO now.
2528          * OK, we have enough stripes, start collecting inactive
2529          * stripes and copying them over
2530          */
2531         hash = 0;
2532         cnt = 0;
2533         list_for_each_entry(nsh, &newstripes, lru) {
2534                 lock_device_hash_lock(conf, hash);
2535                 wait_event_cmd(conf->wait_for_stripe,
2536                                     !list_empty(conf->inactive_list + hash),
2537                                     unlock_device_hash_lock(conf, hash),
2538                                     lock_device_hash_lock(conf, hash));
2539                 osh = get_free_stripe(conf, hash);
2540                 unlock_device_hash_lock(conf, hash);
2541
2542 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2543         for (i = 0; i < osh->nr_pages; i++) {
2544                 nsh->pages[i] = osh->pages[i];
2545                 osh->pages[i] = NULL;
2546         }
2547 #endif
2548                 for(i=0; i<conf->pool_size; i++) {
2549                         nsh->dev[i].page = osh->dev[i].page;
2550                         nsh->dev[i].orig_page = osh->dev[i].page;
2551                         nsh->dev[i].offset = osh->dev[i].offset;
2552                 }
2553                 nsh->hash_lock_index = hash;
2554                 free_stripe(conf->slab_cache, osh);
2555                 cnt++;
2556                 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2557                     !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2558                         hash++;
2559                         cnt = 0;
2560                 }
2561         }
2562         kmem_cache_destroy(conf->slab_cache);
2563
2564         /* Step 3.
2565          * At this point, we are holding all the stripes so the array
2566          * is completely stalled, so now is a good time to resize
2567          * conf->disks and the scribble region
2568          */
2569         ndisks = kcalloc(newsize, sizeof(struct disk_info), GFP_NOIO);
2570         if (ndisks) {
2571                 for (i = 0; i < conf->pool_size; i++)
2572                         ndisks[i] = conf->disks[i];
2573
2574                 for (i = conf->pool_size; i < newsize; i++) {
2575                         ndisks[i].extra_page = alloc_page(GFP_NOIO);
2576                         if (!ndisks[i].extra_page)
2577                                 err = -ENOMEM;
2578                 }
2579
2580                 if (err) {
2581                         for (i = conf->pool_size; i < newsize; i++)
2582                                 if (ndisks[i].extra_page)
2583                                         put_page(ndisks[i].extra_page);
2584                         kfree(ndisks);
2585                 } else {
2586                         kfree(conf->disks);
2587                         conf->disks = ndisks;
2588                 }
2589         } else
2590                 err = -ENOMEM;
2591
2592         conf->slab_cache = sc;
2593         conf->active_name = 1-conf->active_name;
2594
2595         /* Step 4, return new stripes to service */
2596         while(!list_empty(&newstripes)) {
2597                 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2598                 list_del_init(&nsh->lru);
2599
2600 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2601                 for (i = 0; i < nsh->nr_pages; i++) {
2602                         if (nsh->pages[i])
2603                                 continue;
2604                         nsh->pages[i] = alloc_page(GFP_NOIO);
2605                         if (!nsh->pages[i])
2606                                 err = -ENOMEM;
2607                 }
2608
2609                 for (i = conf->raid_disks; i < newsize; i++) {
2610                         if (nsh->dev[i].page)
2611                                 continue;
2612                         nsh->dev[i].page = raid5_get_dev_page(nsh, i);
2613                         nsh->dev[i].orig_page = nsh->dev[i].page;
2614                         nsh->dev[i].offset = raid5_get_page_offset(nsh, i);
2615                 }
2616 #else
2617                 for (i=conf->raid_disks; i < newsize; i++)
2618                         if (nsh->dev[i].page == NULL) {
2619                                 struct page *p = alloc_page(GFP_NOIO);
2620                                 nsh->dev[i].page = p;
2621                                 nsh->dev[i].orig_page = p;
2622                                 nsh->dev[i].offset = 0;
2623                                 if (!p)
2624                                         err = -ENOMEM;
2625                         }
2626 #endif
2627                 raid5_release_stripe(nsh);
2628         }
2629         /* critical section pass, GFP_NOIO no longer needed */
2630
2631         if (!err)
2632                 conf->pool_size = newsize;
2633         mutex_unlock(&conf->cache_size_mutex);
2634
2635         return err;
2636 }
2637
2638 static int drop_one_stripe(struct r5conf *conf)
2639 {
2640         struct stripe_head *sh;
2641         int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2642
2643         spin_lock_irq(conf->hash_locks + hash);
2644         sh = get_free_stripe(conf, hash);
2645         spin_unlock_irq(conf->hash_locks + hash);
2646         if (!sh)
2647                 return 0;
2648         BUG_ON(atomic_read(&sh->count));
2649         shrink_buffers(sh);
2650         free_stripe(conf->slab_cache, sh);
2651         atomic_dec(&conf->active_stripes);
2652         conf->max_nr_stripes--;
2653         return 1;
2654 }
2655
2656 static void shrink_stripes(struct r5conf *conf)
2657 {
2658         while (conf->max_nr_stripes &&
2659                drop_one_stripe(conf))
2660                 ;
2661
2662         kmem_cache_destroy(conf->slab_cache);
2663         conf->slab_cache = NULL;
2664 }
2665
2666 static void raid5_end_read_request(struct bio * bi)
2667 {
2668         struct stripe_head *sh = bi->bi_private;
2669         struct r5conf *conf = sh->raid_conf;
2670         int disks = sh->disks, i;
2671         char b[BDEVNAME_SIZE];
2672         struct md_rdev *rdev = NULL;
2673         sector_t s;
2674
2675         for (i=0 ; i<disks; i++)
2676                 if (bi == &sh->dev[i].req)
2677                         break;
2678
2679         pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2680                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2681                 bi->bi_status);
2682         if (i == disks) {
2683                 bio_reset(bi);
2684                 BUG();
2685                 return;
2686         }
2687         if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2688                 /* If replacement finished while this request was outstanding,
2689                  * 'replacement' might be NULL already.
2690                  * In that case it moved down to 'rdev'.
2691                  * rdev is not removed until all requests are finished.
2692                  */
2693                 rdev = conf->disks[i].replacement;
2694         if (!rdev)
2695                 rdev = conf->disks[i].rdev;
2696
2697         if (use_new_offset(conf, sh))
2698                 s = sh->sector + rdev->new_data_offset;
2699         else
2700                 s = sh->sector + rdev->data_offset;
2701         if (!bi->bi_status) {
2702                 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2703                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2704                         /* Note that this cannot happen on a
2705                          * replacement device.  We just fail those on
2706                          * any error
2707                          */
2708                         pr_info_ratelimited(
2709                                 "md/raid:%s: read error corrected (%lu sectors at %llu on %s)\n",
2710                                 mdname(conf->mddev), RAID5_STRIPE_SECTORS(conf),
2711                                 (unsigned long long)s,
2712                                 bdevname(rdev->bdev, b));
2713                         atomic_add(RAID5_STRIPE_SECTORS(conf), &rdev->corrected_errors);
2714                         clear_bit(R5_ReadError, &sh->dev[i].flags);
2715                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
2716                 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2717                         clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2718
2719                 if (test_bit(R5_InJournal, &sh->dev[i].flags))
2720                         /*
2721                          * end read for a page in journal, this
2722                          * must be preparing for prexor in rmw
2723                          */
2724                         set_bit(R5_OrigPageUPTDODATE, &sh->dev[i].flags);
2725
2726                 if (atomic_read(&rdev->read_errors))
2727                         atomic_set(&rdev->read_errors, 0);
2728         } else {
2729                 const char *bdn = bdevname(rdev->bdev, b);
2730                 int retry = 0;
2731                 int set_bad = 0;
2732
2733                 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2734                 if (!(bi->bi_status == BLK_STS_PROTECTION))
2735                         atomic_inc(&rdev->read_errors);
2736                 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2737                         pr_warn_ratelimited(
2738                                 "md/raid:%s: read error on replacement device (sector %llu on %s).\n",
2739                                 mdname(conf->mddev),
2740                                 (unsigned long long)s,
2741                                 bdn);
2742                 else if (conf->mddev->degraded >= conf->max_degraded) {
2743                         set_bad = 1;
2744                         pr_warn_ratelimited(
2745                                 "md/raid:%s: read error not correctable (sector %llu on %s).\n",
2746                                 mdname(conf->mddev),
2747                                 (unsigned long long)s,
2748                                 bdn);
2749                 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2750                         /* Oh, no!!! */
2751                         set_bad = 1;
2752                         pr_warn_ratelimited(
2753                                 "md/raid:%s: read error NOT corrected!! (sector %llu on %s).\n",
2754                                 mdname(conf->mddev),
2755                                 (unsigned long long)s,
2756                                 bdn);
2757                 } else if (atomic_read(&rdev->read_errors)
2758                          > conf->max_nr_stripes) {
2759                         if (!test_bit(Faulty, &rdev->flags)) {
2760                                 pr_warn("md/raid:%s: %d read_errors > %d stripes\n",
2761                                     mdname(conf->mddev),
2762                                     atomic_read(&rdev->read_errors),
2763                                     conf->max_nr_stripes);
2764                                 pr_warn("md/raid:%s: Too many read errors, failing device %s.\n",
2765                                     mdname(conf->mddev), bdn);
2766                         }
2767                 } else
2768                         retry = 1;
2769                 if (set_bad && test_bit(In_sync, &rdev->flags)
2770                     && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2771                         retry = 1;
2772                 if (retry)
2773                         if (sh->qd_idx >= 0 && sh->pd_idx == i)
2774                                 set_bit(R5_ReadError, &sh->dev[i].flags);
2775                         else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2776                                 set_bit(R5_ReadError, &sh->dev[i].flags);
2777                                 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2778                         } else
2779                                 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2780                 else {
2781                         clear_bit(R5_ReadError, &sh->dev[i].flags);
2782                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
2783                         if (!(set_bad
2784                               && test_bit(In_sync, &rdev->flags)
2785                               && rdev_set_badblocks(
2786                                       rdev, sh->sector, RAID5_STRIPE_SECTORS(conf), 0)))
2787                                 md_error(conf->mddev, rdev);
2788                 }
2789         }
2790         rdev_dec_pending(rdev, conf->mddev);
2791         bio_reset(bi);
2792         clear_bit(R5_LOCKED, &sh->dev[i].flags);
2793         set_bit(STRIPE_HANDLE, &sh->state);
2794         raid5_release_stripe(sh);
2795 }
2796
2797 static void raid5_end_write_request(struct bio *bi)
2798 {
2799         struct stripe_head *sh = bi->bi_private;
2800         struct r5conf *conf = sh->raid_conf;
2801         int disks = sh->disks, i;
2802         struct md_rdev *rdev;
2803         sector_t first_bad;
2804         int bad_sectors;
2805         int replacement = 0;
2806
2807         for (i = 0 ; i < disks; i++) {
2808                 if (bi == &sh->dev[i].req) {
2809                         rdev = conf->disks[i].rdev;
2810                         break;
2811                 }
2812                 if (bi == &sh->dev[i].rreq) {
2813                         rdev = conf->disks[i].replacement;
2814                         if (rdev)
2815                                 replacement = 1;
2816                         else
2817                                 /* rdev was removed and 'replacement'
2818                                  * replaced it.  rdev is not removed
2819                                  * until all requests are finished.
2820                                  */
2821                                 rdev = conf->disks[i].rdev;
2822                         break;
2823                 }
2824         }
2825         pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2826                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2827                 bi->bi_status);
2828         if (i == disks) {
2829                 bio_reset(bi);
2830                 BUG();
2831                 return;
2832         }
2833
2834         if (replacement) {
2835                 if (bi->bi_status)
2836                         md_error(conf->mddev, rdev);
2837                 else if (is_badblock(rdev, sh->sector,
2838                                      RAID5_STRIPE_SECTORS(conf),
2839                                      &first_bad, &bad_sectors))
2840                         set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2841         } else {
2842                 if (bi->bi_status) {
2843                         set_bit(STRIPE_DEGRADED, &sh->state);
2844                         set_bit(WriteErrorSeen, &rdev->flags);
2845                         set_bit(R5_WriteError, &sh->dev[i].flags);
2846                         if (!test_and_set_bit(WantReplacement, &rdev->flags))
2847                                 set_bit(MD_RECOVERY_NEEDED,
2848                                         &rdev->mddev->recovery);
2849                 } else if (is_badblock(rdev, sh->sector,
2850                                        RAID5_STRIPE_SECTORS(conf),
2851                                        &first_bad, &bad_sectors)) {
2852                         set_bit(R5_MadeGood, &sh->dev[i].flags);
2853                         if (test_bit(R5_ReadError, &sh->dev[i].flags))
2854                                 /* That was a successful write so make
2855                                  * sure it looks like we already did
2856                                  * a re-write.
2857                                  */
2858                                 set_bit(R5_ReWrite, &sh->dev[i].flags);
2859                 }
2860         }
2861         rdev_dec_pending(rdev, conf->mddev);
2862
2863         if (sh->batch_head && bi->bi_status && !replacement)
2864                 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2865
2866         bio_reset(bi);
2867         if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2868                 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2869         set_bit(STRIPE_HANDLE, &sh->state);
2870
2871         if (sh->batch_head && sh != sh->batch_head)
2872                 raid5_release_stripe(sh->batch_head);
2873         raid5_release_stripe(sh);
2874 }
2875
2876 static void raid5_error(struct mddev *mddev, struct md_rdev *rdev)
2877 {
2878         char b[BDEVNAME_SIZE];
2879         struct r5conf *conf = mddev->private;
2880         unsigned long flags;
2881         pr_debug("raid456: error called\n");
2882
2883         pr_crit("md/raid:%s: Disk failure on %s, disabling device.\n",
2884                 mdname(mddev), bdevname(rdev->bdev, b));
2885
2886         spin_lock_irqsave(&conf->device_lock, flags);
2887         set_bit(Faulty, &rdev->flags);
2888         clear_bit(In_sync, &rdev->flags);
2889         mddev->degraded = raid5_calc_degraded(conf);
2890
2891         if (has_failed(conf)) {
2892                 set_bit(MD_BROKEN, &conf->mddev->flags);
2893                 conf->recovery_disabled = mddev->recovery_disabled;
2894
2895                 pr_crit("md/raid:%s: Cannot continue operation (%d/%d failed).\n",
2896                         mdname(mddev), mddev->degraded, conf->raid_disks);
2897         } else {
2898                 pr_crit("md/raid:%s: Operation continuing on %d devices.\n",
2899                         mdname(mddev), conf->raid_disks - mddev->degraded);
2900         }
2901
2902         spin_unlock_irqrestore(&conf->device_lock, flags);
2903         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2904
2905         set_bit(Blocked, &rdev->flags);
2906         set_mask_bits(&mddev->sb_flags, 0,
2907                       BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
2908         r5c_update_on_rdev_error(mddev, rdev);
2909 }
2910
2911 /*
2912  * Input: a 'big' sector number,
2913  * Output: index of the data and parity disk, and the sector # in them.
2914  */
2915 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2916                               int previous, int *dd_idx,
2917                               struct stripe_head *sh)
2918 {
2919         sector_t stripe, stripe2;
2920         sector_t chunk_number;
2921         unsigned int chunk_offset;
2922         int pd_idx, qd_idx;
2923         int ddf_layout = 0;
2924         sector_t new_sector;
2925         int algorithm = previous ? conf->prev_algo
2926                                  : conf->algorithm;
2927         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2928                                          : conf->chunk_sectors;
2929         int raid_disks = previous ? conf->previous_raid_disks
2930                                   : conf->raid_disks;
2931         int data_disks = raid_disks - conf->max_degraded;
2932
2933         /* First compute the information on this sector */
2934
2935         /*
2936          * Compute the chunk number and the sector offset inside the chunk
2937          */
2938         chunk_offset = sector_div(r_sector, sectors_per_chunk);
2939         chunk_number = r_sector;
2940
2941         /*
2942          * Compute the stripe number
2943          */
2944         stripe = chunk_number;
2945         *dd_idx = sector_div(stripe, data_disks);
2946         stripe2 = stripe;
2947         /*
2948          * Select the parity disk based on the user selected algorithm.
2949          */
2950         pd_idx = qd_idx = -1;
2951         switch(conf->level) {
2952         case 4:
2953                 pd_idx = data_disks;
2954                 break;
2955         case 5:
2956                 switch (algorithm) {
2957                 case ALGORITHM_LEFT_ASYMMETRIC:
2958                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
2959                         if (*dd_idx >= pd_idx)
2960                                 (*dd_idx)++;
2961                         break;
2962                 case ALGORITHM_RIGHT_ASYMMETRIC:
2963                         pd_idx = sector_div(stripe2, raid_disks);
2964                         if (*dd_idx >= pd_idx)
2965                                 (*dd_idx)++;
2966                         break;
2967                 case ALGORITHM_LEFT_SYMMETRIC:
2968                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
2969                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2970                         break;
2971                 case ALGORITHM_RIGHT_SYMMETRIC:
2972                         pd_idx = sector_div(stripe2, raid_disks);
2973                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2974                         break;
2975                 case ALGORITHM_PARITY_0:
2976                         pd_idx = 0;
2977                         (*dd_idx)++;
2978                         break;
2979                 case ALGORITHM_PARITY_N:
2980                         pd_idx = data_disks;
2981                         break;
2982                 default:
2983                         BUG();
2984                 }
2985                 break;
2986         case 6:
2987
2988                 switch (algorithm) {
2989                 case ALGORITHM_LEFT_ASYMMETRIC:
2990                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2991                         qd_idx = pd_idx + 1;
2992                         if (pd_idx == raid_disks-1) {
2993                                 (*dd_idx)++;    /* Q D D D P */
2994                                 qd_idx = 0;
2995                         } else if (*dd_idx >= pd_idx)
2996                                 (*dd_idx) += 2; /* D D P Q D */
2997                         break;
2998                 case ALGORITHM_RIGHT_ASYMMETRIC:
2999                         pd_idx = sector_div(stripe2, raid_disks);
3000                         qd_idx = pd_idx + 1;
3001                         if (pd_idx == raid_disks-1) {
3002                                 (*dd_idx)++;    /* Q D D D P */
3003                                 qd_idx = 0;
3004                         } else if (*dd_idx >= pd_idx)
3005                                 (*dd_idx) += 2; /* D D P Q D */
3006                         break;
3007                 case ALGORITHM_LEFT_SYMMETRIC:
3008                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3009                         qd_idx = (pd_idx + 1) % raid_disks;
3010                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
3011                         break;
3012                 case ALGORITHM_RIGHT_SYMMETRIC:
3013                         pd_idx = sector_div(stripe2, raid_disks);
3014                         qd_idx = (pd_idx + 1) % raid_disks;
3015                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
3016                         break;
3017
3018                 case ALGORITHM_PARITY_0:
3019                         pd_idx = 0;
3020                         qd_idx = 1;
3021                         (*dd_idx) += 2;
3022                         break;
3023                 case ALGORITHM_PARITY_N:
3024                         pd_idx = data_disks;
3025                         qd_idx = data_disks + 1;
3026                         break;
3027
3028                 case ALGORITHM_ROTATING_ZERO_RESTART:
3029                         /* Exactly the same as RIGHT_ASYMMETRIC, but or
3030                          * of blocks for computing Q is different.
3031                          */
3032                         pd_idx = sector_div(stripe2, raid_disks);
3033                         qd_idx = pd_idx + 1;
3034                         if (pd_idx == raid_disks-1) {
3035                                 (*dd_idx)++;    /* Q D D D P */
3036                                 qd_idx = 0;
3037                         } else if (*dd_idx >= pd_idx)
3038                                 (*dd_idx) += 2; /* D D P Q D */
3039                         ddf_layout = 1;
3040                         break;
3041
3042                 case ALGORITHM_ROTATING_N_RESTART:
3043                         /* Same a left_asymmetric, by first stripe is
3044                          * D D D P Q  rather than
3045                          * Q D D D P
3046                          */
3047                         stripe2 += 1;
3048                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3049                         qd_idx = pd_idx + 1;
3050                         if (pd_idx == raid_disks-1) {
3051                                 (*dd_idx)++;    /* Q D D D P */
3052                                 qd_idx = 0;
3053                         } else if (*dd_idx >= pd_idx)
3054                                 (*dd_idx) += 2; /* D D P Q D */
3055                         ddf_layout = 1;
3056                         break;
3057
3058                 case ALGORITHM_ROTATING_N_CONTINUE:
3059                         /* Same as left_symmetric but Q is before P */
3060                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3061                         qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
3062                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
3063                         ddf_layout = 1;
3064                         break;
3065
3066                 case ALGORITHM_LEFT_ASYMMETRIC_6:
3067                         /* RAID5 left_asymmetric, with Q on last device */
3068                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
3069                         if (*dd_idx >= pd_idx)
3070                                 (*dd_idx)++;
3071                         qd_idx = raid_disks - 1;
3072                         break;
3073
3074                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3075                         pd_idx = sector_div(stripe2, raid_disks-1);
3076                         if (*dd_idx >= pd_idx)
3077                                 (*dd_idx)++;
3078                         qd_idx = raid_disks - 1;
3079                         break;
3080
3081                 case ALGORITHM_LEFT_SYMMETRIC_6:
3082                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
3083                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
3084                         qd_idx = raid_disks - 1;
3085                         break;
3086
3087                 case ALGORITHM_RIGHT_SYMMETRIC_6:
3088                         pd_idx = sector_div(stripe2, raid_disks-1);
3089                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
3090                         qd_idx = raid_disks - 1;
3091                         break;
3092
3093                 case ALGORITHM_PARITY_0_6:
3094                         pd_idx = 0;
3095                         (*dd_idx)++;
3096                         qd_idx = raid_disks - 1;
3097                         break;
3098
3099                 default:
3100                         BUG();
3101                 }
3102                 break;
3103         }
3104
3105         if (sh) {
3106                 sh->pd_idx = pd_idx;
3107                 sh->qd_idx = qd_idx;
3108                 sh->ddf_layout = ddf_layout;
3109         }
3110         /*
3111          * Finally, compute the new sector number
3112          */
3113         new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
3114         return new_sector;
3115 }
3116
3117 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
3118 {
3119         struct r5conf *conf = sh->raid_conf;
3120         int raid_disks = sh->disks;
3121         int data_disks = raid_disks - conf->max_degraded;
3122         sector_t new_sector = sh->sector, check;
3123         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
3124                                          : conf->chunk_sectors;
3125         int algorithm = previous ? conf->prev_algo
3126                                  : conf->algorithm;
3127         sector_t stripe;
3128         int chunk_offset;
3129         sector_t chunk_number;
3130         int dummy1, dd_idx = i;
3131         sector_t r_sector;
3132         struct stripe_head sh2;
3133
3134         chunk_offset = sector_div(new_sector, sectors_per_chunk);
3135         stripe = new_sector;
3136
3137         if (i == sh->pd_idx)
3138                 return 0;
3139         switch(conf->level) {
3140         case 4: break;
3141         case 5:
3142                 switch (algorithm) {
3143                 case ALGORITHM_LEFT_ASYMMETRIC:
3144                 case ALGORITHM_RIGHT_ASYMMETRIC:
3145                         if (i > sh->pd_idx)
3146                                 i--;
3147                         break;
3148                 case ALGORITHM_LEFT_SYMMETRIC:
3149                 case ALGORITHM_RIGHT_SYMMETRIC:
3150                         if (i < sh->pd_idx)
3151                                 i += raid_disks;
3152                         i -= (sh->pd_idx + 1);
3153                         break;
3154                 case ALGORITHM_PARITY_0:
3155                         i -= 1;
3156                         break;
3157                 case ALGORITHM_PARITY_N:
3158                         break;
3159                 default:
3160                         BUG();
3161                 }
3162                 break;
3163         case 6:
3164                 if (i == sh->qd_idx)
3165                         return 0; /* It is the Q disk */
3166                 switch (algorithm) {
3167                 case ALGORITHM_LEFT_ASYMMETRIC:
3168                 case ALGORITHM_RIGHT_ASYMMETRIC:
3169                 case ALGORITHM_ROTATING_ZERO_RESTART:
3170                 case ALGORITHM_ROTATING_N_RESTART:
3171                         if (sh->pd_idx == raid_disks-1)
3172                                 i--;    /* Q D D D P */
3173                         else if (i > sh->pd_idx)
3174                                 i -= 2; /* D D P Q D */
3175                         break;
3176                 case ALGORITHM_LEFT_SYMMETRIC:
3177                 case ALGORITHM_RIGHT_SYMMETRIC:
3178                         if (sh->pd_idx == raid_disks-1)
3179                                 i--; /* Q D D D P */
3180                         else {
3181                                 /* D D P Q D */
3182                                 if (i < sh->pd_idx)
3183                                         i += raid_disks;
3184                                 i -= (sh->pd_idx + 2);
3185                         }
3186                         break;
3187                 case ALGORITHM_PARITY_0:
3188                         i -= 2;
3189                         break;
3190                 case ALGORITHM_PARITY_N:
3191                         break;
3192                 case ALGORITHM_ROTATING_N_CONTINUE:
3193                         /* Like left_symmetric, but P is before Q */
3194                         if (sh->pd_idx == 0)
3195                                 i--;    /* P D D D Q */
3196                         else {
3197                                 /* D D Q P D */
3198                                 if (i < sh->pd_idx)
3199                                         i += raid_disks;
3200                                 i -= (sh->pd_idx + 1);
3201                         }
3202                         break;
3203                 case ALGORITHM_LEFT_ASYMMETRIC_6:
3204                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3205                         if (i > sh->pd_idx)
3206                                 i--;
3207                         break;
3208                 case ALGORITHM_LEFT_SYMMETRIC_6:
3209                 case ALGORITHM_RIGHT_SYMMETRIC_6:
3210                         if (i < sh->pd_idx)
3211                                 i += data_disks + 1;
3212                         i -= (sh->pd_idx + 1);
3213                         break;
3214                 case ALGORITHM_PARITY_0_6:
3215                         i -= 1;
3216                         break;
3217                 default:
3218                         BUG();
3219                 }
3220                 break;
3221         }
3222
3223         chunk_number = stripe * data_disks + i;
3224         r_sector = chunk_number * sectors_per_chunk + chunk_offset;
3225
3226         check = raid5_compute_sector(conf, r_sector,
3227                                      previous, &dummy1, &sh2);
3228         if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
3229                 || sh2.qd_idx != sh->qd_idx) {
3230                 pr_warn("md/raid:%s: compute_blocknr: map not correct\n",
3231                         mdname(conf->mddev));
3232                 return 0;
3233         }
3234         return r_sector;
3235 }
3236
3237 /*
3238  * There are cases where we want handle_stripe_dirtying() and
3239  * schedule_reconstruction() to delay towrite to some dev of a stripe.
3240  *
3241  * This function checks whether we want to delay the towrite. Specifically,
3242  * we delay the towrite when:
3243  *
3244  *   1. degraded stripe has a non-overwrite to the missing dev, AND this
3245  *      stripe has data in journal (for other devices).
3246  *
3247  *      In this case, when reading data for the non-overwrite dev, it is
3248  *      necessary to handle complex rmw of write back cache (prexor with
3249  *      orig_page, and xor with page). To keep read path simple, we would
3250  *      like to flush data in journal to RAID disks first, so complex rmw
3251  *      is handled in the write patch (handle_stripe_dirtying).
3252  *
3253  *   2. when journal space is critical (R5C_LOG_CRITICAL=1)
3254  *
3255  *      It is important to be able to flush all stripes in raid5-cache.
3256  *      Therefore, we need reserve some space on the journal device for
3257  *      these flushes. If flush operation includes pending writes to the
3258  *      stripe, we need to reserve (conf->raid_disk + 1) pages per stripe
3259  *      for the flush out. If we exclude these pending writes from flush
3260  *      operation, we only need (conf->max_degraded + 1) pages per stripe.
3261  *      Therefore, excluding pending writes in these cases enables more
3262  *      efficient use of the journal device.
3263  *
3264  *      Note: To make sure the stripe makes progress, we only delay
3265  *      towrite for stripes with data already in journal (injournal > 0).
3266  *      When LOG_CRITICAL, stripes with injournal == 0 will be sent to
3267  *      no_space_stripes list.
3268  *
3269  *   3. during journal failure
3270  *      In journal failure, we try to flush all cached data to raid disks
3271  *      based on data in stripe cache. The array is read-only to upper
3272  *      layers, so we would skip all pending writes.
3273  *
3274  */
3275 static inline bool delay_towrite(struct r5conf *conf,
3276                                  struct r5dev *dev,
3277                                  struct stripe_head_state *s)
3278 {
3279         /* case 1 above */
3280         if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3281             !test_bit(R5_Insync, &dev->flags) && s->injournal)
3282                 return true;
3283         /* case 2 above */
3284         if (test_bit(R5C_LOG_CRITICAL, &conf->cache_state) &&
3285             s->injournal > 0)
3286                 return true;
3287         /* case 3 above */
3288         if (s->log_failed && s->injournal)
3289                 return true;
3290         return false;
3291 }
3292
3293 static void
3294 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
3295                          int rcw, int expand)
3296 {
3297         int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
3298         struct r5conf *conf = sh->raid_conf;
3299         int level = conf->level;
3300
3301         if (rcw) {
3302                 /*
3303                  * In some cases, handle_stripe_dirtying initially decided to
3304                  * run rmw and allocates extra page for prexor. However, rcw is
3305                  * cheaper later on. We need to free the extra page now,
3306                  * because we won't be able to do that in ops_complete_prexor().
3307                  */
3308                 r5c_release_extra_page(sh);
3309
3310                 for (i = disks; i--; ) {
3311                         struct r5dev *dev = &sh->dev[i];
3312
3313                         if (dev->towrite && !delay_towrite(conf, dev, s)) {
3314                                 set_bit(R5_LOCKED, &dev->flags);
3315                                 set_bit(R5_Wantdrain, &dev->flags);
3316                                 if (!expand)
3317                                         clear_bit(R5_UPTODATE, &dev->flags);
3318                                 s->locked++;
3319                         } else if (test_bit(R5_InJournal, &dev->flags)) {
3320                                 set_bit(R5_LOCKED, &dev->flags);
3321                                 s->locked++;
3322                         }
3323                 }
3324                 /* if we are not expanding this is a proper write request, and
3325                  * there will be bios with new data to be drained into the
3326                  * stripe cache
3327                  */
3328                 if (!expand) {
3329                         if (!s->locked)
3330                                 /* False alarm, nothing to do */
3331                                 return;
3332                         sh->reconstruct_state = reconstruct_state_drain_run;
3333                         set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3334                 } else
3335                         sh->reconstruct_state = reconstruct_state_run;
3336
3337                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3338
3339                 if (s->locked + conf->max_degraded == disks)
3340                         if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
3341                                 atomic_inc(&conf->pending_full_writes);
3342         } else {
3343                 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
3344                         test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
3345                 BUG_ON(level == 6 &&
3346                         (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
3347                            test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
3348
3349                 for (i = disks; i--; ) {
3350                         struct r5dev *dev = &sh->dev[i];
3351                         if (i == pd_idx || i == qd_idx)
3352                                 continue;
3353
3354                         if (dev->towrite &&
3355                             (test_bit(R5_UPTODATE, &dev->flags) ||
3356                              test_bit(R5_Wantcompute, &dev->flags))) {
3357                                 set_bit(R5_Wantdrain, &dev->flags);
3358                                 set_bit(R5_LOCKED, &dev->flags);
3359                                 clear_bit(R5_UPTODATE, &dev->flags);
3360                                 s->locked++;
3361                         } else if (test_bit(R5_InJournal, &dev->flags)) {
3362                                 set_bit(R5_LOCKED, &dev->flags);
3363                                 s->locked++;
3364                         }
3365                 }
3366                 if (!s->locked)
3367                         /* False alarm - nothing to do */
3368                         return;
3369                 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
3370                 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
3371                 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3372                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3373         }
3374
3375         /* keep the parity disk(s) locked while asynchronous operations
3376          * are in flight
3377          */
3378         set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
3379         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3380         s->locked++;
3381
3382         if (level == 6) {
3383                 int qd_idx = sh->qd_idx;
3384                 struct r5dev *dev = &sh->dev[qd_idx];
3385
3386                 set_bit(R5_LOCKED, &dev->flags);
3387                 clear_bit(R5_UPTODATE, &dev->flags);
3388                 s->locked++;
3389         }
3390
3391         if (raid5_has_ppl(sh->raid_conf) && sh->ppl_page &&
3392             test_bit(STRIPE_OP_BIODRAIN, &s->ops_request) &&
3393             !test_bit(STRIPE_FULL_WRITE, &sh->state) &&
3394             test_bit(R5_Insync, &sh->dev[pd_idx].flags))
3395                 set_bit(STRIPE_OP_PARTIAL_PARITY, &s->ops_request);
3396
3397         pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
3398                 __func__, (unsigned long long)sh->sector,
3399                 s->locked, s->ops_request);
3400 }
3401
3402 /*
3403  * Each stripe/dev can have one or more bion attached.
3404  * toread/towrite point to the first in a chain.
3405  * The bi_next chain must be in order.
3406  */
3407 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
3408                           int forwrite, int previous)
3409 {
3410         struct bio **bip;
3411         struct r5conf *conf = sh->raid_conf;
3412         int firstwrite=0;
3413
3414         pr_debug("adding bi b#%llu to stripe s#%llu\n",
3415                 (unsigned long long)bi->bi_iter.bi_sector,
3416                 (unsigned long long)sh->sector);
3417
3418         spin_lock_irq(&sh->stripe_lock);
3419         sh->dev[dd_idx].write_hint = bi->bi_write_hint;
3420         /* Don't allow new IO added to stripes in batch list */
3421         if (sh->batch_head)
3422                 goto overlap;
3423         if (forwrite) {
3424                 bip = &sh->dev[dd_idx].towrite;
3425                 if (*bip == NULL)
3426                         firstwrite = 1;
3427         } else
3428                 bip = &sh->dev[dd_idx].toread;
3429         while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
3430                 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
3431                         goto overlap;
3432                 bip = & (*bip)->bi_next;
3433         }
3434         if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
3435                 goto overlap;
3436
3437         if (forwrite && raid5_has_ppl(conf)) {
3438                 /*
3439                  * With PPL only writes to consecutive data chunks within a
3440                  * stripe are allowed because for a single stripe_head we can
3441                  * only have one PPL entry at a time, which describes one data
3442                  * range. Not really an overlap, but wait_for_overlap can be
3443                  * used to handle this.
3444                  */
3445                 sector_t sector;
3446                 sector_t first = 0;
3447                 sector_t last = 0;
3448                 int count = 0;
3449                 int i;
3450
3451                 for (i = 0; i < sh->disks; i++) {
3452                         if (i != sh->pd_idx &&
3453                             (i == dd_idx || sh->dev[i].towrite)) {
3454                                 sector = sh->dev[i].sector;
3455                                 if (count == 0 || sector < first)
3456                                         first = sector;
3457                                 if (sector > last)
3458                                         last = sector;
3459                                 count++;
3460                         }
3461                 }
3462
3463                 if (first + conf->chunk_sectors * (count - 1) != last)
3464                         goto overlap;
3465         }
3466
3467         if (!forwrite || previous)
3468                 clear_bit(STRIPE_BATCH_READY, &sh->state);
3469
3470         BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3471         if (*bip)
3472                 bi->bi_next = *bip;
3473         *bip = bi;
3474         bio_inc_remaining(bi);
3475         md_write_inc(conf->mddev, bi);
3476
3477         if (forwrite) {
3478                 /* check if page is covered */
3479                 sector_t sector = sh->dev[dd_idx].sector;
3480                 for (bi=sh->dev[dd_idx].towrite;
3481                      sector < sh->dev[dd_idx].sector + RAID5_STRIPE_SECTORS(conf) &&
3482                              bi && bi->bi_iter.bi_sector <= sector;
3483                      bi = r5_next_bio(conf, bi, sh->dev[dd_idx].sector)) {
3484                         if (bio_end_sector(bi) >= sector)
3485                                 sector = bio_end_sector(bi);
3486                 }
3487                 if (sector >= sh->dev[dd_idx].sector + RAID5_STRIPE_SECTORS(conf))
3488                         if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3489                                 sh->overwrite_disks++;
3490         }
3491
3492         pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3493                 (unsigned long long)(*bip)->bi_iter.bi_sector,
3494                 (unsigned long long)sh->sector, dd_idx);
3495
3496         if (conf->mddev->bitmap && firstwrite) {
3497                 /* Cannot hold spinlock over bitmap_startwrite,
3498                  * but must ensure this isn't added to a batch until
3499                  * we have added to the bitmap and set bm_seq.
3500                  * So set STRIPE_BITMAP_PENDING to prevent
3501                  * batching.
3502                  * If multiple add_stripe_bio() calls race here they
3503                  * much all set STRIPE_BITMAP_PENDING.  So only the first one
3504                  * to complete "bitmap_startwrite" gets to set
3505                  * STRIPE_BIT_DELAY.  This is important as once a stripe
3506                  * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3507                  * any more.
3508                  */
3509                 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3510                 spin_unlock_irq(&sh->stripe_lock);
3511                 md_bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3512                                      RAID5_STRIPE_SECTORS(conf), 0);
3513                 spin_lock_irq(&sh->stripe_lock);
3514                 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3515                 if (!sh->batch_head) {
3516                         sh->bm_seq = conf->seq_flush+1;
3517                         set_bit(STRIPE_BIT_DELAY, &sh->state);
3518                 }
3519         }
3520         spin_unlock_irq(&sh->stripe_lock);
3521
3522         if (stripe_can_batch(sh))
3523                 stripe_add_to_batch_list(conf, sh);
3524         return 1;
3525
3526  overlap:
3527         set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3528         spin_unlock_irq(&sh->stripe_lock);
3529         return 0;
3530 }
3531
3532 static void end_reshape(struct r5conf *conf);
3533
3534 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3535                             struct stripe_head *sh)
3536 {
3537         int sectors_per_chunk =
3538                 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3539         int dd_idx;
3540         int chunk_offset = sector_div(stripe, sectors_per_chunk);
3541         int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3542
3543         raid5_compute_sector(conf,
3544                              stripe * (disks - conf->max_degraded)
3545                              *sectors_per_chunk + chunk_offset,
3546                              previous,
3547                              &dd_idx, sh);
3548 }
3549
3550 static void
3551 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3552                      struct stripe_head_state *s, int disks)
3553 {
3554         int i;
3555         BUG_ON(sh->batch_head);
3556         for (i = disks; i--; ) {
3557                 struct bio *bi;
3558                 int bitmap_end = 0;
3559
3560                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3561                         struct md_rdev *rdev;
3562                         rcu_read_lock();
3563                         rdev = rcu_dereference(conf->disks[i].rdev);
3564                         if (rdev && test_bit(In_sync, &rdev->flags) &&
3565                             !test_bit(Faulty, &rdev->flags))
3566                                 atomic_inc(&rdev->nr_pending);
3567                         else
3568                                 rdev = NULL;
3569                         rcu_read_unlock();
3570                         if (rdev) {
3571                                 if (!rdev_set_badblocks(
3572                                             rdev,
3573                                             sh->sector,
3574                                             RAID5_STRIPE_SECTORS(conf), 0))
3575                                         md_error(conf->mddev, rdev);
3576                                 rdev_dec_pending(rdev, conf->mddev);
3577                         }
3578                 }
3579                 spin_lock_irq(&sh->stripe_lock);
3580                 /* fail all writes first */
3581                 bi = sh->dev[i].towrite;
3582                 sh->dev[i].towrite = NULL;
3583                 sh->overwrite_disks = 0;
3584                 spin_unlock_irq(&sh->stripe_lock);
3585                 if (bi)
3586                         bitmap_end = 1;
3587
3588                 log_stripe_write_finished(sh);
3589
3590                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3591                         wake_up(&conf->wait_for_overlap);
3592
3593                 while (bi && bi->bi_iter.bi_sector <
3594                         sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3595                         struct bio *nextbi = r5_next_bio(conf, bi, sh->dev[i].sector);
3596
3597                         md_write_end(conf->mddev);
3598                         bio_io_error(bi);
3599                         bi = nextbi;
3600                 }
3601                 if (bitmap_end)
3602                         md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3603                                            RAID5_STRIPE_SECTORS(conf), 0, 0);
3604                 bitmap_end = 0;
3605                 /* and fail all 'written' */
3606                 bi = sh->dev[i].written;
3607                 sh->dev[i].written = NULL;
3608                 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3609                         WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3610                         sh->dev[i].page = sh->dev[i].orig_page;
3611                 }
3612
3613                 if (bi) bitmap_end = 1;
3614                 while (bi && bi->bi_iter.bi_sector <
3615                        sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3616                         struct bio *bi2 = r5_next_bio(conf, bi, sh->dev[i].sector);
3617
3618                         md_write_end(conf->mddev);
3619                         bio_io_error(bi);
3620                         bi = bi2;
3621                 }
3622
3623                 /* fail any reads if this device is non-operational and
3624                  * the data has not reached the cache yet.
3625                  */
3626                 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3627                     s->failed > conf->max_degraded &&
3628                     (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3629                       test_bit(R5_ReadError, &sh->dev[i].flags))) {
3630                         spin_lock_irq(&sh->stripe_lock);
3631                         bi = sh->dev[i].toread;
3632                         sh->dev[i].toread = NULL;
3633                         spin_unlock_irq(&sh->stripe_lock);
3634                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3635                                 wake_up(&conf->wait_for_overlap);
3636                         if (bi)
3637                                 s->to_read--;
3638                         while (bi && bi->bi_iter.bi_sector <
3639                                sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3640                                 struct bio *nextbi =
3641                                         r5_next_bio(conf, bi, sh->dev[i].sector);
3642
3643                                 bio_io_error(bi);
3644                                 bi = nextbi;
3645                         }
3646                 }
3647                 if (bitmap_end)
3648                         md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3649                                            RAID5_STRIPE_SECTORS(conf), 0, 0);
3650                 /* If we were in the middle of a write the parity block might
3651                  * still be locked - so just clear all R5_LOCKED flags
3652                  */
3653                 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3654         }
3655         s->to_write = 0;
3656         s->written = 0;
3657
3658         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3659                 if (atomic_dec_and_test(&conf->pending_full_writes))
3660                         md_wakeup_thread(conf->mddev->thread);
3661 }
3662
3663 static void
3664 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3665                    struct stripe_head_state *s)
3666 {
3667         int abort = 0;
3668         int i;
3669
3670         BUG_ON(sh->batch_head);
3671         clear_bit(STRIPE_SYNCING, &sh->state);
3672         if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3673                 wake_up(&conf->wait_for_overlap);
3674         s->syncing = 0;
3675         s->replacing = 0;
3676         /* There is nothing more to do for sync/check/repair.
3677          * Don't even need to abort as that is handled elsewhere
3678          * if needed, and not always wanted e.g. if there is a known
3679          * bad block here.
3680          * For recover/replace we need to record a bad block on all
3681          * non-sync devices, or abort the recovery
3682          */
3683         if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3684                 /* During recovery devices cannot be removed, so
3685                  * locking and refcounting of rdevs is not needed
3686                  */
3687                 rcu_read_lock();
3688                 for (i = 0; i < conf->raid_disks; i++) {
3689                         struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
3690                         if (rdev
3691                             && !test_bit(Faulty, &rdev->flags)
3692                             && !test_bit(In_sync, &rdev->flags)
3693                             && !rdev_set_badblocks(rdev, sh->sector,
3694                                                    RAID5_STRIPE_SECTORS(conf), 0))
3695                                 abort = 1;
3696                         rdev = rcu_dereference(conf->disks[i].replacement);
3697                         if (rdev
3698                             && !test_bit(Faulty, &rdev->flags)
3699                             && !test_bit(In_sync, &rdev->flags)
3700                             && !rdev_set_badblocks(rdev, sh->sector,
3701                                                    RAID5_STRIPE_SECTORS(conf), 0))
3702                                 abort = 1;
3703                 }
3704                 rcu_read_unlock();
3705                 if (abort)
3706                         conf->recovery_disabled =
3707                                 conf->mddev->recovery_disabled;
3708         }
3709         md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), !abort);
3710 }
3711
3712 static int want_replace(struct stripe_head *sh, int disk_idx)
3713 {
3714         struct md_rdev *rdev;
3715         int rv = 0;
3716
3717         rcu_read_lock();
3718         rdev = rcu_dereference(sh->raid_conf->disks[disk_idx].replacement);
3719         if (rdev
3720             && !test_bit(Faulty, &rdev->flags)
3721             && !test_bit(In_sync, &rdev->flags)
3722             && (rdev->recovery_offset <= sh->sector
3723                 || rdev->mddev->recovery_cp <= sh->sector))
3724                 rv = 1;
3725         rcu_read_unlock();
3726         return rv;
3727 }
3728
3729 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3730                            int disk_idx, int disks)
3731 {
3732         struct r5dev *dev = &sh->dev[disk_idx];
3733         struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3734                                   &sh->dev[s->failed_num[1]] };
3735         int i;
3736         bool force_rcw = (sh->raid_conf->rmw_level == PARITY_DISABLE_RMW);
3737
3738
3739         if (test_bit(R5_LOCKED, &dev->flags) ||
3740             test_bit(R5_UPTODATE, &dev->flags))
3741                 /* No point reading this as we already have it or have
3742                  * decided to get it.
3743                  */
3744                 return 0;
3745
3746         if (dev->toread ||
3747             (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3748                 /* We need this block to directly satisfy a request */
3749                 return 1;
3750
3751         if (s->syncing || s->expanding ||
3752             (s->replacing && want_replace(sh, disk_idx)))
3753                 /* When syncing, or expanding we read everything.
3754                  * When replacing, we need the replaced block.
3755                  */
3756                 return 1;
3757
3758         if ((s->failed >= 1 && fdev[0]->toread) ||
3759             (s->failed >= 2 && fdev[1]->toread))
3760                 /* If we want to read from a failed device, then
3761                  * we need to actually read every other device.
3762                  */
3763                 return 1;
3764
3765         /* Sometimes neither read-modify-write nor reconstruct-write
3766          * cycles can work.  In those cases we read every block we
3767          * can.  Then the parity-update is certain to have enough to
3768          * work with.
3769          * This can only be a problem when we need to write something,
3770          * and some device has failed.  If either of those tests
3771          * fail we need look no further.
3772          */
3773         if (!s->failed || !s->to_write)
3774                 return 0;
3775
3776         if (test_bit(R5_Insync, &dev->flags) &&
3777             !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3778                 /* Pre-reads at not permitted until after short delay
3779                  * to gather multiple requests.  However if this
3780                  * device is no Insync, the block could only be computed
3781                  * and there is no need to delay that.
3782                  */
3783                 return 0;
3784
3785         for (i = 0; i < s->failed && i < 2; i++) {
3786                 if (fdev[i]->towrite &&
3787                     !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3788                     !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3789                         /* If we have a partial write to a failed
3790                          * device, then we will need to reconstruct
3791                          * the content of that device, so all other
3792                          * devices must be read.
3793                          */
3794                         return 1;
3795
3796                 if (s->failed >= 2 &&
3797                     (fdev[i]->towrite ||
3798                      s->failed_num[i] == sh->pd_idx ||
3799                      s->failed_num[i] == sh->qd_idx) &&
3800                     !test_bit(R5_UPTODATE, &fdev[i]->flags))
3801                         /* In max degraded raid6, If the failed disk is P, Q,
3802                          * or we want to read the failed disk, we need to do
3803                          * reconstruct-write.
3804                          */
3805                         force_rcw = true;
3806         }
3807
3808         /* If we are forced to do a reconstruct-write, because parity
3809          * cannot be trusted and we are currently recovering it, there
3810          * is extra need to be careful.
3811          * If one of the devices that we would need to read, because
3812          * it is not being overwritten (and maybe not written at all)
3813          * is missing/faulty, then we need to read everything we can.
3814          */
3815         if (!force_rcw &&
3816             sh->sector < sh->raid_conf->mddev->recovery_cp)
3817                 /* reconstruct-write isn't being forced */
3818                 return 0;
3819         for (i = 0; i < s->failed && i < 2; i++) {
3820                 if (s->failed_num[i] != sh->pd_idx &&
3821                     s->failed_num[i] != sh->qd_idx &&
3822                     !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3823                     !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3824                         return 1;
3825         }
3826
3827         return 0;
3828 }
3829
3830 /* fetch_block - checks the given member device to see if its data needs
3831  * to be read or computed to satisfy a request.
3832  *
3833  * Returns 1 when no more member devices need to be checked, otherwise returns
3834  * 0 to tell the loop in handle_stripe_fill to continue
3835  */
3836 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3837                        int disk_idx, int disks)
3838 {
3839         struct r5dev *dev = &sh->dev[disk_idx];
3840
3841         /* is the data in this block needed, and can we get it? */
3842         if (need_this_block(sh, s, disk_idx, disks)) {
3843                 /* we would like to get this block, possibly by computing it,
3844                  * otherwise read it if the backing disk is insync
3845                  */
3846                 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3847                 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3848                 BUG_ON(sh->batch_head);
3849
3850                 /*
3851                  * In the raid6 case if the only non-uptodate disk is P
3852                  * then we already trusted P to compute the other failed
3853                  * drives. It is safe to compute rather than re-read P.
3854                  * In other cases we only compute blocks from failed
3855                  * devices, otherwise check/repair might fail to detect
3856                  * a real inconsistency.
3857                  */
3858
3859                 if ((s->uptodate == disks - 1) &&
3860                     ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3861                     (s->failed && (disk_idx == s->failed_num[0] ||
3862                                    disk_idx == s->failed_num[1])))) {
3863                         /* have disk failed, and we're requested to fetch it;
3864                          * do compute it
3865                          */
3866                         pr_debug("Computing stripe %llu block %d\n",
3867                                (unsigned long long)sh->sector, disk_idx);
3868                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3869                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3870                         set_bit(R5_Wantcompute, &dev->flags);
3871                         sh->ops.target = disk_idx;
3872                         sh->ops.target2 = -1; /* no 2nd target */
3873                         s->req_compute = 1;
3874                         /* Careful: from this point on 'uptodate' is in the eye
3875                          * of raid_run_ops which services 'compute' operations
3876                          * before writes. R5_Wantcompute flags a block that will
3877                          * be R5_UPTODATE by the time it is needed for a
3878                          * subsequent operation.
3879                          */
3880                         s->uptodate++;
3881                         return 1;
3882                 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3883                         /* Computing 2-failure is *very* expensive; only
3884                          * do it if failed >= 2
3885                          */
3886                         int other;
3887                         for (other = disks; other--; ) {
3888                                 if (other == disk_idx)
3889                                         continue;
3890                                 if (!test_bit(R5_UPTODATE,
3891                                       &sh->dev[other].flags))
3892                                         break;
3893                         }
3894                         BUG_ON(other < 0);
3895                         pr_debug("Computing stripe %llu blocks %d,%d\n",
3896                                (unsigned long long)sh->sector,
3897                                disk_idx, other);
3898                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3899                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3900                         set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3901                         set_bit(R5_Wantcompute, &sh->dev[other].flags);
3902                         sh->ops.target = disk_idx;
3903                         sh->ops.target2 = other;
3904                         s->uptodate += 2;
3905                         s->req_compute = 1;
3906                         return 1;
3907                 } else if (test_bit(R5_Insync, &dev->flags)) {
3908                         set_bit(R5_LOCKED, &dev->flags);
3909                         set_bit(R5_Wantread, &dev->flags);
3910                         s->locked++;
3911                         pr_debug("Reading block %d (sync=%d)\n",
3912                                 disk_idx, s->syncing);
3913                 }
3914         }
3915
3916         return 0;
3917 }
3918
3919 /*
3920  * handle_stripe_fill - read or compute data to satisfy pending requests.
3921  */
3922 static void handle_stripe_fill(struct stripe_head *sh,
3923                                struct stripe_head_state *s,
3924                                int disks)
3925 {
3926         int i;
3927
3928         /* look for blocks to read/compute, skip this if a compute
3929          * is already in flight, or if the stripe contents are in the
3930          * midst of changing due to a write
3931          */
3932         if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3933             !sh->reconstruct_state) {
3934
3935                 /*
3936                  * For degraded stripe with data in journal, do not handle
3937                  * read requests yet, instead, flush the stripe to raid
3938                  * disks first, this avoids handling complex rmw of write
3939                  * back cache (prexor with orig_page, and then xor with
3940                  * page) in the read path
3941                  */
3942                 if (s->to_read && s->injournal && s->failed) {
3943                         if (test_bit(STRIPE_R5C_CACHING, &sh->state))
3944                                 r5c_make_stripe_write_out(sh);
3945                         goto out;
3946                 }
3947
3948                 for (i = disks; i--; )
3949                         if (fetch_block(sh, s, i, disks))
3950                                 break;
3951         }
3952 out:
3953         set_bit(STRIPE_HANDLE, &sh->state);
3954 }
3955
3956 static void break_stripe_batch_list(struct stripe_head *head_sh,
3957                                     unsigned long handle_flags);
3958 /* handle_stripe_clean_event
3959  * any written block on an uptodate or failed drive can be returned.
3960  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3961  * never LOCKED, so we don't need to test 'failed' directly.
3962  */
3963 static void handle_stripe_clean_event(struct r5conf *conf,
3964         struct stripe_head *sh, int disks)
3965 {
3966         int i;
3967         struct r5dev *dev;
3968         int discard_pending = 0;
3969         struct stripe_head *head_sh = sh;
3970         bool do_endio = false;
3971
3972         for (i = disks; i--; )
3973                 if (sh->dev[i].written) {
3974                         dev = &sh->dev[i];
3975                         if (!test_bit(R5_LOCKED, &dev->flags) &&
3976                             (test_bit(R5_UPTODATE, &dev->flags) ||
3977                              test_bit(R5_Discard, &dev->flags) ||
3978                              test_bit(R5_SkipCopy, &dev->flags))) {
3979                                 /* We can return any write requests */
3980                                 struct bio *wbi, *wbi2;
3981                                 pr_debug("Return write for disc %d\n", i);
3982                                 if (test_and_clear_bit(R5_Discard, &dev->flags))
3983                                         clear_bit(R5_UPTODATE, &dev->flags);
3984                                 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3985                                         WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3986                                 }
3987                                 do_endio = true;
3988
3989 returnbi:
3990                                 dev->page = dev->orig_page;
3991                                 wbi = dev->written;
3992                                 dev->written = NULL;
3993                                 while (wbi && wbi->bi_iter.bi_sector <
3994                                         dev->sector + RAID5_STRIPE_SECTORS(conf)) {
3995                                         wbi2 = r5_next_bio(conf, wbi, dev->sector);
3996                                         md_write_end(conf->mddev);
3997                                         bio_endio(wbi);
3998                                         wbi = wbi2;
3999                                 }
4000                                 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
4001                                                    RAID5_STRIPE_SECTORS(conf),
4002                                                    !test_bit(STRIPE_DEGRADED, &sh->state),
4003                                                    0);
4004                                 if (head_sh->batch_head) {
4005                                         sh = list_first_entry(&sh->batch_list,
4006                                                               struct stripe_head,
4007                                                               batch_list);
4008                                         if (sh != head_sh) {
4009                                                 dev = &sh->dev[i];
4010                                                 goto returnbi;
4011                                         }
4012                                 }
4013                                 sh = head_sh;
4014                                 dev = &sh->dev[i];
4015                         } else if (test_bit(R5_Discard, &dev->flags))
4016                                 discard_pending = 1;
4017                 }
4018
4019         log_stripe_write_finished(sh);
4020
4021         if (!discard_pending &&
4022             test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
4023                 int hash;
4024                 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
4025                 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4026                 if (sh->qd_idx >= 0) {
4027                         clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
4028                         clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
4029                 }
4030                 /* now that discard is done we can proceed with any sync */
4031                 clear_bit(STRIPE_DISCARD, &sh->state);
4032                 /*
4033                  * SCSI discard will change some bio fields and the stripe has
4034                  * no updated data, so remove it from hash list and the stripe
4035                  * will be reinitialized
4036                  */
4037 unhash:
4038                 hash = sh->hash_lock_index;
4039                 spin_lock_irq(conf->hash_locks + hash);
4040                 remove_hash(sh);
4041                 spin_unlock_irq(conf->hash_locks + hash);
4042                 if (head_sh->batch_head) {
4043                         sh = list_first_entry(&sh->batch_list,
4044                                               struct stripe_head, batch_list);
4045                         if (sh != head_sh)
4046                                         goto unhash;
4047                 }
4048                 sh = head_sh;
4049
4050                 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
4051                         set_bit(STRIPE_HANDLE, &sh->state);
4052
4053         }
4054
4055         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
4056                 if (atomic_dec_and_test(&conf->pending_full_writes))
4057                         md_wakeup_thread(conf->mddev->thread);
4058
4059         if (head_sh->batch_head && do_endio)
4060                 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
4061 }
4062
4063 /*
4064  * For RMW in write back cache, we need extra page in prexor to store the
4065  * old data. This page is stored in dev->orig_page.
4066  *
4067  * This function checks whether we have data for prexor. The exact logic
4068  * is:
4069  *       R5_UPTODATE && (!R5_InJournal || R5_OrigPageUPTDODATE)
4070  */
4071 static inline bool uptodate_for_rmw(struct r5dev *dev)
4072 {
4073         return (test_bit(R5_UPTODATE, &dev->flags)) &&
4074                 (!test_bit(R5_InJournal, &dev->flags) ||
4075                  test_bit(R5_OrigPageUPTDODATE, &dev->flags));
4076 }
4077
4078 static int handle_stripe_dirtying(struct r5conf *conf,
4079                                   struct stripe_head *sh,
4080                                   struct stripe_head_state *s,
4081                                   int disks)
4082 {
4083         int rmw = 0, rcw = 0, i;
4084         sector_t recovery_cp = conf->mddev->recovery_cp;
4085
4086         /* Check whether resync is now happening or should start.
4087          * If yes, then the array is dirty (after unclean shutdown or
4088          * initial creation), so parity in some stripes might be inconsistent.
4089          * In this case, we need to always do reconstruct-write, to ensure
4090          * that in case of drive failure or read-error correction, we
4091          * generate correct data from the parity.
4092          */
4093         if (conf->rmw_level == PARITY_DISABLE_RMW ||
4094             (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
4095              s->failed == 0)) {
4096                 /* Calculate the real rcw later - for now make it
4097                  * look like rcw is cheaper
4098                  */
4099                 rcw = 1; rmw = 2;
4100                 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
4101                          conf->rmw_level, (unsigned long long)recovery_cp,
4102                          (unsigned long long)sh->sector);
4103         } else for (i = disks; i--; ) {
4104                 /* would I have to read this buffer for read_modify_write */
4105                 struct r5dev *dev = &sh->dev[i];
4106                 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
4107                      i == sh->pd_idx || i == sh->qd_idx ||
4108                      test_bit(R5_InJournal, &dev->flags)) &&
4109                     !test_bit(R5_LOCKED, &dev->flags) &&
4110                     !(uptodate_for_rmw(dev) ||
4111                       test_bit(R5_Wantcompute, &dev->flags))) {
4112                         if (test_bit(R5_Insync, &dev->flags))
4113                                 rmw++;
4114                         else
4115                                 rmw += 2*disks;  /* cannot read it */
4116                 }
4117                 /* Would I have to read this buffer for reconstruct_write */
4118                 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
4119                     i != sh->pd_idx && i != sh->qd_idx &&
4120                     !test_bit(R5_LOCKED, &dev->flags) &&
4121                     !(test_bit(R5_UPTODATE, &dev->flags) ||
4122                       test_bit(R5_Wantcompute, &dev->flags))) {
4123                         if (test_bit(R5_Insync, &dev->flags))
4124                                 rcw++;
4125                         else
4126                                 rcw += 2*disks;
4127                 }
4128         }
4129
4130         pr_debug("for sector %llu state 0x%lx, rmw=%d rcw=%d\n",
4131                  (unsigned long long)sh->sector, sh->state, rmw, rcw);
4132         set_bit(STRIPE_HANDLE, &sh->state);
4133         if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_PREFER_RMW)) && rmw > 0) {
4134                 /* prefer read-modify-write, but need to get some data */
4135                 if (conf->mddev->queue)
4136                         blk_add_trace_msg(conf->mddev->queue,
4137                                           "raid5 rmw %llu %d",
4138                                           (unsigned long long)sh->sector, rmw);
4139                 for (i = disks; i--; ) {
4140                         struct r5dev *dev = &sh->dev[i];
4141                         if (test_bit(R5_InJournal, &dev->flags) &&
4142                             dev->page == dev->orig_page &&
4143                             !test_bit(R5_LOCKED, &sh->dev[sh->pd_idx].flags)) {
4144                                 /* alloc page for prexor */
4145                                 struct page *p = alloc_page(GFP_NOIO);
4146
4147                                 if (p) {
4148                                         dev->orig_page = p;
4149                                         continue;
4150                                 }
4151
4152                                 /*
4153                                  * alloc_page() failed, try use
4154                                  * disk_info->extra_page
4155                                  */
4156                                 if (!test_and_set_bit(R5C_EXTRA_PAGE_IN_USE,
4157                                                       &conf->cache_state)) {
4158                                         r5c_use_extra_page(sh);
4159                                         break;
4160                                 }
4161
4162                                 /* extra_page in use, add to delayed_list */
4163                                 set_bit(STRIPE_DELAYED, &sh->state);
4164                                 s->waiting_extra_page = 1;
4165                                 return -EAGAIN;
4166                         }
4167                 }
4168
4169                 for (i = disks; i--; ) {
4170                         struct r5dev *dev = &sh->dev[i];
4171                         if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
4172                              i == sh->pd_idx || i == sh->qd_idx ||
4173                              test_bit(R5_InJournal, &dev->flags)) &&
4174                             !test_bit(R5_LOCKED, &dev->flags) &&
4175                             !(uptodate_for_rmw(dev) ||
4176                               test_bit(R5_Wantcompute, &dev->flags)) &&
4177                             test_bit(R5_Insync, &dev->flags)) {
4178                                 if (test_bit(STRIPE_PREREAD_ACTIVE,
4179                                              &sh->state)) {
4180                                         pr_debug("Read_old block %d for r-m-w\n",
4181                                                  i);
4182                                         set_bit(R5_LOCKED, &dev->flags);
4183                                         set_bit(R5_Wantread, &dev->flags);
4184                                         s->locked++;
4185                                 } else
4186                                         set_bit(STRIPE_DELAYED, &sh->state);
4187                         }
4188                 }
4189         }
4190         if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_PREFER_RMW)) && rcw > 0) {
4191                 /* want reconstruct write, but need to get some data */
4192                 int qread =0;
4193                 rcw = 0;
4194                 for (i = disks; i--; ) {
4195                         struct r5dev *dev = &sh->dev[i];
4196                         if (!test_bit(R5_OVERWRITE, &dev->flags) &&
4197                             i != sh->pd_idx && i != sh->qd_idx &&
4198                             !test_bit(R5_LOCKED, &dev->flags) &&
4199                             !(test_bit(R5_UPTODATE, &dev->flags) ||
4200                               test_bit(R5_Wantcompute, &dev->flags))) {
4201                                 rcw++;
4202                                 if (test_bit(R5_Insync, &dev->flags) &&
4203                                     test_bit(STRIPE_PREREAD_ACTIVE,
4204                                              &sh->state)) {
4205                                         pr_debug("Read_old block "
4206                                                 "%d for Reconstruct\n", i);
4207                                         set_bit(R5_LOCKED, &dev->flags);
4208                                         set_bit(R5_Wantread, &dev->flags);
4209                                         s->locked++;
4210                                         qread++;
4211                                 } else
4212                                         set_bit(STRIPE_DELAYED, &sh->state);
4213                         }
4214                 }
4215                 if (rcw && conf->mddev->queue)
4216                         blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
4217                                           (unsigned long long)sh->sector,
4218                                           rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
4219         }
4220
4221         if (rcw > disks && rmw > disks &&
4222             !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4223                 set_bit(STRIPE_DELAYED, &sh->state);
4224
4225         /* now if nothing is locked, and if we have enough data,
4226          * we can start a write request
4227          */
4228         /* since handle_stripe can be called at any time we need to handle the
4229          * case where a compute block operation has been submitted and then a
4230          * subsequent call wants to start a write request.  raid_run_ops only
4231          * handles the case where compute block and reconstruct are requested
4232          * simultaneously.  If this is not the case then new writes need to be
4233          * held off until the compute completes.
4234          */
4235         if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
4236             (s->locked == 0 && (rcw == 0 || rmw == 0) &&
4237              !test_bit(STRIPE_BIT_DELAY, &sh->state)))
4238                 schedule_reconstruction(sh, s, rcw == 0, 0);
4239         return 0;
4240 }
4241
4242 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
4243                                 struct stripe_head_state *s, int disks)
4244 {
4245         struct r5dev *dev = NULL;
4246
4247         BUG_ON(sh->batch_head);
4248         set_bit(STRIPE_HANDLE, &sh->state);
4249
4250         switch (sh->check_state) {
4251         case check_state_idle:
4252                 /* start a new check operation if there are no failures */
4253                 if (s->failed == 0) {
4254                         BUG_ON(s->uptodate != disks);
4255                         sh->check_state = check_state_run;
4256                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
4257                         clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4258                         s->uptodate--;
4259                         break;
4260                 }
4261                 dev = &sh->dev[s->failed_num[0]];
4262                 fallthrough;
4263         case check_state_compute_result:
4264                 sh->check_state = check_state_idle;
4265                 if (!dev)
4266                         dev = &sh->dev[sh->pd_idx];
4267
4268                 /* check that a write has not made the stripe insync */
4269                 if (test_bit(STRIPE_INSYNC, &sh->state))
4270                         break;
4271
4272                 /* either failed parity check, or recovery is happening */
4273                 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
4274                 BUG_ON(s->uptodate != disks);
4275
4276                 set_bit(R5_LOCKED, &dev->flags);
4277                 s->locked++;
4278                 set_bit(R5_Wantwrite, &dev->flags);
4279
4280                 clear_bit(STRIPE_DEGRADED, &sh->state);
4281                 set_bit(STRIPE_INSYNC, &sh->state);
4282                 break;
4283         case check_state_run:
4284                 break; /* we will be called again upon completion */
4285         case check_state_check_result:
4286                 sh->check_state = check_state_idle;
4287
4288                 /* if a failure occurred during the check operation, leave
4289                  * STRIPE_INSYNC not set and let the stripe be handled again
4290                  */
4291                 if (s->failed)
4292                         break;
4293
4294                 /* handle a successful check operation, if parity is correct
4295                  * we are done.  Otherwise update the mismatch count and repair
4296                  * parity if !MD_RECOVERY_CHECK
4297                  */
4298                 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
4299                         /* parity is correct (on disc,
4300                          * not in buffer any more)
4301                          */
4302                         set_bit(STRIPE_INSYNC, &sh->state);
4303                 else {
4304                         atomic64_add(RAID5_STRIPE_SECTORS(conf), &conf->mddev->resync_mismatches);
4305                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4306                                 /* don't try to repair!! */
4307                                 set_bit(STRIPE_INSYNC, &sh->state);
4308                                 pr_warn_ratelimited("%s: mismatch sector in range "
4309                                                     "%llu-%llu\n", mdname(conf->mddev),
4310                                                     (unsigned long long) sh->sector,
4311                                                     (unsigned long long) sh->sector +
4312                                                     RAID5_STRIPE_SECTORS(conf));
4313                         } else {
4314                                 sh->check_state = check_state_compute_run;
4315                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4316                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4317                                 set_bit(R5_Wantcompute,
4318                                         &sh->dev[sh->pd_idx].flags);
4319                                 sh->ops.target = sh->pd_idx;
4320                                 sh->ops.target2 = -1;
4321                                 s->uptodate++;
4322                         }
4323                 }
4324                 break;
4325         case check_state_compute_run:
4326                 break;
4327         default:
4328                 pr_err("%s: unknown check_state: %d sector: %llu\n",
4329                        __func__, sh->check_state,
4330                        (unsigned long long) sh->sector);
4331                 BUG();
4332         }
4333 }
4334
4335 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
4336                                   struct stripe_head_state *s,
4337                                   int disks)
4338 {
4339         int pd_idx = sh->pd_idx;
4340         int qd_idx = sh->qd_idx;
4341         struct r5dev *dev;
4342
4343         BUG_ON(sh->batch_head);
4344         set_bit(STRIPE_HANDLE, &sh->state);
4345
4346         BUG_ON(s->failed > 2);
4347
4348         /* Want to check and possibly repair P and Q.
4349          * However there could be one 'failed' device, in which
4350          * case we can only check one of them, possibly using the
4351          * other to generate missing data
4352          */
4353
4354         switch (sh->check_state) {
4355         case check_state_idle:
4356                 /* start a new check operation if there are < 2 failures */
4357                 if (s->failed == s->q_failed) {
4358                         /* The only possible failed device holds Q, so it
4359                          * makes sense to check P (If anything else were failed,
4360                          * we would have used P to recreate it).
4361                          */
4362                         sh->check_state = check_state_run;
4363                 }
4364                 if (!s->q_failed && s->failed < 2) {
4365                         /* Q is not failed, and we didn't use it to generate
4366                          * anything, so it makes sense to check it
4367                          */
4368                         if (sh->check_state == check_state_run)
4369                                 sh->check_state = check_state_run_pq;
4370                         else
4371                                 sh->check_state = check_state_run_q;
4372                 }
4373
4374                 /* discard potentially stale zero_sum_result */
4375                 sh->ops.zero_sum_result = 0;
4376
4377                 if (sh->check_state == check_state_run) {
4378                         /* async_xor_zero_sum destroys the contents of P */
4379                         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
4380                         s->uptodate--;
4381                 }
4382                 if (sh->check_state >= check_state_run &&
4383                     sh->check_state <= check_state_run_pq) {
4384                         /* async_syndrome_zero_sum preserves P and Q, so
4385                          * no need to mark them !uptodate here
4386                          */
4387                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
4388                         break;
4389                 }
4390
4391                 /* we have 2-disk failure */
4392                 BUG_ON(s->failed != 2);
4393                 fallthrough;
4394         case check_state_compute_result:
4395                 sh->check_state = check_state_idle;
4396
4397                 /* check that a write has not made the stripe insync */
4398                 if (test_bit(STRIPE_INSYNC, &sh->state))
4399                         break;
4400
4401                 /* now write out any block on a failed drive,
4402                  * or P or Q if they were recomputed
4403                  */
4404                 dev = NULL;
4405                 if (s->failed == 2) {
4406                         dev = &sh->dev[s->failed_num[1]];
4407                         s->locked++;
4408                         set_bit(R5_LOCKED, &dev->flags);
4409                         set_bit(R5_Wantwrite, &dev->flags);
4410                 }
4411                 if (s->failed >= 1) {
4412                         dev = &sh->dev[s->failed_num[0]];
4413                         s->locked++;
4414                         set_bit(R5_LOCKED, &dev->flags);
4415                         set_bit(R5_Wantwrite, &dev->flags);
4416                 }
4417                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4418                         dev = &sh->dev[pd_idx];
4419                         s->locked++;
4420                         set_bit(R5_LOCKED, &dev->flags);
4421                         set_bit(R5_Wantwrite, &dev->flags);
4422                 }
4423                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4424                         dev = &sh->dev[qd_idx];
4425                         s->locked++;
4426                         set_bit(R5_LOCKED, &dev->flags);
4427                         set_bit(R5_Wantwrite, &dev->flags);
4428                 }
4429                 if (WARN_ONCE(dev && !test_bit(R5_UPTODATE, &dev->flags),
4430                               "%s: disk%td not up to date\n",
4431                               mdname(conf->mddev),
4432                               dev - (struct r5dev *) &sh->dev)) {
4433                         clear_bit(R5_LOCKED, &dev->flags);
4434                         clear_bit(R5_Wantwrite, &dev->flags);
4435                         s->locked--;
4436                 }
4437                 clear_bit(STRIPE_DEGRADED, &sh->state);
4438
4439                 set_bit(STRIPE_INSYNC, &sh->state);
4440                 break;
4441         case check_state_run:
4442         case check_state_run_q:
4443         case check_state_run_pq:
4444                 break; /* we will be called again upon completion */
4445         case check_state_check_result:
4446                 sh->check_state = check_state_idle;
4447
4448                 /* handle a successful check operation, if parity is correct
4449                  * we are done.  Otherwise update the mismatch count and repair
4450                  * parity if !MD_RECOVERY_CHECK
4451                  */
4452                 if (sh->ops.zero_sum_result == 0) {
4453                         /* both parities are correct */
4454                         if (!s->failed)
4455                                 set_bit(STRIPE_INSYNC, &sh->state);
4456                         else {
4457                                 /* in contrast to the raid5 case we can validate
4458                                  * parity, but still have a failure to write
4459                                  * back
4460                                  */
4461                                 sh->check_state = check_state_compute_result;
4462                                 /* Returning at this point means that we may go
4463                                  * off and bring p and/or q uptodate again so
4464                                  * we make sure to check zero_sum_result again
4465                                  * to verify if p or q need writeback
4466                                  */
4467                         }
4468                 } else {
4469                         atomic64_add(RAID5_STRIPE_SECTORS(conf), &conf->mddev->resync_mismatches);
4470                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4471                                 /* don't try to repair!! */
4472                                 set_bit(STRIPE_INSYNC, &sh->state);
4473                                 pr_warn_ratelimited("%s: mismatch sector in range "
4474                                                     "%llu-%llu\n", mdname(conf->mddev),
4475                                                     (unsigned long long) sh->sector,
4476                                                     (unsigned long long) sh->sector +
4477                                                     RAID5_STRIPE_SECTORS(conf));
4478                         } else {
4479                                 int *target = &sh->ops.target;
4480
4481                                 sh->ops.target = -1;
4482                                 sh->ops.target2 = -1;
4483                                 sh->check_state = check_state_compute_run;
4484                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4485                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4486                                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4487                                         set_bit(R5_Wantcompute,
4488                                                 &sh->dev[pd_idx].flags);
4489                                         *target = pd_idx;
4490                                         target = &sh->ops.target2;
4491                                         s->uptodate++;
4492                                 }
4493                                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4494                                         set_bit(R5_Wantcompute,
4495                                                 &sh->dev[qd_idx].flags);
4496                                         *target = qd_idx;
4497                                         s->uptodate++;
4498                                 }
4499                         }
4500                 }
4501                 break;
4502         case check_state_compute_run:
4503                 break;
4504         default:
4505                 pr_warn("%s: unknown check_state: %d sector: %llu\n",
4506                         __func__, sh->check_state,
4507                         (unsigned long long) sh->sector);
4508                 BUG();
4509         }
4510 }
4511
4512 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
4513 {
4514         int i;
4515
4516         /* We have read all the blocks in this stripe and now we need to
4517          * copy some of them into a target stripe for expand.
4518          */
4519         struct dma_async_tx_descriptor *tx = NULL;
4520         BUG_ON(sh->batch_head);
4521         clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4522         for (i = 0; i < sh->disks; i++)
4523                 if (i != sh->pd_idx && i != sh->qd_idx) {
4524                         int dd_idx, j;
4525                         struct stripe_head *sh2;
4526                         struct async_submit_ctl submit;
4527
4528                         sector_t bn = raid5_compute_blocknr(sh, i, 1);
4529                         sector_t s = raid5_compute_sector(conf, bn, 0,
4530                                                           &dd_idx, NULL);
4531                         sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
4532                         if (sh2 == NULL)
4533                                 /* so far only the early blocks of this stripe
4534                                  * have been requested.  When later blocks
4535                                  * get requested, we will try again
4536                                  */
4537                                 continue;
4538                         if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
4539                            test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
4540                                 /* must have already done this block */
4541                                 raid5_release_stripe(sh2);
4542                                 continue;
4543                         }
4544
4545                         /* place all the copies on one channel */
4546                         init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
4547                         tx = async_memcpy(sh2->dev[dd_idx].page,
4548                                           sh->dev[i].page, sh2->dev[dd_idx].offset,
4549                                           sh->dev[i].offset, RAID5_STRIPE_SIZE(conf),
4550                                           &submit);
4551
4552                         set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
4553                         set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4554                         for (j = 0; j < conf->raid_disks; j++)
4555                                 if (j != sh2->pd_idx &&
4556                                     j != sh2->qd_idx &&
4557                                     !test_bit(R5_Expanded, &sh2->dev[j].flags))
4558                                         break;
4559                         if (j == conf->raid_disks) {
4560                                 set_bit(STRIPE_EXPAND_READY, &sh2->state);
4561                                 set_bit(STRIPE_HANDLE, &sh2->state);
4562                         }
4563                         raid5_release_stripe(sh2);
4564
4565                 }
4566         /* done submitting copies, wait for them to complete */
4567         async_tx_quiesce(&tx);
4568 }
4569
4570 /*
4571  * handle_stripe - do things to a stripe.
4572  *
4573  * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4574  * state of various bits to see what needs to be done.
4575  * Possible results:
4576  *    return some read requests which now have data
4577  *    return some write requests which are safely on storage
4578  *    schedule a read on some buffers
4579  *    schedule a write of some buffers
4580  *    return confirmation of parity correctness
4581  *
4582  */
4583
4584 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4585 {
4586         struct r5conf *conf = sh->raid_conf;
4587         int disks = sh->disks;
4588         struct r5dev *dev;
4589         int i;
4590         int do_recovery = 0;
4591
4592         memset(s, 0, sizeof(*s));
4593
4594         s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4595         s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4596         s->failed_num[0] = -1;
4597         s->failed_num[1] = -1;
4598         s->log_failed = r5l_log_disk_error(conf);
4599
4600         /* Now to look around and see what can be done */
4601         rcu_read_lock();
4602         for (i=disks; i--; ) {
4603                 struct md_rdev *rdev;
4604                 sector_t first_bad;
4605                 int bad_sectors;
4606                 int is_bad = 0;
4607
4608                 dev = &sh->dev[i];
4609
4610                 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4611                          i, dev->flags,
4612                          dev->toread, dev->towrite, dev->written);
4613                 /* maybe we can reply to a read
4614                  *
4615                  * new wantfill requests are only permitted while
4616                  * ops_complete_biofill is guaranteed to be inactive
4617                  */
4618                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4619                     !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4620                         set_bit(R5_Wantfill, &dev->flags);
4621
4622                 /* now count some things */
4623                 if (test_bit(R5_LOCKED, &dev->flags))
4624                         s->locked++;
4625                 if (test_bit(R5_UPTODATE, &dev->flags))
4626                         s->uptodate++;
4627                 if (test_bit(R5_Wantcompute, &dev->flags)) {
4628                         s->compute++;
4629                         BUG_ON(s->compute > 2);
4630                 }
4631
4632                 if (test_bit(R5_Wantfill, &dev->flags))
4633                         s->to_fill++;
4634                 else if (dev->toread)
4635                         s->to_read++;
4636                 if (dev->towrite) {
4637                         s->to_write++;
4638                         if (!test_bit(R5_OVERWRITE, &dev->flags))
4639                                 s->non_overwrite++;
4640                 }
4641                 if (dev->written)
4642                         s->written++;
4643                 /* Prefer to use the replacement for reads, but only
4644                  * if it is recovered enough and has no bad blocks.
4645                  */
4646                 rdev = rcu_dereference(conf->disks[i].replacement);
4647                 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4648                     rdev->recovery_offset >= sh->sector + RAID5_STRIPE_SECTORS(conf) &&
4649                     !is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
4650                                  &first_bad, &bad_sectors))
4651                         set_bit(R5_ReadRepl, &dev->flags);
4652                 else {
4653                         if (rdev && !test_bit(Faulty, &rdev->flags))
4654                                 set_bit(R5_NeedReplace, &dev->flags);
4655                         else
4656                                 clear_bit(R5_NeedReplace, &dev->flags);
4657                         rdev = rcu_dereference(conf->disks[i].rdev);
4658                         clear_bit(R5_ReadRepl, &dev->flags);
4659                 }
4660                 if (rdev && test_bit(Faulty, &rdev->flags))
4661                         rdev = NULL;
4662                 if (rdev) {
4663                         is_bad = is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
4664                                              &first_bad, &bad_sectors);
4665                         if (s->blocked_rdev == NULL
4666                             && (test_bit(Blocked, &rdev->flags)
4667                                 || is_bad < 0)) {
4668                                 if (is_bad < 0)
4669                                         set_bit(BlockedBadBlocks,
4670                                                 &rdev->flags);
4671                                 s->blocked_rdev = rdev;
4672                                 atomic_inc(&rdev->nr_pending);
4673                         }
4674                 }
4675                 clear_bit(R5_Insync, &dev->flags);
4676                 if (!rdev)
4677                         /* Not in-sync */;
4678                 else if (is_bad) {
4679                         /* also not in-sync */
4680                         if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4681                             test_bit(R5_UPTODATE, &dev->flags)) {
4682                                 /* treat as in-sync, but with a read error
4683                                  * which we can now try to correct
4684                                  */
4685                                 set_bit(R5_Insync, &dev->flags);
4686                                 set_bit(R5_ReadError, &dev->flags);
4687                         }
4688                 } else if (test_bit(In_sync, &rdev->flags))
4689                         set_bit(R5_Insync, &dev->flags);
4690                 else if (sh->sector + RAID5_STRIPE_SECTORS(conf) <= rdev->recovery_offset)
4691                         /* in sync if before recovery_offset */
4692                         set_bit(R5_Insync, &dev->flags);
4693                 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4694                          test_bit(R5_Expanded, &dev->flags))
4695                         /* If we've reshaped into here, we assume it is Insync.
4696                          * We will shortly update recovery_offset to make
4697                          * it official.
4698                          */
4699                         set_bit(R5_Insync, &dev->flags);
4700
4701                 if (test_bit(R5_WriteError, &dev->flags)) {
4702                         /* This flag does not apply to '.replacement'
4703                          * only to .rdev, so make sure to check that*/
4704                         struct md_rdev *rdev2 = rcu_dereference(
4705                                 conf->disks[i].rdev);
4706                         if (rdev2 == rdev)
4707                                 clear_bit(R5_Insync, &dev->flags);
4708                         if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4709                                 s->handle_bad_blocks = 1;
4710                                 atomic_inc(&rdev2->nr_pending);
4711                         } else
4712                                 clear_bit(R5_WriteError, &dev->flags);
4713                 }
4714                 if (test_bit(R5_MadeGood, &dev->flags)) {
4715                         /* This flag does not apply to '.replacement'
4716                          * only to .rdev, so make sure to check that*/
4717                         struct md_rdev *rdev2 = rcu_dereference(
4718                                 conf->disks[i].rdev);
4719                         if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4720                                 s->handle_bad_blocks = 1;
4721                                 atomic_inc(&rdev2->nr_pending);
4722                         } else
4723                                 clear_bit(R5_MadeGood, &dev->flags);
4724                 }
4725                 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4726                         struct md_rdev *rdev2 = rcu_dereference(
4727                                 conf->disks[i].replacement);
4728                         if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4729                                 s->handle_bad_blocks = 1;
4730                                 atomic_inc(&rdev2->nr_pending);
4731                         } else
4732                                 clear_bit(R5_MadeGoodRepl, &dev->flags);
4733                 }
4734                 if (!test_bit(R5_Insync, &dev->flags)) {
4735                         /* The ReadError flag will just be confusing now */
4736                         clear_bit(R5_ReadError, &dev->flags);
4737                         clear_bit(R5_ReWrite, &dev->flags);
4738                 }
4739                 if (test_bit(R5_ReadError, &dev->flags))
4740                         clear_bit(R5_Insync, &dev->flags);
4741                 if (!test_bit(R5_Insync, &dev->flags)) {
4742                         if (s->failed < 2)
4743                                 s->failed_num[s->failed] = i;
4744                         s->failed++;
4745                         if (rdev && !test_bit(Faulty, &rdev->flags))
4746                                 do_recovery = 1;
4747                         else if (!rdev) {
4748                                 rdev = rcu_dereference(
4749                                     conf->disks[i].replacement);
4750                                 if (rdev && !test_bit(Faulty, &rdev->flags))
4751                                         do_recovery = 1;
4752                         }
4753                 }
4754
4755                 if (test_bit(R5_InJournal, &dev->flags))
4756                         s->injournal++;
4757                 if (test_bit(R5_InJournal, &dev->flags) && dev->written)
4758                         s->just_cached++;
4759         }
4760         if (test_bit(STRIPE_SYNCING, &sh->state)) {
4761                 /* If there is a failed device being replaced,
4762                  *     we must be recovering.
4763                  * else if we are after recovery_cp, we must be syncing
4764                  * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4765                  * else we can only be replacing
4766                  * sync and recovery both need to read all devices, and so
4767                  * use the same flag.
4768                  */
4769                 if (do_recovery ||
4770                     sh->sector >= conf->mddev->recovery_cp ||
4771                     test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4772                         s->syncing = 1;
4773                 else
4774                         s->replacing = 1;
4775         }
4776         rcu_read_unlock();
4777 }
4778
4779 /*
4780  * Return '1' if this is a member of batch, or '0' if it is a lone stripe or
4781  * a head which can now be handled.
4782  */
4783 static int clear_batch_ready(struct stripe_head *sh)
4784 {
4785         struct stripe_head *tmp;
4786         if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4787                 return (sh->batch_head && sh->batch_head != sh);
4788         spin_lock(&sh->stripe_lock);
4789         if (!sh->batch_head) {
4790                 spin_unlock(&sh->stripe_lock);
4791                 return 0;
4792         }
4793
4794         /*
4795          * this stripe could be added to a batch list before we check
4796          * BATCH_READY, skips it
4797          */
4798         if (sh->batch_head != sh) {
4799                 spin_unlock(&sh->stripe_lock);
4800                 return 1;
4801         }
4802         spin_lock(&sh->batch_lock);
4803         list_for_each_entry(tmp, &sh->batch_list, batch_list)
4804                 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4805         spin_unlock(&sh->batch_lock);
4806         spin_unlock(&sh->stripe_lock);
4807
4808         /*
4809          * BATCH_READY is cleared, no new stripes can be added.
4810          * batch_list can be accessed without lock
4811          */
4812         return 0;
4813 }
4814
4815 static void break_stripe_batch_list(struct stripe_head *head_sh,
4816                                     unsigned long handle_flags)
4817 {
4818         struct stripe_head *sh, *next;
4819         int i;
4820         int do_wakeup = 0;
4821
4822         list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4823
4824                 list_del_init(&sh->batch_list);
4825
4826                 WARN_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4827                                           (1 << STRIPE_SYNCING) |
4828                                           (1 << STRIPE_REPLACED) |
4829                                           (1 << STRIPE_DELAYED) |
4830                                           (1 << STRIPE_BIT_DELAY) |
4831                                           (1 << STRIPE_FULL_WRITE) |
4832                                           (1 << STRIPE_BIOFILL_RUN) |
4833                                           (1 << STRIPE_COMPUTE_RUN)  |
4834                                           (1 << STRIPE_DISCARD) |
4835                                           (1 << STRIPE_BATCH_READY) |
4836                                           (1 << STRIPE_BATCH_ERR) |
4837                                           (1 << STRIPE_BITMAP_PENDING)),
4838                         "stripe state: %lx\n", sh->state);
4839                 WARN_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4840                                               (1 << STRIPE_REPLACED)),
4841                         "head stripe state: %lx\n", head_sh->state);
4842
4843                 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4844                                             (1 << STRIPE_PREREAD_ACTIVE) |
4845                                             (1 << STRIPE_DEGRADED) |
4846                                             (1 << STRIPE_ON_UNPLUG_LIST)),
4847                               head_sh->state & (1 << STRIPE_INSYNC));
4848
4849                 sh->check_state = head_sh->check_state;
4850                 sh->reconstruct_state = head_sh->reconstruct_state;
4851                 spin_lock_irq(&sh->stripe_lock);
4852                 sh->batch_head = NULL;
4853                 spin_unlock_irq(&sh->stripe_lock);
4854                 for (i = 0; i < sh->disks; i++) {
4855                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4856                                 do_wakeup = 1;
4857                         sh->dev[i].flags = head_sh->dev[i].flags &
4858                                 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4859                 }
4860                 if (handle_flags == 0 ||
4861                     sh->state & handle_flags)
4862                         set_bit(STRIPE_HANDLE, &sh->state);
4863                 raid5_release_stripe(sh);
4864         }
4865         spin_lock_irq(&head_sh->stripe_lock);
4866         head_sh->batch_head = NULL;
4867         spin_unlock_irq(&head_sh->stripe_lock);
4868         for (i = 0; i < head_sh->disks; i++)
4869                 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4870                         do_wakeup = 1;
4871         if (head_sh->state & handle_flags)
4872                 set_bit(STRIPE_HANDLE, &head_sh->state);
4873
4874         if (do_wakeup)
4875                 wake_up(&head_sh->raid_conf->wait_for_overlap);
4876 }
4877
4878 static void handle_stripe(struct stripe_head *sh)
4879 {
4880         struct stripe_head_state s;
4881         struct r5conf *conf = sh->raid_conf;
4882         int i;
4883         int prexor;
4884         int disks = sh->disks;
4885         struct r5dev *pdev, *qdev;
4886
4887         clear_bit(STRIPE_HANDLE, &sh->state);
4888
4889         /*
4890          * handle_stripe should not continue handle the batched stripe, only
4891          * the head of batch list or lone stripe can continue. Otherwise we
4892          * could see break_stripe_batch_list warns about the STRIPE_ACTIVE
4893          * is set for the batched stripe.
4894          */
4895         if (clear_batch_ready(sh))
4896                 return;
4897
4898         if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4899                 /* already being handled, ensure it gets handled
4900                  * again when current action finishes */
4901                 set_bit(STRIPE_HANDLE, &sh->state);
4902                 return;
4903         }
4904
4905         if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4906                 break_stripe_batch_list(sh, 0);
4907
4908         if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4909                 spin_lock(&sh->stripe_lock);
4910                 /*
4911                  * Cannot process 'sync' concurrently with 'discard'.
4912                  * Flush data in r5cache before 'sync'.
4913                  */
4914                 if (!test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state) &&
4915                     !test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) &&
4916                     !test_bit(STRIPE_DISCARD, &sh->state) &&
4917                     test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4918                         set_bit(STRIPE_SYNCING, &sh->state);
4919                         clear_bit(STRIPE_INSYNC, &sh->state);
4920                         clear_bit(STRIPE_REPLACED, &sh->state);
4921                 }
4922                 spin_unlock(&sh->stripe_lock);
4923         }
4924         clear_bit(STRIPE_DELAYED, &sh->state);
4925
4926         pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4927                 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4928                (unsigned long long)sh->sector, sh->state,
4929                atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4930                sh->check_state, sh->reconstruct_state);
4931
4932         analyse_stripe(sh, &s);
4933
4934         if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4935                 goto finish;
4936
4937         if (s.handle_bad_blocks ||
4938             test_bit(MD_SB_CHANGE_PENDING, &conf->mddev->sb_flags)) {
4939                 set_bit(STRIPE_HANDLE, &sh->state);
4940                 goto finish;
4941         }
4942
4943         if (unlikely(s.blocked_rdev)) {
4944                 if (s.syncing || s.expanding || s.expanded ||
4945                     s.replacing || s.to_write || s.written) {
4946                         set_bit(STRIPE_HANDLE, &sh->state);
4947                         goto finish;
4948                 }
4949                 /* There is nothing for the blocked_rdev to block */
4950                 rdev_dec_pending(s.blocked_rdev, conf->mddev);
4951                 s.blocked_rdev = NULL;
4952         }
4953
4954         if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4955                 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4956                 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4957         }
4958
4959         pr_debug("locked=%d uptodate=%d to_read=%d"
4960                " to_write=%d failed=%d failed_num=%d,%d\n",
4961                s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4962                s.failed_num[0], s.failed_num[1]);
4963         /*
4964          * check if the array has lost more than max_degraded devices and,
4965          * if so, some requests might need to be failed.
4966          *
4967          * When journal device failed (log_failed), we will only process
4968          * the stripe if there is data need write to raid disks
4969          */
4970         if (s.failed > conf->max_degraded ||
4971             (s.log_failed && s.injournal == 0)) {
4972                 sh->check_state = 0;
4973                 sh->reconstruct_state = 0;
4974                 break_stripe_batch_list(sh, 0);
4975                 if (s.to_read+s.to_write+s.written)
4976                         handle_failed_stripe(conf, sh, &s, disks);
4977                 if (s.syncing + s.replacing)
4978                         handle_failed_sync(conf, sh, &s);
4979         }
4980
4981         /* Now we check to see if any write operations have recently
4982          * completed
4983          */
4984         prexor = 0;
4985         if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4986                 prexor = 1;
4987         if (sh->reconstruct_state == reconstruct_state_drain_result ||
4988             sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4989                 sh->reconstruct_state = reconstruct_state_idle;
4990
4991                 /* All the 'written' buffers and the parity block are ready to
4992                  * be written back to disk
4993                  */
4994                 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4995                        !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4996                 BUG_ON(sh->qd_idx >= 0 &&
4997                        !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4998                        !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4999                 for (i = disks; i--; ) {
5000                         struct r5dev *dev = &sh->dev[i];
5001                         if (test_bit(R5_LOCKED, &dev->flags) &&
5002                                 (i == sh->pd_idx || i == sh->qd_idx ||
5003                                  dev->written || test_bit(R5_InJournal,
5004                                                           &dev->flags))) {
5005                                 pr_debug("Writing block %d\n", i);
5006                                 set_bit(R5_Wantwrite, &dev->flags);
5007                                 if (prexor)
5008                                         continue;
5009                                 if (s.failed > 1)
5010                                         continue;
5011                                 if (!test_bit(R5_Insync, &dev->flags) ||
5012                                     ((i == sh->pd_idx || i == sh->qd_idx)  &&
5013                                      s.failed == 0))
5014                                         set_bit(STRIPE_INSYNC, &sh->state);
5015                         }
5016                 }
5017                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5018                         s.dec_preread_active = 1;
5019         }
5020
5021         /*
5022          * might be able to return some write requests if the parity blocks
5023          * are safe, or on a failed drive
5024          */
5025         pdev = &sh->dev[sh->pd_idx];
5026         s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
5027                 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
5028         qdev = &sh->dev[sh->qd_idx];
5029         s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
5030                 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
5031                 || conf->level < 6;
5032
5033         if (s.written &&
5034             (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
5035                              && !test_bit(R5_LOCKED, &pdev->flags)
5036                              && (test_bit(R5_UPTODATE, &pdev->flags) ||
5037                                  test_bit(R5_Discard, &pdev->flags))))) &&
5038             (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
5039                              && !test_bit(R5_LOCKED, &qdev->flags)
5040                              && (test_bit(R5_UPTODATE, &qdev->flags) ||
5041                                  test_bit(R5_Discard, &qdev->flags))))))
5042                 handle_stripe_clean_event(conf, sh, disks);
5043
5044         if (s.just_cached)
5045                 r5c_handle_cached_data_endio(conf, sh, disks);
5046         log_stripe_write_finished(sh);
5047
5048         /* Now we might consider reading some blocks, either to check/generate
5049          * parity, or to satisfy requests
5050          * or to load a block that is being partially written.
5051          */
5052         if (s.to_read || s.non_overwrite
5053             || (s.to_write && s.failed)
5054             || (s.syncing && (s.uptodate + s.compute < disks))
5055             || s.replacing
5056             || s.expanding)
5057                 handle_stripe_fill(sh, &s, disks);
5058
5059         /*
5060          * When the stripe finishes full journal write cycle (write to journal
5061          * and raid disk), this is the clean up procedure so it is ready for
5062          * next operation.
5063          */
5064         r5c_finish_stripe_write_out(conf, sh, &s);
5065
5066         /*
5067          * Now to consider new write requests, cache write back and what else,
5068          * if anything should be read.  We do not handle new writes when:
5069          * 1/ A 'write' operation (copy+xor) is already in flight.
5070          * 2/ A 'check' operation is in flight, as it may clobber the parity
5071          *    block.
5072          * 3/ A r5c cache log write is in flight.
5073          */
5074
5075         if (!sh->reconstruct_state && !sh->check_state && !sh->log_io) {
5076                 if (!r5c_is_writeback(conf->log)) {
5077                         if (s.to_write)
5078                                 handle_stripe_dirtying(conf, sh, &s, disks);
5079                 } else { /* write back cache */
5080                         int ret = 0;
5081
5082                         /* First, try handle writes in caching phase */
5083                         if (s.to_write)
5084                                 ret = r5c_try_caching_write(conf, sh, &s,
5085                                                             disks);
5086                         /*
5087                          * If caching phase failed: ret == -EAGAIN
5088                          *    OR
5089                          * stripe under reclaim: !caching && injournal
5090                          *
5091                          * fall back to handle_stripe_dirtying()
5092                          */
5093                         if (ret == -EAGAIN ||
5094                             /* stripe under reclaim: !caching && injournal */
5095                             (!test_bit(STRIPE_R5C_CACHING, &sh->state) &&
5096                              s.injournal > 0)) {
5097                                 ret = handle_stripe_dirtying(conf, sh, &s,
5098                                                              disks);
5099                                 if (ret == -EAGAIN)
5100                                         goto finish;
5101                         }
5102                 }
5103         }
5104
5105         /* maybe we need to check and possibly fix the parity for this stripe
5106          * Any reads will already have been scheduled, so we just see if enough
5107          * data is available.  The parity check is held off while parity
5108          * dependent operations are in flight.
5109          */
5110         if (sh->check_state ||
5111             (s.syncing && s.locked == 0 &&
5112              !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
5113              !test_bit(STRIPE_INSYNC, &sh->state))) {
5114                 if (conf->level == 6)
5115                         handle_parity_checks6(conf, sh, &s, disks);
5116                 else
5117                         handle_parity_checks5(conf, sh, &s, disks);
5118         }
5119
5120         if ((s.replacing || s.syncing) && s.locked == 0
5121             && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
5122             && !test_bit(STRIPE_REPLACED, &sh->state)) {
5123                 /* Write out to replacement devices where possible */
5124                 for (i = 0; i < conf->raid_disks; i++)
5125                         if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
5126                                 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
5127                                 set_bit(R5_WantReplace, &sh->dev[i].flags);
5128                                 set_bit(R5_LOCKED, &sh->dev[i].flags);
5129                                 s.locked++;
5130                         }
5131                 if (s.replacing)
5132                         set_bit(STRIPE_INSYNC, &sh->state);
5133                 set_bit(STRIPE_REPLACED, &sh->state);
5134         }
5135         if ((s.syncing || s.replacing) && s.locked == 0 &&
5136             !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
5137             test_bit(STRIPE_INSYNC, &sh->state)) {
5138                 md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), 1);
5139                 clear_bit(STRIPE_SYNCING, &sh->state);
5140                 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
5141                         wake_up(&conf->wait_for_overlap);
5142         }
5143
5144         /* If the failed drives are just a ReadError, then we might need
5145          * to progress the repair/check process
5146          */
5147         if (s.failed <= conf->max_degraded && !conf->mddev->ro)
5148                 for (i = 0; i < s.failed; i++) {
5149                         struct r5dev *dev = &sh->dev[s.failed_num[i]];
5150                         if (test_bit(R5_ReadError, &dev->flags)
5151                             && !test_bit(R5_LOCKED, &dev->flags)
5152                             && test_bit(R5_UPTODATE, &dev->flags)
5153                                 ) {
5154                                 if (!test_bit(R5_ReWrite, &dev->flags)) {
5155                                         set_bit(R5_Wantwrite, &dev->flags);
5156                                         set_bit(R5_ReWrite, &dev->flags);
5157                                 } else
5158                                         /* let's read it back */
5159                                         set_bit(R5_Wantread, &dev->flags);
5160                                 set_bit(R5_LOCKED, &dev->flags);
5161                                 s.locked++;
5162                         }
5163                 }
5164
5165         /* Finish reconstruct operations initiated by the expansion process */
5166         if (sh->reconstruct_state == reconstruct_state_result) {
5167                 struct stripe_head *sh_src
5168                         = raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
5169                 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
5170                         /* sh cannot be written until sh_src has been read.
5171                          * so arrange for sh to be delayed a little
5172                          */
5173                         set_bit(STRIPE_DELAYED, &sh->state);
5174                         set_bit(STRIPE_HANDLE, &sh->state);
5175                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
5176                                               &sh_src->state))
5177                                 atomic_inc(&conf->preread_active_stripes);
5178                         raid5_release_stripe(sh_src);
5179                         goto finish;
5180                 }
5181                 if (sh_src)
5182                         raid5_release_stripe(sh_src);
5183
5184                 sh->reconstruct_state = reconstruct_state_idle;
5185                 clear_bit(STRIPE_EXPANDING, &sh->state);
5186                 for (i = conf->raid_disks; i--; ) {
5187                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
5188                         set_bit(R5_LOCKED, &sh->dev[i].flags);
5189                         s.locked++;
5190                 }
5191         }
5192
5193         if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
5194             !sh->reconstruct_state) {
5195                 /* Need to write out all blocks after computing parity */
5196                 sh->disks = conf->raid_disks;
5197                 stripe_set_idx(sh->sector, conf, 0, sh);
5198                 schedule_reconstruction(sh, &s, 1, 1);
5199         } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
5200                 clear_bit(STRIPE_EXPAND_READY, &sh->state);
5201                 atomic_dec(&conf->reshape_stripes);
5202                 wake_up(&conf->wait_for_overlap);
5203                 md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), 1);
5204         }
5205
5206         if (s.expanding && s.locked == 0 &&
5207             !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
5208                 handle_stripe_expansion(conf, sh);
5209
5210 finish:
5211         /* wait for this device to become unblocked */
5212         if (unlikely(s.blocked_rdev)) {
5213                 if (conf->mddev->external)
5214                         md_wait_for_blocked_rdev(s.blocked_rdev,
5215                                                  conf->mddev);
5216                 else
5217                         /* Internal metadata will immediately
5218                          * be written by raid5d, so we don't
5219                          * need to wait here.
5220                          */
5221                         rdev_dec_pending(s.blocked_rdev,
5222                                          conf->mddev);
5223         }
5224
5225         if (s.handle_bad_blocks)
5226                 for (i = disks; i--; ) {
5227                         struct md_rdev *rdev;
5228                         struct r5dev *dev = &sh->dev[i];
5229                         if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
5230                                 /* We own a safe reference to the rdev */
5231                                 rdev = conf->disks[i].rdev;
5232                                 if (!rdev_set_badblocks(rdev, sh->sector,
5233                                                         RAID5_STRIPE_SECTORS(conf), 0))
5234                                         md_error(conf->mddev, rdev);
5235                                 rdev_dec_pending(rdev, conf->mddev);
5236                         }
5237                         if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
5238                                 rdev = conf->disks[i].rdev;
5239                                 rdev_clear_badblocks(rdev, sh->sector,
5240                                                      RAID5_STRIPE_SECTORS(conf), 0);
5241                                 rdev_dec_pending(rdev, conf->mddev);
5242                         }
5243                         if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
5244                                 rdev = conf->disks[i].replacement;
5245                                 if (!rdev)
5246                                         /* rdev have been moved down */
5247                                         rdev = conf->disks[i].rdev;
5248                                 rdev_clear_badblocks(rdev, sh->sector,
5249                                                      RAID5_STRIPE_SECTORS(conf), 0);
5250                                 rdev_dec_pending(rdev, conf->mddev);
5251                         }
5252                 }
5253
5254         if (s.ops_request)
5255                 raid_run_ops(sh, s.ops_request);
5256
5257         ops_run_io(sh, &s);
5258
5259         if (s.dec_preread_active) {
5260                 /* We delay this until after ops_run_io so that if make_request
5261                  * is waiting on a flush, it won't continue until the writes
5262                  * have actually been submitted.
5263                  */
5264                 atomic_dec(&conf->preread_active_stripes);
5265                 if (atomic_read(&conf->preread_active_stripes) <
5266                     IO_THRESHOLD)
5267                         md_wakeup_thread(conf->mddev->thread);
5268         }
5269
5270         clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
5271 }
5272
5273 static void raid5_activate_delayed(struct r5conf *conf)
5274 {
5275         if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
5276                 while (!list_empty(&conf->delayed_list)) {
5277                         struct list_head *l = conf->delayed_list.next;
5278                         struct stripe_head *sh;
5279                         sh = list_entry(l, struct stripe_head, lru);
5280                         list_del_init(l);
5281                         clear_bit(STRIPE_DELAYED, &sh->state);
5282                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5283                                 atomic_inc(&conf->preread_active_stripes);
5284                         list_add_tail(&sh->lru, &conf->hold_list);
5285                         raid5_wakeup_stripe_thread(sh);
5286                 }
5287         }
5288 }
5289
5290 static void activate_bit_delay(struct r5conf *conf,
5291         struct list_head *temp_inactive_list)
5292 {
5293         /* device_lock is held */
5294         struct list_head head;
5295         list_add(&head, &conf->bitmap_list);
5296         list_del_init(&conf->bitmap_list);
5297         while (!list_empty(&head)) {
5298                 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
5299                 int hash;
5300                 list_del_init(&sh->lru);
5301                 atomic_inc(&sh->count);
5302                 hash = sh->hash_lock_index;
5303                 __release_stripe(conf, sh, &temp_inactive_list[hash]);
5304         }
5305 }
5306
5307 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
5308 {
5309         struct r5conf *conf = mddev->private;
5310         sector_t sector = bio->bi_iter.bi_sector;
5311         unsigned int chunk_sectors;
5312         unsigned int bio_sectors = bio_sectors(bio);
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 md_io_acct *md_io_acct = bi->bi_private;
5366         struct bio *raid_bi = md_io_acct->orig_bio;
5367         struct mddev *mddev;
5368         struct r5conf *conf;
5369         struct md_rdev *rdev;
5370         blk_status_t error = bi->bi_status;
5371         unsigned long start_time = md_io_acct->start_time;
5372
5373         bio_put(bi);
5374
5375         rdev = (void*)raid_bi->bi_next;
5376         raid_bi->bi_next = NULL;
5377         mddev = rdev->mddev;
5378         conf = mddev->private;
5379
5380         rdev_dec_pending(rdev, conf->mddev);
5381
5382         if (!error) {
5383                 if (blk_queue_io_stat(raid_bi->bi_bdev->bd_disk->queue))
5384                         bio_end_io_acct(raid_bi, start_time);
5385                 bio_endio(raid_bi);
5386                 if (atomic_dec_and_test(&conf->active_aligned_reads))
5387                         wake_up(&conf->wait_for_quiescent);
5388                 return;
5389         }
5390
5391         pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
5392
5393         add_bio_to_retry(raid_bi, conf);
5394 }
5395
5396 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
5397 {
5398         struct r5conf *conf = mddev->private;
5399         struct bio *align_bio;
5400         struct md_rdev *rdev;
5401         sector_t sector, end_sector, first_bad;
5402         int bad_sectors, dd_idx;
5403         struct md_io_acct *md_io_acct;
5404         bool did_inc;
5405
5406         if (!in_chunk_boundary(mddev, raid_bio)) {
5407                 pr_debug("%s: non aligned\n", __func__);
5408                 return 0;
5409         }
5410
5411         sector = raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector, 0,
5412                                       &dd_idx, NULL);
5413         end_sector = bio_end_sector(raid_bio);
5414
5415         rcu_read_lock();
5416         if (r5c_big_stripe_cached(conf, sector))
5417                 goto out_rcu_unlock;
5418
5419         rdev = rcu_dereference(conf->disks[dd_idx].replacement);
5420         if (!rdev || test_bit(Faulty, &rdev->flags) ||
5421             rdev->recovery_offset < end_sector) {
5422                 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
5423                 if (!rdev)
5424                         goto out_rcu_unlock;
5425                 if (test_bit(Faulty, &rdev->flags) ||
5426                     !(test_bit(In_sync, &rdev->flags) ||
5427                       rdev->recovery_offset >= end_sector))
5428                         goto out_rcu_unlock;
5429         }
5430
5431         atomic_inc(&rdev->nr_pending);
5432         rcu_read_unlock();
5433
5434         if (is_badblock(rdev, sector, bio_sectors(raid_bio), &first_bad,
5435                         &bad_sectors)) {
5436                 rdev_dec_pending(rdev, mddev);
5437                 return 0;
5438         }
5439
5440         align_bio = bio_clone_fast(raid_bio, GFP_NOIO, &mddev->io_acct_set);
5441         md_io_acct = container_of(align_bio, struct md_io_acct, bio_clone);
5442         raid_bio->bi_next = (void *)rdev;
5443         if (blk_queue_io_stat(raid_bio->bi_bdev->bd_disk->queue))
5444                 md_io_acct->start_time = bio_start_io_acct(raid_bio);
5445         md_io_acct->orig_bio = raid_bio;
5446
5447         bio_set_dev(align_bio, rdev->bdev);
5448         align_bio->bi_end_io = raid5_align_endio;
5449         align_bio->bi_private = md_io_acct;
5450         align_bio->bi_iter.bi_sector = sector;
5451
5452         /* No reshape active, so we can trust rdev->data_offset */
5453         align_bio->bi_iter.bi_sector += rdev->data_offset;
5454
5455         did_inc = false;
5456         if (conf->quiesce == 0) {
5457                 atomic_inc(&conf->active_aligned_reads);
5458                 did_inc = true;
5459         }
5460         /* need a memory barrier to detect the race with raid5_quiesce() */
5461         if (!did_inc || smp_load_acquire(&conf->quiesce) != 0) {
5462                 /* quiesce is in progress, so we need to undo io activation and wait
5463                  * for it to finish
5464                  */
5465                 if (did_inc && atomic_dec_and_test(&conf->active_aligned_reads))
5466                         wake_up(&conf->wait_for_quiescent);
5467                 spin_lock_irq(&conf->device_lock);
5468                 wait_event_lock_irq(conf->wait_for_quiescent, conf->quiesce == 0,
5469                                     conf->device_lock);
5470                 atomic_inc(&conf->active_aligned_reads);
5471                 spin_unlock_irq(&conf->device_lock);
5472         }
5473
5474         if (mddev->gendisk)
5475                 trace_block_bio_remap(align_bio, disk_devt(mddev->gendisk),
5476                                       raid_bio->bi_iter.bi_sector);
5477         submit_bio_noacct(align_bio);
5478         return 1;
5479
5480 out_rcu_unlock:
5481         rcu_read_unlock();
5482         return 0;
5483 }
5484
5485 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
5486 {
5487         struct bio *split;
5488         sector_t sector = raid_bio->bi_iter.bi_sector;
5489         unsigned chunk_sects = mddev->chunk_sectors;
5490         unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
5491
5492         if (sectors < bio_sectors(raid_bio)) {
5493                 struct r5conf *conf = mddev->private;
5494                 split = bio_split(raid_bio, sectors, GFP_NOIO, &conf->bio_split);
5495                 bio_chain(split, raid_bio);
5496                 submit_bio_noacct(raid_bio);
5497                 raid_bio = split;
5498         }
5499
5500         if (!raid5_read_one_chunk(mddev, raid_bio))
5501                 return raid_bio;
5502
5503         return NULL;
5504 }
5505
5506 /* __get_priority_stripe - get the next stripe to process
5507  *
5508  * Full stripe writes are allowed to pass preread active stripes up until
5509  * the bypass_threshold is exceeded.  In general the bypass_count
5510  * increments when the handle_list is handled before the hold_list; however, it
5511  * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
5512  * stripe with in flight i/o.  The bypass_count will be reset when the
5513  * head of the hold_list has changed, i.e. the head was promoted to the
5514  * handle_list.
5515  */
5516 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
5517 {
5518         struct stripe_head *sh, *tmp;
5519         struct list_head *handle_list = NULL;
5520         struct r5worker_group *wg;
5521         bool second_try = !r5c_is_writeback(conf->log) &&
5522                 !r5l_log_disk_error(conf);
5523         bool try_loprio = test_bit(R5C_LOG_TIGHT, &conf->cache_state) ||
5524                 r5l_log_disk_error(conf);
5525
5526 again:
5527         wg = NULL;
5528         sh = NULL;
5529         if (conf->worker_cnt_per_group == 0) {
5530                 handle_list = try_loprio ? &conf->loprio_list :
5531                                         &conf->handle_list;
5532         } else if (group != ANY_GROUP) {
5533                 handle_list = try_loprio ? &conf->worker_groups[group].loprio_list :
5534                                 &conf->worker_groups[group].handle_list;
5535                 wg = &conf->worker_groups[group];
5536         } else {
5537                 int i;
5538                 for (i = 0; i < conf->group_cnt; i++) {
5539                         handle_list = try_loprio ? &conf->worker_groups[i].loprio_list :
5540                                 &conf->worker_groups[i].handle_list;
5541                         wg = &conf->worker_groups[i];
5542                         if (!list_empty(handle_list))
5543                                 break;
5544                 }
5545         }
5546
5547         pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
5548                   __func__,
5549                   list_empty(handle_list) ? "empty" : "busy",
5550                   list_empty(&conf->hold_list) ? "empty" : "busy",
5551                   atomic_read(&conf->pending_full_writes), conf->bypass_count);
5552
5553         if (!list_empty(handle_list)) {
5554                 sh = list_entry(handle_list->next, typeof(*sh), lru);
5555
5556                 if (list_empty(&conf->hold_list))
5557                         conf->bypass_count = 0;
5558                 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
5559                         if (conf->hold_list.next == conf->last_hold)
5560                                 conf->bypass_count++;
5561                         else {
5562                                 conf->last_hold = conf->hold_list.next;
5563                                 conf->bypass_count -= conf->bypass_threshold;
5564                                 if (conf->bypass_count < 0)
5565                                         conf->bypass_count = 0;
5566                         }
5567                 }
5568         } else if (!list_empty(&conf->hold_list) &&
5569                    ((conf->bypass_threshold &&
5570                      conf->bypass_count > conf->bypass_threshold) ||
5571                     atomic_read(&conf->pending_full_writes) == 0)) {
5572
5573                 list_for_each_entry(tmp, &conf->hold_list,  lru) {
5574                         if (conf->worker_cnt_per_group == 0 ||
5575                             group == ANY_GROUP ||
5576                             !cpu_online(tmp->cpu) ||
5577                             cpu_to_group(tmp->cpu) == group) {
5578                                 sh = tmp;
5579                                 break;
5580                         }
5581                 }
5582
5583                 if (sh) {
5584                         conf->bypass_count -= conf->bypass_threshold;
5585                         if (conf->bypass_count < 0)
5586                                 conf->bypass_count = 0;
5587                 }
5588                 wg = NULL;
5589         }
5590
5591         if (!sh) {
5592                 if (second_try)
5593                         return NULL;
5594                 second_try = true;
5595                 try_loprio = !try_loprio;
5596                 goto again;
5597         }
5598
5599         if (wg) {
5600                 wg->stripes_cnt--;
5601                 sh->group = NULL;
5602         }
5603         list_del_init(&sh->lru);
5604         BUG_ON(atomic_inc_return(&sh->count) != 1);
5605         return sh;
5606 }
5607
5608 struct raid5_plug_cb {
5609         struct blk_plug_cb      cb;
5610         struct list_head        list;
5611         struct list_head        temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5612 };
5613
5614 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5615 {
5616         struct raid5_plug_cb *cb = container_of(
5617                 blk_cb, struct raid5_plug_cb, cb);
5618         struct stripe_head *sh;
5619         struct mddev *mddev = cb->cb.data;
5620         struct r5conf *conf = mddev->private;
5621         int cnt = 0;
5622         int hash;
5623
5624         if (cb->list.next && !list_empty(&cb->list)) {
5625                 spin_lock_irq(&conf->device_lock);
5626                 while (!list_empty(&cb->list)) {
5627                         sh = list_first_entry(&cb->list, struct stripe_head, lru);
5628                         list_del_init(&sh->lru);
5629                         /*
5630                          * avoid race release_stripe_plug() sees
5631                          * STRIPE_ON_UNPLUG_LIST clear but the stripe
5632                          * is still in our list
5633                          */
5634                         smp_mb__before_atomic();
5635                         clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5636                         /*
5637                          * STRIPE_ON_RELEASE_LIST could be set here. In that
5638                          * case, the count is always > 1 here
5639                          */
5640                         hash = sh->hash_lock_index;
5641                         __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5642                         cnt++;
5643                 }
5644                 spin_unlock_irq(&conf->device_lock);
5645         }
5646         release_inactive_stripe_list(conf, cb->temp_inactive_list,
5647                                      NR_STRIPE_HASH_LOCKS);
5648         if (mddev->queue)
5649                 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5650         kfree(cb);
5651 }
5652
5653 static void release_stripe_plug(struct mddev *mddev,
5654                                 struct stripe_head *sh)
5655 {
5656         struct blk_plug_cb *blk_cb = blk_check_plugged(
5657                 raid5_unplug, mddev,
5658                 sizeof(struct raid5_plug_cb));
5659         struct raid5_plug_cb *cb;
5660
5661         if (!blk_cb) {
5662                 raid5_release_stripe(sh);
5663                 return;
5664         }
5665
5666         cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5667
5668         if (cb->list.next == NULL) {
5669                 int i;
5670                 INIT_LIST_HEAD(&cb->list);
5671                 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5672                         INIT_LIST_HEAD(cb->temp_inactive_list + i);
5673         }
5674
5675         if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5676                 list_add_tail(&sh->lru, &cb->list);
5677         else
5678                 raid5_release_stripe(sh);
5679 }
5680
5681 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5682 {
5683         struct r5conf *conf = mddev->private;
5684         sector_t logical_sector, last_sector;
5685         struct stripe_head *sh;
5686         int stripe_sectors;
5687
5688         if (mddev->reshape_position != MaxSector)
5689                 /* Skip discard while reshape is happening */
5690                 return;
5691
5692         logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5693         last_sector = bio_end_sector(bi);
5694
5695         bi->bi_next = NULL;
5696
5697         stripe_sectors = conf->chunk_sectors *
5698                 (conf->raid_disks - conf->max_degraded);
5699         logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5700                                                stripe_sectors);
5701         sector_div(last_sector, stripe_sectors);
5702
5703         logical_sector *= conf->chunk_sectors;
5704         last_sector *= conf->chunk_sectors;
5705
5706         for (; logical_sector < last_sector;
5707              logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5708                 DEFINE_WAIT(w);
5709                 int d;
5710         again:
5711                 sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5712                 prepare_to_wait(&conf->wait_for_overlap, &w,
5713                                 TASK_UNINTERRUPTIBLE);
5714                 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5715                 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5716                         raid5_release_stripe(sh);
5717                         schedule();
5718                         goto again;
5719                 }
5720                 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5721                 spin_lock_irq(&sh->stripe_lock);
5722                 for (d = 0; d < conf->raid_disks; d++) {
5723                         if (d == sh->pd_idx || d == sh->qd_idx)
5724                                 continue;
5725                         if (sh->dev[d].towrite || sh->dev[d].toread) {
5726                                 set_bit(R5_Overlap, &sh->dev[d].flags);
5727                                 spin_unlock_irq(&sh->stripe_lock);
5728                                 raid5_release_stripe(sh);
5729                                 schedule();
5730                                 goto again;
5731                         }
5732                 }
5733                 set_bit(STRIPE_DISCARD, &sh->state);
5734                 finish_wait(&conf->wait_for_overlap, &w);
5735                 sh->overwrite_disks = 0;
5736                 for (d = 0; d < conf->raid_disks; d++) {
5737                         if (d == sh->pd_idx || d == sh->qd_idx)
5738                                 continue;
5739                         sh->dev[d].towrite = bi;
5740                         set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5741                         bio_inc_remaining(bi);
5742                         md_write_inc(mddev, bi);
5743                         sh->overwrite_disks++;
5744                 }
5745                 spin_unlock_irq(&sh->stripe_lock);
5746                 if (conf->mddev->bitmap) {
5747                         for (d = 0;
5748                              d < conf->raid_disks - conf->max_degraded;
5749                              d++)
5750                                 md_bitmap_startwrite(mddev->bitmap,
5751                                                      sh->sector,
5752                                                      RAID5_STRIPE_SECTORS(conf),
5753                                                      0);
5754                         sh->bm_seq = conf->seq_flush + 1;
5755                         set_bit(STRIPE_BIT_DELAY, &sh->state);
5756                 }
5757
5758                 set_bit(STRIPE_HANDLE, &sh->state);
5759                 clear_bit(STRIPE_DELAYED, &sh->state);
5760                 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5761                         atomic_inc(&conf->preread_active_stripes);
5762                 release_stripe_plug(mddev, sh);
5763         }
5764
5765         bio_endio(bi);
5766 }
5767
5768 static bool raid5_make_request(struct mddev *mddev, struct bio * bi)
5769 {
5770         struct r5conf *conf = mddev->private;
5771         int dd_idx;
5772         sector_t new_sector;
5773         sector_t logical_sector, last_sector;
5774         struct stripe_head *sh;
5775         const int rw = bio_data_dir(bi);
5776         DEFINE_WAIT(w);
5777         bool do_prepare;
5778         bool do_flush = false;
5779
5780         if (unlikely(bi->bi_opf & REQ_PREFLUSH)) {
5781                 int ret = log_handle_flush_request(conf, bi);
5782
5783                 if (ret == 0)
5784                         return true;
5785                 if (ret == -ENODEV) {
5786                         if (md_flush_request(mddev, bi))
5787                                 return true;
5788                 }
5789                 /* ret == -EAGAIN, fallback */
5790                 /*
5791                  * if r5l_handle_flush_request() didn't clear REQ_PREFLUSH,
5792                  * we need to flush journal device
5793                  */
5794                 do_flush = bi->bi_opf & REQ_PREFLUSH;
5795         }
5796
5797         if (!md_write_start(mddev, bi))
5798                 return false;
5799         /*
5800          * If array is degraded, better not do chunk aligned read because
5801          * later we might have to read it again in order to reconstruct
5802          * data on failed drives.
5803          */
5804         if (rw == READ && mddev->degraded == 0 &&
5805             mddev->reshape_position == MaxSector) {
5806                 bi = chunk_aligned_read(mddev, bi);
5807                 if (!bi)
5808                         return true;
5809         }
5810
5811         if (unlikely(bio_op(bi) == REQ_OP_DISCARD)) {
5812                 make_discard_request(mddev, bi);
5813                 md_write_end(mddev);
5814                 return true;
5815         }
5816
5817         logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5818         last_sector = bio_end_sector(bi);
5819         bi->bi_next = NULL;
5820
5821         md_account_bio(mddev, &bi);
5822         prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5823         for (; logical_sector < last_sector; logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5824                 int previous;
5825                 int seq;
5826
5827                 do_prepare = false;
5828         retry:
5829                 seq = read_seqcount_begin(&conf->gen_lock);
5830                 previous = 0;
5831                 if (do_prepare)
5832                         prepare_to_wait(&conf->wait_for_overlap, &w,
5833                                 TASK_UNINTERRUPTIBLE);
5834                 if (unlikely(conf->reshape_progress != MaxSector)) {
5835                         /* spinlock is needed as reshape_progress may be
5836                          * 64bit on a 32bit platform, and so it might be
5837                          * possible to see a half-updated value
5838                          * Of course reshape_progress could change after
5839                          * the lock is dropped, so once we get a reference
5840                          * to the stripe that we think it is, we will have
5841                          * to check again.
5842                          */
5843                         spin_lock_irq(&conf->device_lock);
5844                         if (mddev->reshape_backwards
5845                             ? logical_sector < conf->reshape_progress
5846                             : logical_sector >= conf->reshape_progress) {
5847                                 previous = 1;
5848                         } else {
5849                                 if (mddev->reshape_backwards
5850                                     ? logical_sector < conf->reshape_safe
5851                                     : logical_sector >= conf->reshape_safe) {
5852                                         spin_unlock_irq(&conf->device_lock);
5853                                         schedule();
5854                                         do_prepare = true;
5855                                         goto retry;
5856                                 }
5857                         }
5858                         spin_unlock_irq(&conf->device_lock);
5859                 }
5860
5861                 new_sector = raid5_compute_sector(conf, logical_sector,
5862                                                   previous,
5863                                                   &dd_idx, NULL);
5864                 pr_debug("raid456: raid5_make_request, sector %llu logical %llu\n",
5865                         (unsigned long long)new_sector,
5866                         (unsigned long long)logical_sector);
5867
5868                 sh = raid5_get_active_stripe(conf, new_sector, previous,
5869                                        (bi->bi_opf & REQ_RAHEAD), 0);
5870                 if (sh) {
5871                         if (unlikely(previous)) {
5872                                 /* expansion might have moved on while waiting for a
5873                                  * stripe, so we must do the range check again.
5874                                  * Expansion could still move past after this
5875                                  * test, but as we are holding a reference to
5876                                  * 'sh', we know that if that happens,
5877                                  *  STRIPE_EXPANDING will get set and the expansion
5878                                  * won't proceed until we finish with the stripe.
5879                                  */
5880                                 int must_retry = 0;
5881                                 spin_lock_irq(&conf->device_lock);
5882                                 if (mddev->reshape_backwards
5883                                     ? logical_sector >= conf->reshape_progress
5884                                     : logical_sector < conf->reshape_progress)
5885                                         /* mismatch, need to try again */
5886                                         must_retry = 1;
5887                                 spin_unlock_irq(&conf->device_lock);
5888                                 if (must_retry) {
5889                                         raid5_release_stripe(sh);
5890                                         schedule();
5891                                         do_prepare = true;
5892                                         goto retry;
5893                                 }
5894                         }
5895                         if (read_seqcount_retry(&conf->gen_lock, seq)) {
5896                                 /* Might have got the wrong stripe_head
5897                                  * by accident
5898                                  */
5899                                 raid5_release_stripe(sh);
5900                                 goto retry;
5901                         }
5902
5903                         if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5904                             !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5905                                 /* Stripe is busy expanding or
5906                                  * add failed due to overlap.  Flush everything
5907                                  * and wait a while
5908                                  */
5909                                 md_wakeup_thread(mddev->thread);
5910                                 raid5_release_stripe(sh);
5911                                 schedule();
5912                                 do_prepare = true;
5913                                 goto retry;
5914                         }
5915                         if (do_flush) {
5916                                 set_bit(STRIPE_R5C_PREFLUSH, &sh->state);
5917                                 /* we only need flush for one stripe */
5918                                 do_flush = false;
5919                         }
5920
5921                         set_bit(STRIPE_HANDLE, &sh->state);
5922                         clear_bit(STRIPE_DELAYED, &sh->state);
5923                         if ((!sh->batch_head || sh == sh->batch_head) &&
5924                             (bi->bi_opf & REQ_SYNC) &&
5925                             !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5926                                 atomic_inc(&conf->preread_active_stripes);
5927                         release_stripe_plug(mddev, sh);
5928                 } else {
5929                         /* cannot get stripe for read-ahead, just give-up */
5930                         bi->bi_status = BLK_STS_IOERR;
5931                         break;
5932                 }
5933         }
5934         finish_wait(&conf->wait_for_overlap, &w);
5935
5936         if (rw == WRITE)
5937                 md_write_end(mddev);
5938         bio_endio(bi);
5939         return true;
5940 }
5941
5942 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5943
5944 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5945 {
5946         /* reshaping is quite different to recovery/resync so it is
5947          * handled quite separately ... here.
5948          *
5949          * On each call to sync_request, we gather one chunk worth of
5950          * destination stripes and flag them as expanding.
5951          * Then we find all the source stripes and request reads.
5952          * As the reads complete, handle_stripe will copy the data
5953          * into the destination stripe and release that stripe.
5954          */
5955         struct r5conf *conf = mddev->private;
5956         struct stripe_head *sh;
5957         struct md_rdev *rdev;
5958         sector_t first_sector, last_sector;
5959         int raid_disks = conf->previous_raid_disks;
5960         int data_disks = raid_disks - conf->max_degraded;
5961         int new_data_disks = conf->raid_disks - conf->max_degraded;
5962         int i;
5963         int dd_idx;
5964         sector_t writepos, readpos, safepos;
5965         sector_t stripe_addr;
5966         int reshape_sectors;
5967         struct list_head stripes;
5968         sector_t retn;
5969
5970         if (sector_nr == 0) {
5971                 /* If restarting in the middle, skip the initial sectors */
5972                 if (mddev->reshape_backwards &&
5973                     conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5974                         sector_nr = raid5_size(mddev, 0, 0)
5975                                 - conf->reshape_progress;
5976                 } else if (mddev->reshape_backwards &&
5977                            conf->reshape_progress == MaxSector) {
5978                         /* shouldn't happen, but just in case, finish up.*/
5979                         sector_nr = MaxSector;
5980                 } else if (!mddev->reshape_backwards &&
5981                            conf->reshape_progress > 0)
5982                         sector_nr = conf->reshape_progress;
5983                 sector_div(sector_nr, new_data_disks);
5984                 if (sector_nr) {
5985                         mddev->curr_resync_completed = sector_nr;
5986                         sysfs_notify_dirent_safe(mddev->sysfs_completed);
5987                         *skipped = 1;
5988                         retn = sector_nr;
5989                         goto finish;
5990                 }
5991         }
5992
5993         /* We need to process a full chunk at a time.
5994          * If old and new chunk sizes differ, we need to process the
5995          * largest of these
5996          */
5997
5998         reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5999
6000         /* We update the metadata at least every 10 seconds, or when
6001          * the data about to be copied would over-write the source of
6002          * the data at the front of the range.  i.e. one new_stripe
6003          * along from reshape_progress new_maps to after where
6004          * reshape_safe old_maps to
6005          */
6006         writepos = conf->reshape_progress;
6007         sector_div(writepos, new_data_disks);
6008         readpos = conf->reshape_progress;
6009         sector_div(readpos, data_disks);
6010         safepos = conf->reshape_safe;
6011         sector_div(safepos, data_disks);
6012         if (mddev->reshape_backwards) {
6013                 BUG_ON(writepos < reshape_sectors);
6014                 writepos -= reshape_sectors;
6015                 readpos += reshape_sectors;
6016                 safepos += reshape_sectors;
6017         } else {
6018                 writepos += reshape_sectors;
6019                 /* readpos and safepos are worst-case calculations.
6020                  * A negative number is overly pessimistic, and causes
6021                  * obvious problems for unsigned storage.  So clip to 0.
6022                  */
6023                 readpos -= min_t(sector_t, reshape_sectors, readpos);
6024                 safepos -= min_t(sector_t, reshape_sectors, safepos);
6025         }
6026
6027         /* Having calculated the 'writepos' possibly use it
6028          * to set 'stripe_addr' which is where we will write to.
6029          */
6030         if (mddev->reshape_backwards) {
6031                 BUG_ON(conf->reshape_progress == 0);
6032                 stripe_addr = writepos;
6033                 BUG_ON((mddev->dev_sectors &
6034                         ~((sector_t)reshape_sectors - 1))
6035                        - reshape_sectors - stripe_addr
6036                        != sector_nr);
6037         } else {
6038                 BUG_ON(writepos != sector_nr + reshape_sectors);
6039                 stripe_addr = sector_nr;
6040         }
6041
6042         /* 'writepos' is the most advanced device address we might write.
6043          * 'readpos' is the least advanced device address we might read.
6044          * 'safepos' is the least address recorded in the metadata as having
6045          *     been reshaped.
6046          * If there is a min_offset_diff, these are adjusted either by
6047          * increasing the safepos/readpos if diff is negative, or
6048          * increasing writepos if diff is positive.
6049          * If 'readpos' is then behind 'writepos', there is no way that we can
6050          * ensure safety in the face of a crash - that must be done by userspace
6051          * making a backup of the data.  So in that case there is no particular
6052          * rush to update metadata.
6053          * Otherwise if 'safepos' is behind 'writepos', then we really need to
6054          * update the metadata to advance 'safepos' to match 'readpos' so that
6055          * we can be safe in the event of a crash.
6056          * So we insist on updating metadata if safepos is behind writepos and
6057          * readpos is beyond writepos.
6058          * In any case, update the metadata every 10 seconds.
6059          * Maybe that number should be configurable, but I'm not sure it is
6060          * worth it.... maybe it could be a multiple of safemode_delay???
6061          */
6062         if (conf->min_offset_diff < 0) {
6063                 safepos += -conf->min_offset_diff;
6064                 readpos += -conf->min_offset_diff;
6065         } else
6066                 writepos += conf->min_offset_diff;
6067
6068         if ((mddev->reshape_backwards
6069              ? (safepos > writepos && readpos < writepos)
6070              : (safepos < writepos && readpos > writepos)) ||
6071             time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
6072                 /* Cannot proceed until we've updated the superblock... */
6073                 wait_event(conf->wait_for_overlap,
6074                            atomic_read(&conf->reshape_stripes)==0
6075                            || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6076                 if (atomic_read(&conf->reshape_stripes) != 0)
6077                         return 0;
6078                 mddev->reshape_position = conf->reshape_progress;
6079                 mddev->curr_resync_completed = sector_nr;
6080                 if (!mddev->reshape_backwards)
6081                         /* Can update recovery_offset */
6082                         rdev_for_each(rdev, mddev)
6083                                 if (rdev->raid_disk >= 0 &&
6084                                     !test_bit(Journal, &rdev->flags) &&
6085                                     !test_bit(In_sync, &rdev->flags) &&
6086                                     rdev->recovery_offset < sector_nr)
6087                                         rdev->recovery_offset = sector_nr;
6088
6089                 conf->reshape_checkpoint = jiffies;
6090                 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6091                 md_wakeup_thread(mddev->thread);
6092                 wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
6093                            test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6094                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6095                         return 0;
6096                 spin_lock_irq(&conf->device_lock);
6097                 conf->reshape_safe = mddev->reshape_position;
6098                 spin_unlock_irq(&conf->device_lock);
6099                 wake_up(&conf->wait_for_overlap);
6100                 sysfs_notify_dirent_safe(mddev->sysfs_completed);
6101         }
6102
6103         INIT_LIST_HEAD(&stripes);
6104         for (i = 0; i < reshape_sectors; i += RAID5_STRIPE_SECTORS(conf)) {
6105                 int j;
6106                 int skipped_disk = 0;
6107                 sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
6108                 set_bit(STRIPE_EXPANDING, &sh->state);
6109                 atomic_inc(&conf->reshape_stripes);
6110                 /* If any of this stripe is beyond the end of the old
6111                  * array, then we need to zero those blocks
6112                  */
6113                 for (j=sh->disks; j--;) {
6114                         sector_t s;
6115                         if (j == sh->pd_idx)
6116                                 continue;
6117                         if (conf->level == 6 &&
6118                             j == sh->qd_idx)
6119                                 continue;
6120                         s = raid5_compute_blocknr(sh, j, 0);
6121                         if (s < raid5_size(mddev, 0, 0)) {
6122                                 skipped_disk = 1;
6123                                 continue;
6124                         }
6125                         memset(page_address(sh->dev[j].page), 0, RAID5_STRIPE_SIZE(conf));
6126                         set_bit(R5_Expanded, &sh->dev[j].flags);
6127                         set_bit(R5_UPTODATE, &sh->dev[j].flags);
6128                 }
6129                 if (!skipped_disk) {
6130                         set_bit(STRIPE_EXPAND_READY, &sh->state);
6131                         set_bit(STRIPE_HANDLE, &sh->state);
6132                 }
6133                 list_add(&sh->lru, &stripes);
6134         }
6135         spin_lock_irq(&conf->device_lock);
6136         if (mddev->reshape_backwards)
6137                 conf->reshape_progress -= reshape_sectors * new_data_disks;
6138         else
6139                 conf->reshape_progress += reshape_sectors * new_data_disks;
6140         spin_unlock_irq(&conf->device_lock);
6141         /* Ok, those stripe are ready. We can start scheduling
6142          * reads on the source stripes.
6143          * The source stripes are determined by mapping the first and last
6144          * block on the destination stripes.
6145          */
6146         first_sector =
6147                 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
6148                                      1, &dd_idx, NULL);
6149         last_sector =
6150                 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
6151                                             * new_data_disks - 1),
6152                                      1, &dd_idx, NULL);
6153         if (last_sector >= mddev->dev_sectors)
6154                 last_sector = mddev->dev_sectors - 1;
6155         while (first_sector <= last_sector) {
6156                 sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
6157                 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
6158                 set_bit(STRIPE_HANDLE, &sh->state);
6159                 raid5_release_stripe(sh);
6160                 first_sector += RAID5_STRIPE_SECTORS(conf);
6161         }
6162         /* Now that the sources are clearly marked, we can release
6163          * the destination stripes
6164          */
6165         while (!list_empty(&stripes)) {
6166                 sh = list_entry(stripes.next, struct stripe_head, lru);
6167                 list_del_init(&sh->lru);
6168                 raid5_release_stripe(sh);
6169         }
6170         /* If this takes us to the resync_max point where we have to pause,
6171          * then we need to write out the superblock.
6172          */
6173         sector_nr += reshape_sectors;
6174         retn = reshape_sectors;
6175 finish:
6176         if (mddev->curr_resync_completed > mddev->resync_max ||
6177             (sector_nr - mddev->curr_resync_completed) * 2
6178             >= mddev->resync_max - mddev->curr_resync_completed) {
6179                 /* Cannot proceed until we've updated the superblock... */
6180                 wait_event(conf->wait_for_overlap,
6181                            atomic_read(&conf->reshape_stripes) == 0
6182                            || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6183                 if (atomic_read(&conf->reshape_stripes) != 0)
6184                         goto ret;
6185                 mddev->reshape_position = conf->reshape_progress;
6186                 mddev->curr_resync_completed = sector_nr;
6187                 if (!mddev->reshape_backwards)
6188                         /* Can update recovery_offset */
6189                         rdev_for_each(rdev, mddev)
6190                                 if (rdev->raid_disk >= 0 &&
6191                                     !test_bit(Journal, &rdev->flags) &&
6192                                     !test_bit(In_sync, &rdev->flags) &&
6193                                     rdev->recovery_offset < sector_nr)
6194                                         rdev->recovery_offset = sector_nr;
6195                 conf->reshape_checkpoint = jiffies;
6196                 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6197                 md_wakeup_thread(mddev->thread);
6198                 wait_event(mddev->sb_wait,
6199                            !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)
6200                            || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6201                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6202                         goto ret;
6203                 spin_lock_irq(&conf->device_lock);
6204                 conf->reshape_safe = mddev->reshape_position;
6205                 spin_unlock_irq(&conf->device_lock);
6206                 wake_up(&conf->wait_for_overlap);
6207                 sysfs_notify_dirent_safe(mddev->sysfs_completed);
6208         }
6209 ret:
6210         return retn;
6211 }
6212
6213 static inline sector_t raid5_sync_request(struct mddev *mddev, sector_t sector_nr,
6214                                           int *skipped)
6215 {
6216         struct r5conf *conf = mddev->private;
6217         struct stripe_head *sh;
6218         sector_t max_sector = mddev->dev_sectors;
6219         sector_t sync_blocks;
6220         int still_degraded = 0;
6221         int i;
6222
6223         if (sector_nr >= max_sector) {
6224                 /* just being told to finish up .. nothing much to do */
6225
6226                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
6227                         end_reshape(conf);
6228                         return 0;
6229                 }
6230
6231                 if (mddev->curr_resync < max_sector) /* aborted */
6232                         md_bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
6233                                            &sync_blocks, 1);
6234                 else /* completed sync */
6235                         conf->fullsync = 0;
6236                 md_bitmap_close_sync(mddev->bitmap);
6237
6238                 return 0;
6239         }
6240
6241         /* Allow raid5_quiesce to complete */
6242         wait_event(conf->wait_for_overlap, conf->quiesce != 2);
6243
6244         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6245                 return reshape_request(mddev, sector_nr, skipped);
6246
6247         /* No need to check resync_max as we never do more than one
6248          * stripe, and as resync_max will always be on a chunk boundary,
6249          * if the check in md_do_sync didn't fire, there is no chance
6250          * of overstepping resync_max here
6251          */
6252
6253         /* if there is too many failed drives and we are trying
6254          * to resync, then assert that we are finished, because there is
6255          * nothing we can do.
6256          */
6257         if (mddev->degraded >= conf->max_degraded &&
6258             test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6259                 sector_t rv = mddev->dev_sectors - sector_nr;
6260                 *skipped = 1;
6261                 return rv;
6262         }
6263         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
6264             !conf->fullsync &&
6265             !md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
6266             sync_blocks >= RAID5_STRIPE_SECTORS(conf)) {
6267                 /* we can skip this block, and probably more */
6268                 do_div(sync_blocks, RAID5_STRIPE_SECTORS(conf));
6269                 *skipped = 1;
6270                 /* keep things rounded to whole stripes */
6271                 return sync_blocks * RAID5_STRIPE_SECTORS(conf);
6272         }
6273
6274         md_bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
6275
6276         sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
6277         if (sh == NULL) {
6278                 sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
6279                 /* make sure we don't swamp the stripe cache if someone else
6280                  * is trying to get access
6281                  */
6282                 schedule_timeout_uninterruptible(1);
6283         }
6284         /* Need to check if array will still be degraded after recovery/resync
6285          * Note in case of > 1 drive failures it's possible we're rebuilding
6286          * one drive while leaving another faulty drive in array.
6287          */
6288         rcu_read_lock();
6289         for (i = 0; i < conf->raid_disks; i++) {
6290                 struct md_rdev *rdev = READ_ONCE(conf->disks[i].rdev);
6291
6292                 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
6293                         still_degraded = 1;
6294         }
6295         rcu_read_unlock();
6296
6297         md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
6298
6299         set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
6300         set_bit(STRIPE_HANDLE, &sh->state);
6301
6302         raid5_release_stripe(sh);
6303
6304         return RAID5_STRIPE_SECTORS(conf);
6305 }
6306
6307 static int  retry_aligned_read(struct r5conf *conf, struct bio *raid_bio,
6308                                unsigned int offset)
6309 {
6310         /* We may not be able to submit a whole bio at once as there
6311          * may not be enough stripe_heads available.
6312          * We cannot pre-allocate enough stripe_heads as we may need
6313          * more than exist in the cache (if we allow ever large chunks).
6314          * So we do one stripe head at a time and record in
6315          * ->bi_hw_segments how many have been done.
6316          *
6317          * We *know* that this entire raid_bio is in one chunk, so
6318          * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
6319          */
6320         struct stripe_head *sh;
6321         int dd_idx;
6322         sector_t sector, logical_sector, last_sector;
6323         int scnt = 0;
6324         int handled = 0;
6325
6326         logical_sector = raid_bio->bi_iter.bi_sector &
6327                 ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
6328         sector = raid5_compute_sector(conf, logical_sector,
6329                                       0, &dd_idx, NULL);
6330         last_sector = bio_end_sector(raid_bio);
6331
6332         for (; logical_sector < last_sector;
6333              logical_sector += RAID5_STRIPE_SECTORS(conf),
6334                      sector += RAID5_STRIPE_SECTORS(conf),
6335                      scnt++) {
6336
6337                 if (scnt < offset)
6338                         /* already done this stripe */
6339                         continue;
6340
6341                 sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
6342
6343                 if (!sh) {
6344                         /* failed to get a stripe - must wait */
6345                         conf->retry_read_aligned = raid_bio;
6346                         conf->retry_read_offset = scnt;
6347                         return handled;
6348                 }
6349
6350                 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
6351                         raid5_release_stripe(sh);
6352                         conf->retry_read_aligned = raid_bio;
6353                         conf->retry_read_offset = scnt;
6354                         return handled;
6355                 }
6356
6357                 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
6358                 handle_stripe(sh);
6359                 raid5_release_stripe(sh);
6360                 handled++;
6361         }
6362
6363         bio_endio(raid_bio);
6364
6365         if (atomic_dec_and_test(&conf->active_aligned_reads))
6366                 wake_up(&conf->wait_for_quiescent);
6367         return handled;
6368 }
6369
6370 static int handle_active_stripes(struct r5conf *conf, int group,
6371                                  struct r5worker *worker,
6372                                  struct list_head *temp_inactive_list)
6373                 __releases(&conf->device_lock)
6374                 __acquires(&conf->device_lock)
6375 {
6376         struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
6377         int i, batch_size = 0, hash;
6378         bool release_inactive = false;
6379
6380         while (batch_size < MAX_STRIPE_BATCH &&
6381                         (sh = __get_priority_stripe(conf, group)) != NULL)
6382                 batch[batch_size++] = sh;
6383
6384         if (batch_size == 0) {
6385                 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6386                         if (!list_empty(temp_inactive_list + i))
6387                                 break;
6388                 if (i == NR_STRIPE_HASH_LOCKS) {
6389                         spin_unlock_irq(&conf->device_lock);
6390                         log_flush_stripe_to_raid(conf);
6391                         spin_lock_irq(&conf->device_lock);
6392                         return batch_size;
6393                 }
6394                 release_inactive = true;
6395         }
6396         spin_unlock_irq(&conf->device_lock);
6397
6398         release_inactive_stripe_list(conf, temp_inactive_list,
6399                                      NR_STRIPE_HASH_LOCKS);
6400
6401         r5l_flush_stripe_to_raid(conf->log);
6402         if (release_inactive) {
6403                 spin_lock_irq(&conf->device_lock);
6404                 return 0;
6405         }
6406
6407         for (i = 0; i < batch_size; i++)
6408                 handle_stripe(batch[i]);
6409         log_write_stripe_run(conf);
6410
6411         cond_resched();
6412
6413         spin_lock_irq(&conf->device_lock);
6414         for (i = 0; i < batch_size; i++) {
6415                 hash = batch[i]->hash_lock_index;
6416                 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
6417         }
6418         return batch_size;
6419 }
6420
6421 static void raid5_do_work(struct work_struct *work)
6422 {
6423         struct r5worker *worker = container_of(work, struct r5worker, work);
6424         struct r5worker_group *group = worker->group;
6425         struct r5conf *conf = group->conf;
6426         struct mddev *mddev = conf->mddev;
6427         int group_id = group - conf->worker_groups;
6428         int handled;
6429         struct blk_plug plug;
6430
6431         pr_debug("+++ raid5worker active\n");
6432
6433         blk_start_plug(&plug);
6434         handled = 0;
6435         spin_lock_irq(&conf->device_lock);
6436         while (1) {
6437                 int batch_size, released;
6438
6439                 released = release_stripe_list(conf, worker->temp_inactive_list);
6440
6441                 batch_size = handle_active_stripes(conf, group_id, worker,
6442                                                    worker->temp_inactive_list);
6443                 worker->working = false;
6444                 if (!batch_size && !released)
6445                         break;
6446                 handled += batch_size;
6447                 wait_event_lock_irq(mddev->sb_wait,
6448                         !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6449                         conf->device_lock);
6450         }
6451         pr_debug("%d stripes handled\n", handled);
6452
6453         spin_unlock_irq(&conf->device_lock);
6454
6455         flush_deferred_bios(conf);
6456
6457         r5l_flush_stripe_to_raid(conf->log);
6458
6459         async_tx_issue_pending_all();
6460         blk_finish_plug(&plug);
6461
6462         pr_debug("--- raid5worker inactive\n");
6463 }
6464
6465 /*
6466  * This is our raid5 kernel thread.
6467  *
6468  * We scan the hash table for stripes which can be handled now.
6469  * During the scan, completed stripes are saved for us by the interrupt
6470  * handler, so that they will not have to wait for our next wakeup.
6471  */
6472 static void raid5d(struct md_thread *thread)
6473 {
6474         struct mddev *mddev = thread->mddev;
6475         struct r5conf *conf = mddev->private;
6476         int handled;
6477         struct blk_plug plug;
6478
6479         pr_debug("+++ raid5d active\n");
6480
6481         md_check_recovery(mddev);
6482
6483         blk_start_plug(&plug);
6484         handled = 0;
6485         spin_lock_irq(&conf->device_lock);
6486         while (1) {
6487                 struct bio *bio;
6488                 int batch_size, released;
6489                 unsigned int offset;
6490
6491                 released = release_stripe_list(conf, conf->temp_inactive_list);
6492                 if (released)
6493                         clear_bit(R5_DID_ALLOC, &conf->cache_state);
6494
6495                 if (
6496                     !list_empty(&conf->bitmap_list)) {
6497                         /* Now is a good time to flush some bitmap updates */
6498                         conf->seq_flush++;
6499                         spin_unlock_irq(&conf->device_lock);
6500                         md_bitmap_unplug(mddev->bitmap);
6501                         spin_lock_irq(&conf->device_lock);
6502                         conf->seq_write = conf->seq_flush;
6503                         activate_bit_delay(conf, conf->temp_inactive_list);
6504                 }
6505                 raid5_activate_delayed(conf);
6506
6507                 while ((bio = remove_bio_from_retry(conf, &offset))) {
6508                         int ok;
6509                         spin_unlock_irq(&conf->device_lock);
6510                         ok = retry_aligned_read(conf, bio, offset);
6511                         spin_lock_irq(&conf->device_lock);
6512                         if (!ok)
6513                                 break;
6514                         handled++;
6515                 }
6516
6517                 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
6518                                                    conf->temp_inactive_list);
6519                 if (!batch_size && !released)
6520                         break;
6521                 handled += batch_size;
6522
6523                 if (mddev->sb_flags & ~(1 << MD_SB_CHANGE_PENDING)) {
6524                         spin_unlock_irq(&conf->device_lock);
6525                         md_check_recovery(mddev);
6526                         spin_lock_irq(&conf->device_lock);
6527
6528                         /*
6529                          * Waiting on MD_SB_CHANGE_PENDING below may deadlock
6530                          * seeing md_check_recovery() is needed to clear
6531                          * the flag when using mdmon.
6532                          */
6533                         continue;
6534                 }
6535
6536                 wait_event_lock_irq(mddev->sb_wait,
6537                         !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6538                         conf->device_lock);
6539         }
6540         pr_debug("%d stripes handled\n", handled);
6541
6542         spin_unlock_irq(&conf->device_lock);
6543         if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
6544             mutex_trylock(&conf->cache_size_mutex)) {
6545                 grow_one_stripe(conf, __GFP_NOWARN);
6546                 /* Set flag even if allocation failed.  This helps
6547                  * slow down allocation requests when mem is short
6548                  */
6549                 set_bit(R5_DID_ALLOC, &conf->cache_state);
6550                 mutex_unlock(&conf->cache_size_mutex);
6551         }
6552
6553         flush_deferred_bios(conf);
6554
6555         r5l_flush_stripe_to_raid(conf->log);
6556
6557         async_tx_issue_pending_all();
6558         blk_finish_plug(&plug);
6559
6560         pr_debug("--- raid5d inactive\n");
6561 }
6562
6563 static ssize_t
6564 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
6565 {
6566         struct r5conf *conf;
6567         int ret = 0;
6568         spin_lock(&mddev->lock);
6569         conf = mddev->private;
6570         if (conf)
6571                 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
6572         spin_unlock(&mddev->lock);
6573         return ret;
6574 }
6575
6576 int
6577 raid5_set_cache_size(struct mddev *mddev, int size)
6578 {
6579         int result = 0;
6580         struct r5conf *conf = mddev->private;
6581
6582         if (size <= 16 || size > 32768)
6583                 return -EINVAL;
6584
6585         conf->min_nr_stripes = size;
6586         mutex_lock(&conf->cache_size_mutex);
6587         while (size < conf->max_nr_stripes &&
6588                drop_one_stripe(conf))
6589                 ;
6590         mutex_unlock(&conf->cache_size_mutex);
6591
6592         md_allow_write(mddev);
6593
6594         mutex_lock(&conf->cache_size_mutex);
6595         while (size > conf->max_nr_stripes)
6596                 if (!grow_one_stripe(conf, GFP_KERNEL)) {
6597                         conf->min_nr_stripes = conf->max_nr_stripes;
6598                         result = -ENOMEM;
6599                         break;
6600                 }
6601         mutex_unlock(&conf->cache_size_mutex);
6602
6603         return result;
6604 }
6605 EXPORT_SYMBOL(raid5_set_cache_size);
6606
6607 static ssize_t
6608 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6609 {
6610         struct r5conf *conf;
6611         unsigned long new;
6612         int err;
6613
6614         if (len >= PAGE_SIZE)
6615                 return -EINVAL;
6616         if (kstrtoul(page, 10, &new))
6617                 return -EINVAL;
6618         err = mddev_lock(mddev);
6619         if (err)
6620                 return err;
6621         conf = mddev->private;
6622         if (!conf)
6623                 err = -ENODEV;
6624         else
6625                 err = raid5_set_cache_size(mddev, new);
6626         mddev_unlock(mddev);
6627
6628         return err ?: len;
6629 }
6630
6631 static struct md_sysfs_entry
6632 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6633                                 raid5_show_stripe_cache_size,
6634                                 raid5_store_stripe_cache_size);
6635
6636 static ssize_t
6637 raid5_show_rmw_level(struct mddev  *mddev, char *page)
6638 {
6639         struct r5conf *conf = mddev->private;
6640         if (conf)
6641                 return sprintf(page, "%d\n", conf->rmw_level);
6642         else
6643                 return 0;
6644 }
6645
6646 static ssize_t
6647 raid5_store_rmw_level(struct mddev  *mddev, const char *page, size_t len)
6648 {
6649         struct r5conf *conf = mddev->private;
6650         unsigned long new;
6651
6652         if (!conf)
6653                 return -ENODEV;
6654
6655         if (len >= PAGE_SIZE)
6656                 return -EINVAL;
6657
6658         if (kstrtoul(page, 10, &new))
6659                 return -EINVAL;
6660
6661         if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6662                 return -EINVAL;
6663
6664         if (new != PARITY_DISABLE_RMW &&
6665             new != PARITY_ENABLE_RMW &&
6666             new != PARITY_PREFER_RMW)
6667                 return -EINVAL;
6668
6669         conf->rmw_level = new;
6670         return len;
6671 }
6672
6673 static struct md_sysfs_entry
6674 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6675                          raid5_show_rmw_level,
6676                          raid5_store_rmw_level);
6677
6678 static ssize_t
6679 raid5_show_stripe_size(struct mddev  *mddev, char *page)
6680 {
6681         struct r5conf *conf;
6682         int ret = 0;
6683
6684         spin_lock(&mddev->lock);
6685         conf = mddev->private;
6686         if (conf)
6687                 ret = sprintf(page, "%lu\n", RAID5_STRIPE_SIZE(conf));
6688         spin_unlock(&mddev->lock);
6689         return ret;
6690 }
6691
6692 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
6693 static ssize_t
6694 raid5_store_stripe_size(struct mddev  *mddev, const char *page, size_t len)
6695 {
6696         struct r5conf *conf;
6697         unsigned long new;
6698         int err;
6699         int size;
6700
6701         if (len >= PAGE_SIZE)
6702                 return -EINVAL;
6703         if (kstrtoul(page, 10, &new))
6704                 return -EINVAL;
6705
6706         /*
6707          * The value should not be bigger than PAGE_SIZE. It requires to
6708          * be multiple of DEFAULT_STRIPE_SIZE and the value should be power
6709          * of two.
6710          */
6711         if (new % DEFAULT_STRIPE_SIZE != 0 ||
6712                         new > PAGE_SIZE || new == 0 ||
6713                         new != roundup_pow_of_two(new))
6714                 return -EINVAL;
6715
6716         err = mddev_lock(mddev);
6717         if (err)
6718                 return err;
6719
6720         conf = mddev->private;
6721         if (!conf) {
6722                 err = -ENODEV;
6723                 goto out_unlock;
6724         }
6725
6726         if (new == conf->stripe_size)
6727                 goto out_unlock;
6728
6729         pr_debug("md/raid: change stripe_size from %lu to %lu\n",
6730                         conf->stripe_size, new);
6731
6732         if (mddev->sync_thread ||
6733                 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6734                 mddev->reshape_position != MaxSector ||
6735                 mddev->sysfs_active) {
6736                 err = -EBUSY;
6737                 goto out_unlock;
6738         }
6739
6740         mddev_suspend(mddev);
6741         mutex_lock(&conf->cache_size_mutex);
6742         size = conf->max_nr_stripes;
6743
6744         shrink_stripes(conf);
6745
6746         conf->stripe_size = new;
6747         conf->stripe_shift = ilog2(new) - 9;
6748         conf->stripe_sectors = new >> 9;
6749         if (grow_stripes(conf, size)) {
6750                 pr_warn("md/raid:%s: couldn't allocate buffers\n",
6751                                 mdname(mddev));
6752                 err = -ENOMEM;
6753         }
6754         mutex_unlock(&conf->cache_size_mutex);
6755         mddev_resume(mddev);
6756
6757 out_unlock:
6758         mddev_unlock(mddev);
6759         return err ?: len;
6760 }
6761
6762 static struct md_sysfs_entry
6763 raid5_stripe_size = __ATTR(stripe_size, 0644,
6764                          raid5_show_stripe_size,
6765                          raid5_store_stripe_size);
6766 #else
6767 static struct md_sysfs_entry
6768 raid5_stripe_size = __ATTR(stripe_size, 0444,
6769                          raid5_show_stripe_size,
6770                          NULL);
6771 #endif
6772
6773 static ssize_t
6774 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6775 {
6776         struct r5conf *conf;
6777         int ret = 0;
6778         spin_lock(&mddev->lock);
6779         conf = mddev->private;
6780         if (conf)
6781                 ret = sprintf(page, "%d\n", conf->bypass_threshold);
6782         spin_unlock(&mddev->lock);
6783         return ret;
6784 }
6785
6786 static ssize_t
6787 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6788 {
6789         struct r5conf *conf;
6790         unsigned long new;
6791         int err;
6792
6793         if (len >= PAGE_SIZE)
6794                 return -EINVAL;
6795         if (kstrtoul(page, 10, &new))
6796                 return -EINVAL;
6797
6798         err = mddev_lock(mddev);
6799         if (err)
6800                 return err;
6801         conf = mddev->private;
6802         if (!conf)
6803                 err = -ENODEV;
6804         else if (new > conf->min_nr_stripes)
6805                 err = -EINVAL;
6806         else
6807                 conf->bypass_threshold = new;
6808         mddev_unlock(mddev);
6809         return err ?: len;
6810 }
6811
6812 static struct md_sysfs_entry
6813 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6814                                         S_IRUGO | S_IWUSR,
6815                                         raid5_show_preread_threshold,
6816                                         raid5_store_preread_threshold);
6817
6818 static ssize_t
6819 raid5_show_skip_copy(struct mddev *mddev, char *page)
6820 {
6821         struct r5conf *conf;
6822         int ret = 0;
6823         spin_lock(&mddev->lock);
6824         conf = mddev->private;
6825         if (conf)
6826                 ret = sprintf(page, "%d\n", conf->skip_copy);
6827         spin_unlock(&mddev->lock);
6828         return ret;
6829 }
6830
6831 static ssize_t
6832 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6833 {
6834         struct r5conf *conf;
6835         unsigned long new;
6836         int err;
6837
6838         if (len >= PAGE_SIZE)
6839                 return -EINVAL;
6840         if (kstrtoul(page, 10, &new))
6841                 return -EINVAL;
6842         new = !!new;
6843
6844         err = mddev_lock(mddev);
6845         if (err)
6846                 return err;
6847         conf = mddev->private;
6848         if (!conf)
6849                 err = -ENODEV;
6850         else if (new != conf->skip_copy) {
6851                 struct request_queue *q = mddev->queue;
6852
6853                 mddev_suspend(mddev);
6854                 conf->skip_copy = new;
6855                 if (new)
6856                         blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, q);
6857                 else
6858                         blk_queue_flag_clear(QUEUE_FLAG_STABLE_WRITES, q);
6859                 mddev_resume(mddev);
6860         }
6861         mddev_unlock(mddev);
6862         return err ?: len;
6863 }
6864
6865 static struct md_sysfs_entry
6866 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6867                                         raid5_show_skip_copy,
6868                                         raid5_store_skip_copy);
6869
6870 static ssize_t
6871 stripe_cache_active_show(struct mddev *mddev, char *page)
6872 {
6873         struct r5conf *conf = mddev->private;
6874         if (conf)
6875                 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6876         else
6877                 return 0;
6878 }
6879
6880 static struct md_sysfs_entry
6881 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6882
6883 static ssize_t
6884 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6885 {
6886         struct r5conf *conf;
6887         int ret = 0;
6888         spin_lock(&mddev->lock);
6889         conf = mddev->private;
6890         if (conf)
6891                 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6892         spin_unlock(&mddev->lock);
6893         return ret;
6894 }
6895
6896 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6897                                int *group_cnt,
6898                                struct r5worker_group **worker_groups);
6899 static ssize_t
6900 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6901 {
6902         struct r5conf *conf;
6903         unsigned int new;
6904         int err;
6905         struct r5worker_group *new_groups, *old_groups;
6906         int group_cnt;
6907
6908         if (len >= PAGE_SIZE)
6909                 return -EINVAL;
6910         if (kstrtouint(page, 10, &new))
6911                 return -EINVAL;
6912         /* 8192 should be big enough */
6913         if (new > 8192)
6914                 return -EINVAL;
6915
6916         err = mddev_lock(mddev);
6917         if (err)
6918                 return err;
6919         conf = mddev->private;
6920         if (!conf)
6921                 err = -ENODEV;
6922         else if (new != conf->worker_cnt_per_group) {
6923                 mddev_suspend(mddev);
6924
6925                 old_groups = conf->worker_groups;
6926                 if (old_groups)
6927                         flush_workqueue(raid5_wq);
6928
6929                 err = alloc_thread_groups(conf, new, &group_cnt, &new_groups);
6930                 if (!err) {
6931                         spin_lock_irq(&conf->device_lock);
6932                         conf->group_cnt = group_cnt;
6933                         conf->worker_cnt_per_group = new;
6934                         conf->worker_groups = new_groups;
6935                         spin_unlock_irq(&conf->device_lock);
6936
6937                         if (old_groups)
6938                                 kfree(old_groups[0].workers);
6939                         kfree(old_groups);
6940                 }
6941                 mddev_resume(mddev);
6942         }
6943         mddev_unlock(mddev);
6944
6945         return err ?: len;
6946 }
6947
6948 static struct md_sysfs_entry
6949 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6950                                 raid5_show_group_thread_cnt,
6951                                 raid5_store_group_thread_cnt);
6952
6953 static struct attribute *raid5_attrs[] =  {
6954         &raid5_stripecache_size.attr,
6955         &raid5_stripecache_active.attr,
6956         &raid5_preread_bypass_threshold.attr,
6957         &raid5_group_thread_cnt.attr,
6958         &raid5_skip_copy.attr,
6959         &raid5_rmw_level.attr,
6960         &raid5_stripe_size.attr,
6961         &r5c_journal_mode.attr,
6962         &ppl_write_hint.attr,
6963         NULL,
6964 };
6965 static const struct attribute_group raid5_attrs_group = {
6966         .name = NULL,
6967         .attrs = raid5_attrs,
6968 };
6969
6970 static int alloc_thread_groups(struct r5conf *conf, int cnt, int *group_cnt,
6971                                struct r5worker_group **worker_groups)
6972 {
6973         int i, j, k;
6974         ssize_t size;
6975         struct r5worker *workers;
6976
6977         if (cnt == 0) {
6978                 *group_cnt = 0;
6979                 *worker_groups = NULL;
6980                 return 0;
6981         }
6982         *group_cnt = num_possible_nodes();
6983         size = sizeof(struct r5worker) * cnt;
6984         workers = kcalloc(size, *group_cnt, GFP_NOIO);
6985         *worker_groups = kcalloc(*group_cnt, sizeof(struct r5worker_group),
6986                                  GFP_NOIO);
6987         if (!*worker_groups || !workers) {
6988                 kfree(workers);
6989                 kfree(*worker_groups);
6990                 return -ENOMEM;
6991         }
6992
6993         for (i = 0; i < *group_cnt; i++) {
6994                 struct r5worker_group *group;
6995
6996                 group = &(*worker_groups)[i];
6997                 INIT_LIST_HEAD(&group->handle_list);
6998                 INIT_LIST_HEAD(&group->loprio_list);
6999                 group->conf = conf;
7000                 group->workers = workers + i * cnt;
7001
7002                 for (j = 0; j < cnt; j++) {
7003                         struct r5worker *worker = group->workers + j;
7004                         worker->group = group;
7005                         INIT_WORK(&worker->work, raid5_do_work);
7006
7007                         for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
7008                                 INIT_LIST_HEAD(worker->temp_inactive_list + k);
7009                 }
7010         }
7011
7012         return 0;
7013 }
7014
7015 static void free_thread_groups(struct r5conf *conf)
7016 {
7017         if (conf->worker_groups)
7018                 kfree(conf->worker_groups[0].workers);
7019         kfree(conf->worker_groups);
7020         conf->worker_groups = NULL;
7021 }
7022
7023 static sector_t
7024 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
7025 {
7026         struct r5conf *conf = mddev->private;
7027
7028         if (!sectors)
7029                 sectors = mddev->dev_sectors;
7030         if (!raid_disks)
7031                 /* size is defined by the smallest of previous and new size */
7032                 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
7033
7034         sectors &= ~((sector_t)conf->chunk_sectors - 1);
7035         sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
7036         return sectors * (raid_disks - conf->max_degraded);
7037 }
7038
7039 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7040 {
7041         safe_put_page(percpu->spare_page);
7042         percpu->spare_page = NULL;
7043         kvfree(percpu->scribble);
7044         percpu->scribble = NULL;
7045 }
7046
7047 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7048 {
7049         if (conf->level == 6 && !percpu->spare_page) {
7050                 percpu->spare_page = alloc_page(GFP_KERNEL);
7051                 if (!percpu->spare_page)
7052                         return -ENOMEM;
7053         }
7054
7055         if (scribble_alloc(percpu,
7056                            max(conf->raid_disks,
7057                                conf->previous_raid_disks),
7058                            max(conf->chunk_sectors,
7059                                conf->prev_chunk_sectors)
7060                            / RAID5_STRIPE_SECTORS(conf))) {
7061                 free_scratch_buffer(conf, percpu);
7062                 return -ENOMEM;
7063         }
7064
7065         return 0;
7066 }
7067
7068 static int raid456_cpu_dead(unsigned int cpu, struct hlist_node *node)
7069 {
7070         struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7071
7072         free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
7073         return 0;
7074 }
7075
7076 static void raid5_free_percpu(struct r5conf *conf)
7077 {
7078         if (!conf->percpu)
7079                 return;
7080
7081         cpuhp_state_remove_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7082         free_percpu(conf->percpu);
7083 }
7084
7085 static void free_conf(struct r5conf *conf)
7086 {
7087         int i;
7088
7089         log_exit(conf);
7090
7091         unregister_shrinker(&conf->shrinker);
7092         free_thread_groups(conf);
7093         shrink_stripes(conf);
7094         raid5_free_percpu(conf);
7095         for (i = 0; i < conf->pool_size; i++)
7096                 if (conf->disks[i].extra_page)
7097                         put_page(conf->disks[i].extra_page);
7098         kfree(conf->disks);
7099         bioset_exit(&conf->bio_split);
7100         kfree(conf->stripe_hashtbl);
7101         kfree(conf->pending_data);
7102         kfree(conf);
7103 }
7104
7105 static int raid456_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
7106 {
7107         struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7108         struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
7109
7110         if (alloc_scratch_buffer(conf, percpu)) {
7111                 pr_warn("%s: failed memory allocation for cpu%u\n",
7112                         __func__, cpu);
7113                 return -ENOMEM;
7114         }
7115         spin_lock_init(&per_cpu_ptr(conf->percpu, cpu)->lock);
7116         return 0;
7117 }
7118
7119 static int raid5_alloc_percpu(struct r5conf *conf)
7120 {
7121         int err = 0;
7122
7123         conf->percpu = alloc_percpu(struct raid5_percpu);
7124         if (!conf->percpu)
7125                 return -ENOMEM;
7126
7127         err = cpuhp_state_add_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7128         if (!err) {
7129                 conf->scribble_disks = max(conf->raid_disks,
7130                         conf->previous_raid_disks);
7131                 conf->scribble_sectors = max(conf->chunk_sectors,
7132                         conf->prev_chunk_sectors);
7133         }
7134         return err;
7135 }
7136
7137 static unsigned long raid5_cache_scan(struct shrinker *shrink,
7138                                       struct shrink_control *sc)
7139 {
7140         struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7141         unsigned long ret = SHRINK_STOP;
7142
7143         if (mutex_trylock(&conf->cache_size_mutex)) {
7144                 ret= 0;
7145                 while (ret < sc->nr_to_scan &&
7146                        conf->max_nr_stripes > conf->min_nr_stripes) {
7147                         if (drop_one_stripe(conf) == 0) {
7148                                 ret = SHRINK_STOP;
7149                                 break;
7150                         }
7151                         ret++;
7152                 }
7153                 mutex_unlock(&conf->cache_size_mutex);
7154         }
7155         return ret;
7156 }
7157
7158 static unsigned long raid5_cache_count(struct shrinker *shrink,
7159                                        struct shrink_control *sc)
7160 {
7161         struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7162
7163         if (conf->max_nr_stripes < conf->min_nr_stripes)
7164                 /* unlikely, but not impossible */
7165                 return 0;
7166         return conf->max_nr_stripes - conf->min_nr_stripes;
7167 }
7168
7169 static struct r5conf *setup_conf(struct mddev *mddev)
7170 {
7171         struct r5conf *conf;
7172         int raid_disk, memory, max_disks;
7173         struct md_rdev *rdev;
7174         struct disk_info *disk;
7175         char pers_name[6];
7176         int i;
7177         int group_cnt;
7178         struct r5worker_group *new_group;
7179         int ret;
7180
7181         if (mddev->new_level != 5
7182             && mddev->new_level != 4
7183             && mddev->new_level != 6) {
7184                 pr_warn("md/raid:%s: raid level not set to 4/5/6 (%d)\n",
7185                         mdname(mddev), mddev->new_level);
7186                 return ERR_PTR(-EIO);
7187         }
7188         if ((mddev->new_level == 5
7189              && !algorithm_valid_raid5(mddev->new_layout)) ||
7190             (mddev->new_level == 6
7191              && !algorithm_valid_raid6(mddev->new_layout))) {
7192                 pr_warn("md/raid:%s: layout %d not supported\n",
7193                         mdname(mddev), mddev->new_layout);
7194                 return ERR_PTR(-EIO);
7195         }
7196         if (mddev->new_level == 6 && mddev->raid_disks < 4) {
7197                 pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n",
7198                         mdname(mddev), mddev->raid_disks);
7199                 return ERR_PTR(-EINVAL);
7200         }
7201
7202         if (!mddev->new_chunk_sectors ||
7203             (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
7204             !is_power_of_2(mddev->new_chunk_sectors)) {
7205                 pr_warn("md/raid:%s: invalid chunk size %d\n",
7206                         mdname(mddev), mddev->new_chunk_sectors << 9);
7207                 return ERR_PTR(-EINVAL);
7208         }
7209
7210         conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
7211         if (conf == NULL)
7212                 goto abort;
7213
7214 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
7215         conf->stripe_size = DEFAULT_STRIPE_SIZE;
7216         conf->stripe_shift = ilog2(DEFAULT_STRIPE_SIZE) - 9;
7217         conf->stripe_sectors = DEFAULT_STRIPE_SIZE >> 9;
7218 #endif
7219         INIT_LIST_HEAD(&conf->free_list);
7220         INIT_LIST_HEAD(&conf->pending_list);
7221         conf->pending_data = kcalloc(PENDING_IO_MAX,
7222                                      sizeof(struct r5pending_data),
7223                                      GFP_KERNEL);
7224         if (!conf->pending_data)
7225                 goto abort;
7226         for (i = 0; i < PENDING_IO_MAX; i++)
7227                 list_add(&conf->pending_data[i].sibling, &conf->free_list);
7228         /* Don't enable multi-threading by default*/
7229         if (!alloc_thread_groups(conf, 0, &group_cnt, &new_group)) {
7230                 conf->group_cnt = group_cnt;
7231                 conf->worker_cnt_per_group = 0;
7232                 conf->worker_groups = new_group;
7233         } else
7234                 goto abort;
7235         spin_lock_init(&conf->device_lock);
7236         seqcount_spinlock_init(&conf->gen_lock, &conf->device_lock);
7237         mutex_init(&conf->cache_size_mutex);
7238         init_waitqueue_head(&conf->wait_for_quiescent);
7239         init_waitqueue_head(&conf->wait_for_stripe);
7240         init_waitqueue_head(&conf->wait_for_overlap);
7241         INIT_LIST_HEAD(&conf->handle_list);
7242         INIT_LIST_HEAD(&conf->loprio_list);
7243         INIT_LIST_HEAD(&conf->hold_list);
7244         INIT_LIST_HEAD(&conf->delayed_list);
7245         INIT_LIST_HEAD(&conf->bitmap_list);
7246         init_llist_head(&conf->released_stripes);
7247         atomic_set(&conf->active_stripes, 0);
7248         atomic_set(&conf->preread_active_stripes, 0);
7249         atomic_set(&conf->active_aligned_reads, 0);
7250         spin_lock_init(&conf->pending_bios_lock);
7251         conf->batch_bio_dispatch = true;
7252         rdev_for_each(rdev, mddev) {
7253                 if (test_bit(Journal, &rdev->flags))
7254                         continue;
7255                 if (blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
7256                         conf->batch_bio_dispatch = false;
7257                         break;
7258                 }
7259         }
7260
7261         conf->bypass_threshold = BYPASS_THRESHOLD;
7262         conf->recovery_disabled = mddev->recovery_disabled - 1;
7263
7264         conf->raid_disks = mddev->raid_disks;
7265         if (mddev->reshape_position == MaxSector)
7266                 conf->previous_raid_disks = mddev->raid_disks;
7267         else
7268                 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
7269         max_disks = max(conf->raid_disks, conf->previous_raid_disks);
7270
7271         conf->disks = kcalloc(max_disks, sizeof(struct disk_info),
7272                               GFP_KERNEL);
7273
7274         if (!conf->disks)
7275                 goto abort;
7276
7277         for (i = 0; i < max_disks; i++) {
7278                 conf->disks[i].extra_page = alloc_page(GFP_KERNEL);
7279                 if (!conf->disks[i].extra_page)
7280                         goto abort;
7281         }
7282
7283         ret = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
7284         if (ret)
7285                 goto abort;
7286         conf->mddev = mddev;
7287
7288         if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
7289                 goto abort;
7290
7291         /* We init hash_locks[0] separately to that it can be used
7292          * as the reference lock in the spin_lock_nest_lock() call
7293          * in lock_all_device_hash_locks_irq in order to convince
7294          * lockdep that we know what we are doing.
7295          */
7296         spin_lock_init(conf->hash_locks);
7297         for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
7298                 spin_lock_init(conf->hash_locks + i);
7299
7300         for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7301                 INIT_LIST_HEAD(conf->inactive_list + i);
7302
7303         for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7304                 INIT_LIST_HEAD(conf->temp_inactive_list + i);
7305
7306         atomic_set(&conf->r5c_cached_full_stripes, 0);
7307         INIT_LIST_HEAD(&conf->r5c_full_stripe_list);
7308         atomic_set(&conf->r5c_cached_partial_stripes, 0);
7309         INIT_LIST_HEAD(&conf->r5c_partial_stripe_list);
7310         atomic_set(&conf->r5c_flushing_full_stripes, 0);
7311         atomic_set(&conf->r5c_flushing_partial_stripes, 0);
7312
7313         conf->level = mddev->new_level;
7314         conf->chunk_sectors = mddev->new_chunk_sectors;
7315         if (raid5_alloc_percpu(conf) != 0)
7316                 goto abort;
7317
7318         pr_debug("raid456: run(%s) called.\n", mdname(mddev));
7319
7320         rdev_for_each(rdev, mddev) {
7321                 raid_disk = rdev->raid_disk;
7322                 if (raid_disk >= max_disks
7323                     || raid_disk < 0 || test_bit(Journal, &rdev->flags))
7324                         continue;
7325                 disk = conf->disks + raid_disk;
7326
7327                 if (test_bit(Replacement, &rdev->flags)) {
7328                         if (disk->replacement)
7329                                 goto abort;
7330                         disk->replacement = rdev;
7331                 } else {
7332                         if (disk->rdev)
7333                                 goto abort;
7334                         disk->rdev = rdev;
7335                 }
7336
7337                 if (test_bit(In_sync, &rdev->flags)) {
7338                         char b[BDEVNAME_SIZE];
7339                         pr_info("md/raid:%s: device %s operational as raid disk %d\n",
7340                                 mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
7341                 } else if (rdev->saved_raid_disk != raid_disk)
7342                         /* Cannot rely on bitmap to complete recovery */
7343                         conf->fullsync = 1;
7344         }
7345
7346         conf->level = mddev->new_level;
7347         if (conf->level == 6) {
7348                 conf->max_degraded = 2;
7349                 if (raid6_call.xor_syndrome)
7350                         conf->rmw_level = PARITY_ENABLE_RMW;
7351                 else
7352                         conf->rmw_level = PARITY_DISABLE_RMW;
7353         } else {
7354                 conf->max_degraded = 1;
7355                 conf->rmw_level = PARITY_ENABLE_RMW;
7356         }
7357         conf->algorithm = mddev->new_layout;
7358         conf->reshape_progress = mddev->reshape_position;
7359         if (conf->reshape_progress != MaxSector) {
7360                 conf->prev_chunk_sectors = mddev->chunk_sectors;
7361                 conf->prev_algo = mddev->layout;
7362         } else {
7363                 conf->prev_chunk_sectors = conf->chunk_sectors;
7364                 conf->prev_algo = conf->algorithm;
7365         }
7366
7367         conf->min_nr_stripes = NR_STRIPES;
7368         if (mddev->reshape_position != MaxSector) {
7369                 int stripes = max_t(int,
7370                         ((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4,
7371                         ((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4);
7372                 conf->min_nr_stripes = max(NR_STRIPES, stripes);
7373                 if (conf->min_nr_stripes != NR_STRIPES)
7374                         pr_info("md/raid:%s: force stripe size %d for reshape\n",
7375                                 mdname(mddev), conf->min_nr_stripes);
7376         }
7377         memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
7378                  max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
7379         atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
7380         if (grow_stripes(conf, conf->min_nr_stripes)) {
7381                 pr_warn("md/raid:%s: couldn't allocate %dkB for buffers\n",
7382                         mdname(mddev), memory);
7383                 goto abort;
7384         } else
7385                 pr_debug("md/raid:%s: allocated %dkB\n", mdname(mddev), memory);
7386         /*
7387          * Losing a stripe head costs more than the time to refill it,
7388          * it reduces the queue depth and so can hurt throughput.
7389          * So set it rather large, scaled by number of devices.
7390          */
7391         conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
7392         conf->shrinker.scan_objects = raid5_cache_scan;
7393         conf->shrinker.count_objects = raid5_cache_count;
7394         conf->shrinker.batch = 128;
7395         conf->shrinker.flags = 0;
7396         if (register_shrinker(&conf->shrinker)) {
7397                 pr_warn("md/raid:%s: couldn't register shrinker.\n",
7398                         mdname(mddev));
7399                 goto abort;
7400         }
7401
7402         sprintf(pers_name, "raid%d", mddev->new_level);
7403         conf->thread = md_register_thread(raid5d, mddev, pers_name);
7404         if (!conf->thread) {
7405                 pr_warn("md/raid:%s: couldn't allocate thread.\n",
7406                         mdname(mddev));
7407                 goto abort;
7408         }
7409
7410         return conf;
7411
7412  abort:
7413         if (conf) {
7414                 free_conf(conf);
7415                 return ERR_PTR(-EIO);
7416         } else
7417                 return ERR_PTR(-ENOMEM);
7418 }
7419
7420 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
7421 {
7422         switch (algo) {
7423         case ALGORITHM_PARITY_0:
7424                 if (raid_disk < max_degraded)
7425                         return 1;
7426                 break;
7427         case ALGORITHM_PARITY_N:
7428                 if (raid_disk >= raid_disks - max_degraded)
7429                         return 1;
7430                 break;
7431         case ALGORITHM_PARITY_0_6:
7432                 if (raid_disk == 0 ||
7433                     raid_disk == raid_disks - 1)
7434                         return 1;
7435                 break;
7436         case ALGORITHM_LEFT_ASYMMETRIC_6:
7437         case ALGORITHM_RIGHT_ASYMMETRIC_6:
7438         case ALGORITHM_LEFT_SYMMETRIC_6:
7439         case ALGORITHM_RIGHT_SYMMETRIC_6:
7440                 if (raid_disk == raid_disks - 1)
7441                         return 1;
7442         }
7443         return 0;
7444 }
7445
7446 static void raid5_set_io_opt(struct r5conf *conf)
7447 {
7448         blk_queue_io_opt(conf->mddev->queue, (conf->chunk_sectors << 9) *
7449                          (conf->raid_disks - conf->max_degraded));
7450 }
7451
7452 static int raid5_run(struct mddev *mddev)
7453 {
7454         struct r5conf *conf;
7455         int working_disks = 0;
7456         int dirty_parity_disks = 0;
7457         struct md_rdev *rdev;
7458         struct md_rdev *journal_dev = NULL;
7459         sector_t reshape_offset = 0;
7460         int i, ret = 0;
7461         long long min_offset_diff = 0;
7462         int first = 1;
7463
7464         if (acct_bioset_init(mddev)) {
7465                 pr_err("md/raid456:%s: alloc acct bioset failed.\n", mdname(mddev));
7466                 return -ENOMEM;
7467         }
7468
7469         if (mddev_init_writes_pending(mddev) < 0) {
7470                 ret = -ENOMEM;
7471                 goto exit_acct_set;
7472         }
7473
7474         if (mddev->recovery_cp != MaxSector)
7475                 pr_notice("md/raid:%s: not clean -- starting background reconstruction\n",
7476                           mdname(mddev));
7477
7478         rdev_for_each(rdev, mddev) {
7479                 long long diff;
7480
7481                 if (test_bit(Journal, &rdev->flags)) {
7482                         journal_dev = rdev;
7483                         continue;
7484                 }
7485                 if (rdev->raid_disk < 0)
7486                         continue;
7487                 diff = (rdev->new_data_offset - rdev->data_offset);
7488                 if (first) {
7489                         min_offset_diff = diff;
7490                         first = 0;
7491                 } else if (mddev->reshape_backwards &&
7492                          diff < min_offset_diff)
7493                         min_offset_diff = diff;
7494                 else if (!mddev->reshape_backwards &&
7495                          diff > min_offset_diff)
7496                         min_offset_diff = diff;
7497         }
7498
7499         if ((test_bit(MD_HAS_JOURNAL, &mddev->flags) || journal_dev) &&
7500             (mddev->bitmap_info.offset || mddev->bitmap_info.file)) {
7501                 pr_notice("md/raid:%s: array cannot have both journal and bitmap\n",
7502                           mdname(mddev));
7503                 ret = -EINVAL;
7504                 goto exit_acct_set;
7505         }
7506
7507         if (mddev->reshape_position != MaxSector) {
7508                 /* Check that we can continue the reshape.
7509                  * Difficulties arise if the stripe we would write to
7510                  * next is at or after the stripe we would read from next.
7511                  * For a reshape that changes the number of devices, this
7512                  * is only possible for a very short time, and mdadm makes
7513                  * sure that time appears to have past before assembling
7514                  * the array.  So we fail if that time hasn't passed.
7515                  * For a reshape that keeps the number of devices the same
7516                  * mdadm must be monitoring the reshape can keeping the
7517                  * critical areas read-only and backed up.  It will start
7518                  * the array in read-only mode, so we check for that.
7519                  */
7520                 sector_t here_new, here_old;
7521                 int old_disks;
7522                 int max_degraded = (mddev->level == 6 ? 2 : 1);
7523                 int chunk_sectors;
7524                 int new_data_disks;
7525
7526                 if (journal_dev) {
7527                         pr_warn("md/raid:%s: don't support reshape with journal - aborting.\n",
7528                                 mdname(mddev));
7529                         ret = -EINVAL;
7530                         goto exit_acct_set;
7531                 }
7532
7533                 if (mddev->new_level != mddev->level) {
7534                         pr_warn("md/raid:%s: unsupported reshape required - aborting.\n",
7535                                 mdname(mddev));
7536                         ret = -EINVAL;
7537                         goto exit_acct_set;
7538                 }
7539                 old_disks = mddev->raid_disks - mddev->delta_disks;
7540                 /* reshape_position must be on a new-stripe boundary, and one
7541                  * further up in new geometry must map after here in old
7542                  * geometry.
7543                  * If the chunk sizes are different, then as we perform reshape
7544                  * in units of the largest of the two, reshape_position needs
7545                  * be a multiple of the largest chunk size times new data disks.
7546                  */
7547                 here_new = mddev->reshape_position;
7548                 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
7549                 new_data_disks = mddev->raid_disks - max_degraded;
7550                 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
7551                         pr_warn("md/raid:%s: reshape_position not on a stripe boundary\n",
7552                                 mdname(mddev));
7553                         ret = -EINVAL;
7554                         goto exit_acct_set;
7555                 }
7556                 reshape_offset = here_new * chunk_sectors;
7557                 /* here_new is the stripe we will write to */
7558                 here_old = mddev->reshape_position;
7559                 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
7560                 /* here_old is the first stripe that we might need to read
7561                  * from */
7562                 if (mddev->delta_disks == 0) {
7563                         /* We cannot be sure it is safe to start an in-place
7564                          * reshape.  It is only safe if user-space is monitoring
7565                          * and taking constant backups.
7566                          * mdadm always starts a situation like this in
7567                          * readonly mode so it can take control before
7568                          * allowing any writes.  So just check for that.
7569                          */
7570                         if (abs(min_offset_diff) >= mddev->chunk_sectors &&
7571                             abs(min_offset_diff) >= mddev->new_chunk_sectors)
7572                                 /* not really in-place - so OK */;
7573                         else if (mddev->ro == 0) {
7574                                 pr_warn("md/raid:%s: in-place reshape must be started in read-only mode - aborting\n",
7575                                         mdname(mddev));
7576                                 ret = -EINVAL;
7577                                 goto exit_acct_set;
7578                         }
7579                 } else if (mddev->reshape_backwards
7580                     ? (here_new * chunk_sectors + min_offset_diff <=
7581                        here_old * chunk_sectors)
7582                     : (here_new * chunk_sectors >=
7583                        here_old * chunk_sectors + (-min_offset_diff))) {
7584                         /* Reading from the same stripe as writing to - bad */
7585                         pr_warn("md/raid:%s: reshape_position too early for auto-recovery - aborting.\n",
7586                                 mdname(mddev));
7587                         ret = -EINVAL;
7588                         goto exit_acct_set;
7589                 }
7590                 pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev));
7591                 /* OK, we should be able to continue; */
7592         } else {
7593                 BUG_ON(mddev->level != mddev->new_level);
7594                 BUG_ON(mddev->layout != mddev->new_layout);
7595                 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
7596                 BUG_ON(mddev->delta_disks != 0);
7597         }
7598
7599         if (test_bit(MD_HAS_JOURNAL, &mddev->flags) &&
7600             test_bit(MD_HAS_PPL, &mddev->flags)) {
7601                 pr_warn("md/raid:%s: using journal device and PPL not allowed - disabling PPL\n",
7602                         mdname(mddev));
7603                 clear_bit(MD_HAS_PPL, &mddev->flags);
7604                 clear_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags);
7605         }
7606
7607         if (mddev->private == NULL)
7608                 conf = setup_conf(mddev);
7609         else
7610                 conf = mddev->private;
7611
7612         if (IS_ERR(conf)) {
7613                 ret = PTR_ERR(conf);
7614                 goto exit_acct_set;
7615         }
7616
7617         if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
7618                 if (!journal_dev) {
7619                         pr_warn("md/raid:%s: journal disk is missing, force array readonly\n",
7620                                 mdname(mddev));
7621                         mddev->ro = 1;
7622                         set_disk_ro(mddev->gendisk, 1);
7623                 } else if (mddev->recovery_cp == MaxSector)
7624                         set_bit(MD_JOURNAL_CLEAN, &mddev->flags);
7625         }
7626
7627         conf->min_offset_diff = min_offset_diff;
7628         mddev->thread = conf->thread;
7629         conf->thread = NULL;
7630         mddev->private = conf;
7631
7632         for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
7633              i++) {
7634                 rdev = conf->disks[i].rdev;
7635                 if (!rdev && conf->disks[i].replacement) {
7636                         /* The replacement is all we have yet */
7637                         rdev = conf->disks[i].replacement;
7638                         conf->disks[i].replacement = NULL;
7639                         clear_bit(Replacement, &rdev->flags);
7640                         conf->disks[i].rdev = rdev;
7641                 }
7642                 if (!rdev)
7643                         continue;
7644                 if (conf->disks[i].replacement &&
7645                     conf->reshape_progress != MaxSector) {
7646                         /* replacements and reshape simply do not mix. */
7647                         pr_warn("md: cannot handle concurrent replacement and reshape.\n");
7648                         goto abort;
7649                 }
7650                 if (test_bit(In_sync, &rdev->flags)) {
7651                         working_disks++;
7652                         continue;
7653                 }
7654                 /* This disc is not fully in-sync.  However if it
7655                  * just stored parity (beyond the recovery_offset),
7656                  * when we don't need to be concerned about the
7657                  * array being dirty.
7658                  * When reshape goes 'backwards', we never have
7659                  * partially completed devices, so we only need
7660                  * to worry about reshape going forwards.
7661                  */
7662                 /* Hack because v0.91 doesn't store recovery_offset properly. */
7663                 if (mddev->major_version == 0 &&
7664                     mddev->minor_version > 90)
7665                         rdev->recovery_offset = reshape_offset;
7666
7667                 if (rdev->recovery_offset < reshape_offset) {
7668                         /* We need to check old and new layout */
7669                         if (!only_parity(rdev->raid_disk,
7670                                          conf->algorithm,
7671                                          conf->raid_disks,
7672                                          conf->max_degraded))
7673                                 continue;
7674                 }
7675                 if (!only_parity(rdev->raid_disk,
7676                                  conf->prev_algo,
7677                                  conf->previous_raid_disks,
7678                                  conf->max_degraded))
7679                         continue;
7680                 dirty_parity_disks++;
7681         }
7682
7683         /*
7684          * 0 for a fully functional array, 1 or 2 for a degraded array.
7685          */
7686         mddev->degraded = raid5_calc_degraded(conf);
7687
7688         if (has_failed(conf)) {
7689                 pr_crit("md/raid:%s: not enough operational devices (%d/%d failed)\n",
7690                         mdname(mddev), mddev->degraded, conf->raid_disks);
7691                 goto abort;
7692         }
7693
7694         /* device size must be a multiple of chunk size */
7695         mddev->dev_sectors &= ~((sector_t)mddev->chunk_sectors - 1);
7696         mddev->resync_max_sectors = mddev->dev_sectors;
7697
7698         if (mddev->degraded > dirty_parity_disks &&
7699             mddev->recovery_cp != MaxSector) {
7700                 if (test_bit(MD_HAS_PPL, &mddev->flags))
7701                         pr_crit("md/raid:%s: starting dirty degraded array with PPL.\n",
7702                                 mdname(mddev));
7703                 else if (mddev->ok_start_degraded)
7704                         pr_crit("md/raid:%s: starting dirty degraded array - data corruption possible.\n",
7705                                 mdname(mddev));
7706                 else {
7707                         pr_crit("md/raid:%s: cannot start dirty degraded array.\n",
7708                                 mdname(mddev));
7709                         goto abort;
7710                 }
7711         }
7712
7713         pr_info("md/raid:%s: raid level %d active with %d out of %d devices, algorithm %d\n",
7714                 mdname(mddev), conf->level,
7715                 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
7716                 mddev->new_layout);
7717
7718         print_raid5_conf(conf);
7719
7720         if (conf->reshape_progress != MaxSector) {
7721                 conf->reshape_safe = conf->reshape_progress;
7722                 atomic_set(&conf->reshape_stripes, 0);
7723                 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7724                 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7725                 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7726                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7727                 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7728                                                         "reshape");
7729                 if (!mddev->sync_thread)
7730                         goto abort;
7731         }
7732
7733         /* Ok, everything is just fine now */
7734         if (mddev->to_remove == &raid5_attrs_group)
7735                 mddev->to_remove = NULL;
7736         else if (mddev->kobj.sd &&
7737             sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
7738                 pr_warn("raid5: failed to create sysfs attributes for %s\n",
7739                         mdname(mddev));
7740         md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7741
7742         if (mddev->queue) {
7743                 int chunk_size;
7744                 /* read-ahead size must cover two whole stripes, which
7745                  * is 2 * (datadisks) * chunksize where 'n' is the
7746                  * number of raid devices
7747                  */
7748                 int data_disks = conf->previous_raid_disks - conf->max_degraded;
7749                 int stripe = data_disks *
7750                         ((mddev->chunk_sectors << 9) / PAGE_SIZE);
7751
7752                 chunk_size = mddev->chunk_sectors << 9;
7753                 blk_queue_io_min(mddev->queue, chunk_size);
7754                 raid5_set_io_opt(conf);
7755                 mddev->queue->limits.raid_partial_stripes_expensive = 1;
7756                 /*
7757                  * We can only discard a whole stripe. It doesn't make sense to
7758                  * discard data disk but write parity disk
7759                  */
7760                 stripe = stripe * PAGE_SIZE;
7761                 /* Round up to power of 2, as discard handling
7762                  * currently assumes that */
7763                 while ((stripe-1) & stripe)
7764                         stripe = (stripe | (stripe-1)) + 1;
7765                 mddev->queue->limits.discard_alignment = stripe;
7766                 mddev->queue->limits.discard_granularity = stripe;
7767
7768                 blk_queue_max_write_same_sectors(mddev->queue, 0);
7769                 blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
7770
7771                 rdev_for_each(rdev, mddev) {
7772                         disk_stack_limits(mddev->gendisk, rdev->bdev,
7773                                           rdev->data_offset << 9);
7774                         disk_stack_limits(mddev->gendisk, rdev->bdev,
7775                                           rdev->new_data_offset << 9);
7776                 }
7777
7778                 /*
7779                  * zeroing is required, otherwise data
7780                  * could be lost. Consider a scenario: discard a stripe
7781                  * (the stripe could be inconsistent if
7782                  * discard_zeroes_data is 0); write one disk of the
7783                  * stripe (the stripe could be inconsistent again
7784                  * depending on which disks are used to calculate
7785                  * parity); the disk is broken; The stripe data of this
7786                  * disk is lost.
7787                  *
7788                  * We only allow DISCARD if the sysadmin has confirmed that
7789                  * only safe devices are in use by setting a module parameter.
7790                  * A better idea might be to turn DISCARD into WRITE_ZEROES
7791                  * requests, as that is required to be safe.
7792                  */
7793                 if (devices_handle_discard_safely &&
7794                     mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7795                     mddev->queue->limits.discard_granularity >= stripe)
7796                         blk_queue_flag_set(QUEUE_FLAG_DISCARD,
7797                                                 mddev->queue);
7798                 else
7799                         blk_queue_flag_clear(QUEUE_FLAG_DISCARD,
7800                                                 mddev->queue);
7801
7802                 blk_queue_max_hw_sectors(mddev->queue, UINT_MAX);
7803         }
7804
7805         if (log_init(conf, journal_dev, raid5_has_ppl(conf)))
7806                 goto abort;
7807
7808         return 0;
7809 abort:
7810         md_unregister_thread(&mddev->thread);
7811         print_raid5_conf(conf);
7812         free_conf(conf);
7813         mddev->private = NULL;
7814         pr_warn("md/raid:%s: failed to run raid set.\n", mdname(mddev));
7815         ret = -EIO;
7816 exit_acct_set:
7817         acct_bioset_exit(mddev);
7818         return ret;
7819 }
7820
7821 static void raid5_free(struct mddev *mddev, void *priv)
7822 {
7823         struct r5conf *conf = priv;
7824
7825         free_conf(conf);
7826         acct_bioset_exit(mddev);
7827         mddev->to_remove = &raid5_attrs_group;
7828 }
7829
7830 static void raid5_status(struct seq_file *seq, struct mddev *mddev)
7831 {
7832         struct r5conf *conf = mddev->private;
7833         int i;
7834
7835         seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7836                 conf->chunk_sectors / 2, mddev->layout);
7837         seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7838         rcu_read_lock();
7839         for (i = 0; i < conf->raid_disks; i++) {
7840                 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
7841                 seq_printf (seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
7842         }
7843         rcu_read_unlock();
7844         seq_printf (seq, "]");
7845 }
7846
7847 static void print_raid5_conf (struct r5conf *conf)
7848 {
7849         int i;
7850         struct disk_info *tmp;
7851
7852         pr_debug("RAID conf printout:\n");
7853         if (!conf) {
7854                 pr_debug("(conf==NULL)\n");
7855                 return;
7856         }
7857         pr_debug(" --- level:%d rd:%d wd:%d\n", conf->level,
7858                conf->raid_disks,
7859                conf->raid_disks - conf->mddev->degraded);
7860
7861         for (i = 0; i < conf->raid_disks; i++) {
7862                 char b[BDEVNAME_SIZE];
7863                 tmp = conf->disks + i;
7864                 if (tmp->rdev)
7865                         pr_debug(" disk %d, o:%d, dev:%s\n",
7866                                i, !test_bit(Faulty, &tmp->rdev->flags),
7867                                bdevname(tmp->rdev->bdev, b));
7868         }
7869 }
7870
7871 static int raid5_spare_active(struct mddev *mddev)
7872 {
7873         int i;
7874         struct r5conf *conf = mddev->private;
7875         struct disk_info *tmp;
7876         int count = 0;
7877         unsigned long flags;
7878
7879         for (i = 0; i < conf->raid_disks; i++) {
7880                 tmp = conf->disks + i;
7881                 if (tmp->replacement
7882                     && tmp->replacement->recovery_offset == MaxSector
7883                     && !test_bit(Faulty, &tmp->replacement->flags)
7884                     && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7885                         /* Replacement has just become active. */
7886                         if (!tmp->rdev
7887                             || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7888                                 count++;
7889                         if (tmp->rdev) {
7890                                 /* Replaced device not technically faulty,
7891                                  * but we need to be sure it gets removed
7892                                  * and never re-added.
7893                                  */
7894                                 set_bit(Faulty, &tmp->rdev->flags);
7895                                 sysfs_notify_dirent_safe(
7896                                         tmp->rdev->sysfs_state);
7897                         }
7898                         sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7899                 } else if (tmp->rdev
7900                     && tmp->rdev->recovery_offset == MaxSector
7901                     && !test_bit(Faulty, &tmp->rdev->flags)
7902                     && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7903                         count++;
7904                         sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7905                 }
7906         }
7907         spin_lock_irqsave(&conf->device_lock, flags);
7908         mddev->degraded = raid5_calc_degraded(conf);
7909         spin_unlock_irqrestore(&conf->device_lock, flags);
7910         print_raid5_conf(conf);
7911         return count;
7912 }
7913
7914 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7915 {
7916         struct r5conf *conf = mddev->private;
7917         int err = 0;
7918         int number = rdev->raid_disk;
7919         struct md_rdev **rdevp;
7920         struct disk_info *p = conf->disks + number;
7921
7922         print_raid5_conf(conf);
7923         if (test_bit(Journal, &rdev->flags) && conf->log) {
7924                 /*
7925                  * we can't wait pending write here, as this is called in
7926                  * raid5d, wait will deadlock.
7927                  * neilb: there is no locking about new writes here,
7928                  * so this cannot be safe.
7929                  */
7930                 if (atomic_read(&conf->active_stripes) ||
7931                     atomic_read(&conf->r5c_cached_full_stripes) ||
7932                     atomic_read(&conf->r5c_cached_partial_stripes)) {
7933                         return -EBUSY;
7934                 }
7935                 log_exit(conf);
7936                 return 0;
7937         }
7938         if (rdev == p->rdev)
7939                 rdevp = &p->rdev;
7940         else if (rdev == p->replacement)
7941                 rdevp = &p->replacement;
7942         else
7943                 return 0;
7944
7945         if (number >= conf->raid_disks &&
7946             conf->reshape_progress == MaxSector)
7947                 clear_bit(In_sync, &rdev->flags);
7948
7949         if (test_bit(In_sync, &rdev->flags) ||
7950             atomic_read(&rdev->nr_pending)) {
7951                 err = -EBUSY;
7952                 goto abort;
7953         }
7954         /* Only remove non-faulty devices if recovery
7955          * isn't possible.
7956          */
7957         if (!test_bit(Faulty, &rdev->flags) &&
7958             mddev->recovery_disabled != conf->recovery_disabled &&
7959             !has_failed(conf) &&
7960             (!p->replacement || p->replacement == rdev) &&
7961             number < conf->raid_disks) {
7962                 err = -EBUSY;
7963                 goto abort;
7964         }
7965         *rdevp = NULL;
7966         if (!test_bit(RemoveSynchronized, &rdev->flags)) {
7967                 synchronize_rcu();
7968                 if (atomic_read(&rdev->nr_pending)) {
7969                         /* lost the race, try later */
7970                         err = -EBUSY;
7971                         *rdevp = rdev;
7972                 }
7973         }
7974         if (!err) {
7975                 err = log_modify(conf, rdev, false);
7976                 if (err)
7977                         goto abort;
7978         }
7979         if (p->replacement) {
7980                 /* We must have just cleared 'rdev' */
7981                 p->rdev = p->replacement;
7982                 clear_bit(Replacement, &p->replacement->flags);
7983                 smp_mb(); /* Make sure other CPUs may see both as identical
7984                            * but will never see neither - if they are careful
7985                            */
7986                 p->replacement = NULL;
7987
7988                 if (!err)
7989                         err = log_modify(conf, p->rdev, true);
7990         }
7991
7992         clear_bit(WantReplacement, &rdev->flags);
7993 abort:
7994
7995         print_raid5_conf(conf);
7996         return err;
7997 }
7998
7999 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
8000 {
8001         struct r5conf *conf = mddev->private;
8002         int ret, err = -EEXIST;
8003         int disk;
8004         struct disk_info *p;
8005         int first = 0;
8006         int last = conf->raid_disks - 1;
8007
8008         if (test_bit(Journal, &rdev->flags)) {
8009                 if (conf->log)
8010                         return -EBUSY;
8011
8012                 rdev->raid_disk = 0;
8013                 /*
8014                  * The array is in readonly mode if journal is missing, so no
8015                  * write requests running. We should be safe
8016                  */
8017                 ret = log_init(conf, rdev, false);
8018                 if (ret)
8019                         return ret;
8020
8021                 ret = r5l_start(conf->log);
8022                 if (ret)
8023                         return ret;
8024
8025                 return 0;
8026         }
8027         if (mddev->recovery_disabled == conf->recovery_disabled)
8028                 return -EBUSY;
8029
8030         if (rdev->saved_raid_disk < 0 && has_failed(conf))
8031                 /* no point adding a device */
8032                 return -EINVAL;
8033
8034         if (rdev->raid_disk >= 0)
8035                 first = last = rdev->raid_disk;
8036
8037         /*
8038          * find the disk ... but prefer rdev->saved_raid_disk
8039          * if possible.
8040          */
8041         if (rdev->saved_raid_disk >= 0 &&
8042             rdev->saved_raid_disk >= first &&
8043             rdev->saved_raid_disk <= last &&
8044             conf->disks[rdev->saved_raid_disk].rdev == NULL)
8045                 first = rdev->saved_raid_disk;
8046
8047         for (disk = first; disk <= last; disk++) {
8048                 p = conf->disks + disk;
8049                 if (p->rdev == NULL) {
8050                         clear_bit(In_sync, &rdev->flags);
8051                         rdev->raid_disk = disk;
8052                         if (rdev->saved_raid_disk != disk)
8053                                 conf->fullsync = 1;
8054                         rcu_assign_pointer(p->rdev, rdev);
8055
8056                         err = log_modify(conf, rdev, true);
8057
8058                         goto out;
8059                 }
8060         }
8061         for (disk = first; disk <= last; disk++) {
8062                 p = conf->disks + disk;
8063                 if (test_bit(WantReplacement, &p->rdev->flags) &&
8064                     p->replacement == NULL) {
8065                         clear_bit(In_sync, &rdev->flags);
8066                         set_bit(Replacement, &rdev->flags);
8067                         rdev->raid_disk = disk;
8068                         err = 0;
8069                         conf->fullsync = 1;
8070                         rcu_assign_pointer(p->replacement, rdev);
8071                         break;
8072                 }
8073         }
8074 out:
8075         print_raid5_conf(conf);
8076         return err;
8077 }
8078
8079 static int raid5_resize(struct mddev *mddev, sector_t sectors)
8080 {
8081         /* no resync is happening, and there is enough space
8082          * on all devices, so we can resize.
8083          * We need to make sure resync covers any new space.
8084          * If the array is shrinking we should possibly wait until
8085          * any io in the removed space completes, but it hardly seems
8086          * worth it.
8087          */
8088         sector_t newsize;
8089         struct r5conf *conf = mddev->private;
8090
8091         if (raid5_has_log(conf) || raid5_has_ppl(conf))
8092                 return -EINVAL;
8093         sectors &= ~((sector_t)conf->chunk_sectors - 1);
8094         newsize = raid5_size(mddev, sectors, mddev->raid_disks);
8095         if (mddev->external_size &&
8096             mddev->array_sectors > newsize)
8097                 return -EINVAL;
8098         if (mddev->bitmap) {
8099                 int ret = md_bitmap_resize(mddev->bitmap, sectors, 0, 0);
8100                 if (ret)
8101                         return ret;
8102         }
8103         md_set_array_sectors(mddev, newsize);
8104         if (sectors > mddev->dev_sectors &&
8105             mddev->recovery_cp > mddev->dev_sectors) {
8106                 mddev->recovery_cp = mddev->dev_sectors;
8107                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8108         }
8109         mddev->dev_sectors = sectors;
8110         mddev->resync_max_sectors = sectors;
8111         return 0;
8112 }
8113
8114 static int check_stripe_cache(struct mddev *mddev)
8115 {
8116         /* Can only proceed if there are plenty of stripe_heads.
8117          * We need a minimum of one full stripe,, and for sensible progress
8118          * it is best to have about 4 times that.
8119          * If we require 4 times, then the default 256 4K stripe_heads will
8120          * allow for chunk sizes up to 256K, which is probably OK.
8121          * If the chunk size is greater, user-space should request more
8122          * stripe_heads first.
8123          */
8124         struct r5conf *conf = mddev->private;
8125         if (((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8126             > conf->min_nr_stripes ||
8127             ((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8128             > conf->min_nr_stripes) {
8129                 pr_warn("md/raid:%s: reshape: not enough stripes.  Needed %lu\n",
8130                         mdname(mddev),
8131                         ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
8132                          / RAID5_STRIPE_SIZE(conf))*4);
8133                 return 0;
8134         }
8135         return 1;
8136 }
8137
8138 static int check_reshape(struct mddev *mddev)
8139 {
8140         struct r5conf *conf = mddev->private;
8141
8142         if (raid5_has_log(conf) || raid5_has_ppl(conf))
8143                 return -EINVAL;
8144         if (mddev->delta_disks == 0 &&
8145             mddev->new_layout == mddev->layout &&
8146             mddev->new_chunk_sectors == mddev->chunk_sectors)
8147                 return 0; /* nothing to do */
8148         if (has_failed(conf))
8149                 return -EINVAL;
8150         if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
8151                 /* We might be able to shrink, but the devices must
8152                  * be made bigger first.
8153                  * For raid6, 4 is the minimum size.
8154                  * Otherwise 2 is the minimum
8155                  */
8156                 int min = 2;
8157                 if (mddev->level == 6)
8158                         min = 4;
8159                 if (mddev->raid_disks + mddev->delta_disks < min)
8160                         return -EINVAL;
8161         }
8162
8163         if (!check_stripe_cache(mddev))
8164                 return -ENOSPC;
8165
8166         if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
8167             mddev->delta_disks > 0)
8168                 if (resize_chunks(conf,
8169                                   conf->previous_raid_disks
8170                                   + max(0, mddev->delta_disks),
8171                                   max(mddev->new_chunk_sectors,
8172                                       mddev->chunk_sectors)
8173                             ) < 0)
8174                         return -ENOMEM;
8175
8176         if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
8177                 return 0; /* never bother to shrink */
8178         return resize_stripes(conf, (conf->previous_raid_disks
8179                                      + mddev->delta_disks));
8180 }
8181
8182 static int raid5_start_reshape(struct mddev *mddev)
8183 {
8184         struct r5conf *conf = mddev->private;
8185         struct md_rdev *rdev;
8186         int spares = 0;
8187         unsigned long flags;
8188
8189         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
8190                 return -EBUSY;
8191
8192         if (!check_stripe_cache(mddev))
8193                 return -ENOSPC;
8194
8195         if (has_failed(conf))
8196                 return -EINVAL;
8197
8198         rdev_for_each(rdev, mddev) {
8199                 if (!test_bit(In_sync, &rdev->flags)
8200                     && !test_bit(Faulty, &rdev->flags))
8201                         spares++;
8202         }
8203
8204         if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
8205                 /* Not enough devices even to make a degraded array
8206                  * of that size
8207                  */
8208                 return -EINVAL;
8209
8210         /* Refuse to reduce size of the array.  Any reductions in
8211          * array size must be through explicit setting of array_size
8212          * attribute.
8213          */
8214         if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
8215             < mddev->array_sectors) {
8216                 pr_warn("md/raid:%s: array size must be reduced before number of disks\n",
8217                         mdname(mddev));
8218                 return -EINVAL;
8219         }
8220
8221         atomic_set(&conf->reshape_stripes, 0);
8222         spin_lock_irq(&conf->device_lock);
8223         write_seqcount_begin(&conf->gen_lock);
8224         conf->previous_raid_disks = conf->raid_disks;
8225         conf->raid_disks += mddev->delta_disks;
8226         conf->prev_chunk_sectors = conf->chunk_sectors;
8227         conf->chunk_sectors = mddev->new_chunk_sectors;
8228         conf->prev_algo = conf->algorithm;
8229         conf->algorithm = mddev->new_layout;
8230         conf->generation++;
8231         /* Code that selects data_offset needs to see the generation update
8232          * if reshape_progress has been set - so a memory barrier needed.
8233          */
8234         smp_mb();
8235         if (mddev->reshape_backwards)
8236                 conf->reshape_progress = raid5_size(mddev, 0, 0);
8237         else
8238                 conf->reshape_progress = 0;
8239         conf->reshape_safe = conf->reshape_progress;
8240         write_seqcount_end(&conf->gen_lock);
8241         spin_unlock_irq(&conf->device_lock);
8242
8243         /* Now make sure any requests that proceeded on the assumption
8244          * the reshape wasn't running - like Discard or Read - have
8245          * completed.
8246          */
8247         mddev_suspend(mddev);
8248         mddev_resume(mddev);
8249
8250         /* Add some new drives, as many as will fit.
8251          * We know there are enough to make the newly sized array work.
8252          * Don't add devices if we are reducing the number of
8253          * devices in the array.  This is because it is not possible
8254          * to correctly record the "partially reconstructed" state of
8255          * such devices during the reshape and confusion could result.
8256          */
8257         if (mddev->delta_disks >= 0) {
8258                 rdev_for_each(rdev, mddev)
8259                         if (rdev->raid_disk < 0 &&
8260                             !test_bit(Faulty, &rdev->flags)) {
8261                                 if (raid5_add_disk(mddev, rdev) == 0) {
8262                                         if (rdev->raid_disk
8263                                             >= conf->previous_raid_disks)
8264                                                 set_bit(In_sync, &rdev->flags);
8265                                         else
8266                                                 rdev->recovery_offset = 0;
8267
8268                                         /* Failure here is OK */
8269                                         sysfs_link_rdev(mddev, rdev);
8270                                 }
8271                         } else if (rdev->raid_disk >= conf->previous_raid_disks
8272                                    && !test_bit(Faulty, &rdev->flags)) {
8273                                 /* This is a spare that was manually added */
8274                                 set_bit(In_sync, &rdev->flags);
8275                         }
8276
8277                 /* When a reshape changes the number of devices,
8278                  * ->degraded is measured against the larger of the
8279                  * pre and post number of devices.
8280                  */
8281                 spin_lock_irqsave(&conf->device_lock, flags);
8282                 mddev->degraded = raid5_calc_degraded(conf);
8283                 spin_unlock_irqrestore(&conf->device_lock, flags);
8284         }
8285         mddev->raid_disks = conf->raid_disks;
8286         mddev->reshape_position = conf->reshape_progress;
8287         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8288
8289         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8290         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8291         clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8292         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8293         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8294         mddev->sync_thread = md_register_thread(md_do_sync, mddev,
8295                                                 "reshape");
8296         if (!mddev->sync_thread) {
8297                 mddev->recovery = 0;
8298                 spin_lock_irq(&conf->device_lock);
8299                 write_seqcount_begin(&conf->gen_lock);
8300                 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
8301                 mddev->new_chunk_sectors =
8302                         conf->chunk_sectors = conf->prev_chunk_sectors;
8303                 mddev->new_layout = conf->algorithm = conf->prev_algo;
8304                 rdev_for_each(rdev, mddev)
8305                         rdev->new_data_offset = rdev->data_offset;
8306                 smp_wmb();
8307                 conf->generation --;
8308                 conf->reshape_progress = MaxSector;
8309                 mddev->reshape_position = MaxSector;
8310                 write_seqcount_end(&conf->gen_lock);
8311                 spin_unlock_irq(&conf->device_lock);
8312                 return -EAGAIN;
8313         }
8314         conf->reshape_checkpoint = jiffies;
8315         md_wakeup_thread(mddev->sync_thread);
8316         md_new_event(mddev);
8317         return 0;
8318 }
8319
8320 /* This is called from the reshape thread and should make any
8321  * changes needed in 'conf'
8322  */
8323 static void end_reshape(struct r5conf *conf)
8324 {
8325
8326         if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
8327                 struct md_rdev *rdev;
8328
8329                 spin_lock_irq(&conf->device_lock);
8330                 conf->previous_raid_disks = conf->raid_disks;
8331                 md_finish_reshape(conf->mddev);
8332                 smp_wmb();
8333                 conf->reshape_progress = MaxSector;
8334                 conf->mddev->reshape_position = MaxSector;
8335                 rdev_for_each(rdev, conf->mddev)
8336                         if (rdev->raid_disk >= 0 &&
8337                             !test_bit(Journal, &rdev->flags) &&
8338                             !test_bit(In_sync, &rdev->flags))
8339                                 rdev->recovery_offset = MaxSector;
8340                 spin_unlock_irq(&conf->device_lock);
8341                 wake_up(&conf->wait_for_overlap);
8342
8343                 if (conf->mddev->queue)
8344                         raid5_set_io_opt(conf);
8345         }
8346 }
8347
8348 /* This is called from the raid5d thread with mddev_lock held.
8349  * It makes config changes to the device.
8350  */
8351 static void raid5_finish_reshape(struct mddev *mddev)
8352 {
8353         struct r5conf *conf = mddev->private;
8354
8355         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8356
8357                 if (mddev->delta_disks <= 0) {
8358                         int d;
8359                         spin_lock_irq(&conf->device_lock);
8360                         mddev->degraded = raid5_calc_degraded(conf);
8361                         spin_unlock_irq(&conf->device_lock);
8362                         for (d = conf->raid_disks ;
8363                              d < conf->raid_disks - mddev->delta_disks;
8364                              d++) {
8365                                 struct md_rdev *rdev = conf->disks[d].rdev;
8366                                 if (rdev)
8367                                         clear_bit(In_sync, &rdev->flags);
8368                                 rdev = conf->disks[d].replacement;
8369                                 if (rdev)
8370                                         clear_bit(In_sync, &rdev->flags);
8371                         }
8372                 }
8373                 mddev->layout = conf->algorithm;
8374                 mddev->chunk_sectors = conf->chunk_sectors;
8375                 mddev->reshape_position = MaxSector;
8376                 mddev->delta_disks = 0;
8377                 mddev->reshape_backwards = 0;
8378         }
8379 }
8380
8381 static void raid5_quiesce(struct mddev *mddev, int quiesce)
8382 {
8383         struct r5conf *conf = mddev->private;
8384
8385         if (quiesce) {
8386                 /* stop all writes */
8387                 lock_all_device_hash_locks_irq(conf);
8388                 /* '2' tells resync/reshape to pause so that all
8389                  * active stripes can drain
8390                  */
8391                 r5c_flush_cache(conf, INT_MAX);
8392                 /* need a memory barrier to make sure read_one_chunk() sees
8393                  * quiesce started and reverts to slow (locked) path.
8394                  */
8395                 smp_store_release(&conf->quiesce, 2);
8396                 wait_event_cmd(conf->wait_for_quiescent,
8397                                     atomic_read(&conf->active_stripes) == 0 &&
8398                                     atomic_read(&conf->active_aligned_reads) == 0,
8399                                     unlock_all_device_hash_locks_irq(conf),
8400                                     lock_all_device_hash_locks_irq(conf));
8401                 conf->quiesce = 1;
8402                 unlock_all_device_hash_locks_irq(conf);
8403                 /* allow reshape to continue */
8404                 wake_up(&conf->wait_for_overlap);
8405         } else {
8406                 /* re-enable writes */
8407                 lock_all_device_hash_locks_irq(conf);
8408                 conf->quiesce = 0;
8409                 wake_up(&conf->wait_for_quiescent);
8410                 wake_up(&conf->wait_for_overlap);
8411                 unlock_all_device_hash_locks_irq(conf);
8412         }
8413         log_quiesce(conf, quiesce);
8414 }
8415
8416 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
8417 {
8418         struct r0conf *raid0_conf = mddev->private;
8419         sector_t sectors;
8420
8421         /* for raid0 takeover only one zone is supported */
8422         if (raid0_conf->nr_strip_zones > 1) {
8423                 pr_warn("md/raid:%s: cannot takeover raid0 with more than one zone.\n",
8424                         mdname(mddev));
8425                 return ERR_PTR(-EINVAL);
8426         }
8427
8428         sectors = raid0_conf->strip_zone[0].zone_end;
8429         sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
8430         mddev->dev_sectors = sectors;
8431         mddev->new_level = level;
8432         mddev->new_layout = ALGORITHM_PARITY_N;
8433         mddev->new_chunk_sectors = mddev->chunk_sectors;
8434         mddev->raid_disks += 1;
8435         mddev->delta_disks = 1;
8436         /* make sure it will be not marked as dirty */
8437         mddev->recovery_cp = MaxSector;
8438
8439         return setup_conf(mddev);
8440 }
8441
8442 static void *raid5_takeover_raid1(struct mddev *mddev)
8443 {
8444         int chunksect;
8445         void *ret;
8446
8447         if (mddev->raid_disks != 2 ||
8448             mddev->degraded > 1)
8449                 return ERR_PTR(-EINVAL);
8450
8451         /* Should check if there are write-behind devices? */
8452
8453         chunksect = 64*2; /* 64K by default */
8454
8455         /* The array must be an exact multiple of chunksize */
8456         while (chunksect && (mddev->array_sectors & (chunksect-1)))
8457                 chunksect >>= 1;
8458
8459         if ((chunksect<<9) < RAID5_STRIPE_SIZE((struct r5conf *)mddev->private))
8460                 /* array size does not allow a suitable chunk size */
8461                 return ERR_PTR(-EINVAL);
8462
8463         mddev->new_level = 5;
8464         mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
8465         mddev->new_chunk_sectors = chunksect;
8466
8467         ret = setup_conf(mddev);
8468         if (!IS_ERR(ret))
8469                 mddev_clear_unsupported_flags(mddev,
8470                         UNSUPPORTED_MDDEV_FLAGS);
8471         return ret;
8472 }
8473
8474 static void *raid5_takeover_raid6(struct mddev *mddev)
8475 {
8476         int new_layout;
8477
8478         switch (mddev->layout) {
8479         case ALGORITHM_LEFT_ASYMMETRIC_6:
8480                 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
8481                 break;
8482         case ALGORITHM_RIGHT_ASYMMETRIC_6:
8483                 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
8484                 break;
8485         case ALGORITHM_LEFT_SYMMETRIC_6:
8486                 new_layout = ALGORITHM_LEFT_SYMMETRIC;
8487                 break;
8488         case ALGORITHM_RIGHT_SYMMETRIC_6:
8489                 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
8490                 break;
8491         case ALGORITHM_PARITY_0_6:
8492                 new_layout = ALGORITHM_PARITY_0;
8493                 break;
8494         case ALGORITHM_PARITY_N:
8495                 new_layout = ALGORITHM_PARITY_N;
8496                 break;
8497         default:
8498                 return ERR_PTR(-EINVAL);
8499         }
8500         mddev->new_level = 5;
8501         mddev->new_layout = new_layout;
8502         mddev->delta_disks = -1;
8503         mddev->raid_disks -= 1;
8504         return setup_conf(mddev);
8505 }
8506
8507 static int raid5_check_reshape(struct mddev *mddev)
8508 {
8509         /* For a 2-drive array, the layout and chunk size can be changed
8510          * immediately as not restriping is needed.
8511          * For larger arrays we record the new value - after validation
8512          * to be used by a reshape pass.
8513          */
8514         struct r5conf *conf = mddev->private;
8515         int new_chunk = mddev->new_chunk_sectors;
8516
8517         if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
8518                 return -EINVAL;
8519         if (new_chunk > 0) {
8520                 if (!is_power_of_2(new_chunk))
8521                         return -EINVAL;
8522                 if (new_chunk < (PAGE_SIZE>>9))
8523                         return -EINVAL;
8524                 if (mddev->array_sectors & (new_chunk-1))
8525                         /* not factor of array size */
8526                         return -EINVAL;
8527         }
8528
8529         /* They look valid */
8530
8531         if (mddev->raid_disks == 2) {
8532                 /* can make the change immediately */
8533                 if (mddev->new_layout >= 0) {
8534                         conf->algorithm = mddev->new_layout;
8535                         mddev->layout = mddev->new_layout;
8536                 }
8537                 if (new_chunk > 0) {
8538                         conf->chunk_sectors = new_chunk ;
8539                         mddev->chunk_sectors = new_chunk;
8540                 }
8541                 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8542                 md_wakeup_thread(mddev->thread);
8543         }
8544         return check_reshape(mddev);
8545 }
8546
8547 static int raid6_check_reshape(struct mddev *mddev)
8548 {
8549         int new_chunk = mddev->new_chunk_sectors;
8550
8551         if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
8552                 return -EINVAL;
8553         if (new_chunk > 0) {
8554                 if (!is_power_of_2(new_chunk))
8555                         return -EINVAL;
8556                 if (new_chunk < (PAGE_SIZE >> 9))
8557                         return -EINVAL;
8558                 if (mddev->array_sectors & (new_chunk-1))
8559                         /* not factor of array size */
8560                         return -EINVAL;
8561         }
8562
8563         /* They look valid */
8564         return check_reshape(mddev);
8565 }
8566
8567 static void *raid5_takeover(struct mddev *mddev)
8568 {
8569         /* raid5 can take over:
8570          *  raid0 - if there is only one strip zone - make it a raid4 layout
8571          *  raid1 - if there are two drives.  We need to know the chunk size
8572          *  raid4 - trivial - just use a raid4 layout.
8573          *  raid6 - Providing it is a *_6 layout
8574          */
8575         if (mddev->level == 0)
8576                 return raid45_takeover_raid0(mddev, 5);
8577         if (mddev->level == 1)
8578                 return raid5_takeover_raid1(mddev);
8579         if (mddev->level == 4) {
8580                 mddev->new_layout = ALGORITHM_PARITY_N;
8581                 mddev->new_level = 5;
8582                 return setup_conf(mddev);
8583         }
8584         if (mddev->level == 6)
8585                 return raid5_takeover_raid6(mddev);
8586
8587         return ERR_PTR(-EINVAL);
8588 }
8589
8590 static void *raid4_takeover(struct mddev *mddev)
8591 {
8592         /* raid4 can take over:
8593          *  raid0 - if there is only one strip zone
8594          *  raid5 - if layout is right
8595          */
8596         if (mddev->level == 0)
8597                 return raid45_takeover_raid0(mddev, 4);
8598         if (mddev->level == 5 &&
8599             mddev->layout == ALGORITHM_PARITY_N) {
8600                 mddev->new_layout = 0;
8601                 mddev->new_level = 4;
8602                 return setup_conf(mddev);
8603         }
8604         return ERR_PTR(-EINVAL);
8605 }
8606
8607 static struct md_personality raid5_personality;
8608
8609 static void *raid6_takeover(struct mddev *mddev)
8610 {
8611         /* Currently can only take over a raid5.  We map the
8612          * personality to an equivalent raid6 personality
8613          * with the Q block at the end.
8614          */
8615         int new_layout;
8616
8617         if (mddev->pers != &raid5_personality)
8618                 return ERR_PTR(-EINVAL);
8619         if (mddev->degraded > 1)
8620                 return ERR_PTR(-EINVAL);
8621         if (mddev->raid_disks > 253)
8622                 return ERR_PTR(-EINVAL);
8623         if (mddev->raid_disks < 3)
8624                 return ERR_PTR(-EINVAL);
8625
8626         switch (mddev->layout) {
8627         case ALGORITHM_LEFT_ASYMMETRIC:
8628                 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
8629                 break;
8630         case ALGORITHM_RIGHT_ASYMMETRIC:
8631                 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
8632                 break;
8633         case ALGORITHM_LEFT_SYMMETRIC:
8634                 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
8635                 break;
8636         case ALGORITHM_RIGHT_SYMMETRIC:
8637                 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
8638                 break;
8639         case ALGORITHM_PARITY_0:
8640                 new_layout = ALGORITHM_PARITY_0_6;
8641                 break;
8642         case ALGORITHM_PARITY_N:
8643                 new_layout = ALGORITHM_PARITY_N;
8644                 break;
8645         default:
8646                 return ERR_PTR(-EINVAL);
8647         }
8648         mddev->new_level = 6;
8649         mddev->new_layout = new_layout;
8650         mddev->delta_disks = 1;
8651         mddev->raid_disks += 1;
8652         return setup_conf(mddev);
8653 }
8654
8655 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
8656 {
8657         struct r5conf *conf;
8658         int err;
8659
8660         err = mddev_lock(mddev);
8661         if (err)
8662                 return err;
8663         conf = mddev->private;
8664         if (!conf) {
8665                 mddev_unlock(mddev);
8666                 return -ENODEV;
8667         }
8668
8669         if (strncmp(buf, "ppl", 3) == 0) {
8670                 /* ppl only works with RAID 5 */
8671                 if (!raid5_has_ppl(conf) && conf->level == 5) {
8672                         err = log_init(conf, NULL, true);
8673                         if (!err) {
8674                                 err = resize_stripes(conf, conf->pool_size);
8675                                 if (err)
8676                                         log_exit(conf);
8677                         }
8678                 } else
8679                         err = -EINVAL;
8680         } else if (strncmp(buf, "resync", 6) == 0) {
8681                 if (raid5_has_ppl(conf)) {
8682                         mddev_suspend(mddev);
8683                         log_exit(conf);
8684                         mddev_resume(mddev);
8685                         err = resize_stripes(conf, conf->pool_size);
8686                 } else if (test_bit(MD_HAS_JOURNAL, &conf->mddev->flags) &&
8687                            r5l_log_disk_error(conf)) {
8688                         bool journal_dev_exists = false;
8689                         struct md_rdev *rdev;
8690
8691                         rdev_for_each(rdev, mddev)
8692                                 if (test_bit(Journal, &rdev->flags)) {
8693                                         journal_dev_exists = true;
8694                                         break;
8695                                 }
8696
8697                         if (!journal_dev_exists) {
8698                                 mddev_suspend(mddev);
8699                                 clear_bit(MD_HAS_JOURNAL, &mddev->flags);
8700                                 mddev_resume(mddev);
8701                         } else  /* need remove journal device first */
8702                                 err = -EBUSY;
8703                 } else
8704                         err = -EINVAL;
8705         } else {
8706                 err = -EINVAL;
8707         }
8708
8709         if (!err)
8710                 md_update_sb(mddev, 1);
8711
8712         mddev_unlock(mddev);
8713
8714         return err;
8715 }
8716
8717 static int raid5_start(struct mddev *mddev)
8718 {
8719         struct r5conf *conf = mddev->private;
8720
8721         return r5l_start(conf->log);
8722 }
8723
8724 static struct md_personality raid6_personality =
8725 {
8726         .name           = "raid6",
8727         .level          = 6,
8728         .owner          = THIS_MODULE,
8729         .make_request   = raid5_make_request,
8730         .run            = raid5_run,
8731         .start          = raid5_start,
8732         .free           = raid5_free,
8733         .status         = raid5_status,
8734         .error_handler  = raid5_error,
8735         .hot_add_disk   = raid5_add_disk,
8736         .hot_remove_disk= raid5_remove_disk,
8737         .spare_active   = raid5_spare_active,
8738         .sync_request   = raid5_sync_request,
8739         .resize         = raid5_resize,
8740         .size           = raid5_size,
8741         .check_reshape  = raid6_check_reshape,
8742         .start_reshape  = raid5_start_reshape,
8743         .finish_reshape = raid5_finish_reshape,
8744         .quiesce        = raid5_quiesce,
8745         .takeover       = raid6_takeover,
8746         .change_consistency_policy = raid5_change_consistency_policy,
8747 };
8748 static struct md_personality raid5_personality =
8749 {
8750         .name           = "raid5",
8751         .level          = 5,
8752         .owner          = THIS_MODULE,
8753         .make_request   = raid5_make_request,
8754         .run            = raid5_run,
8755         .start          = raid5_start,
8756         .free           = raid5_free,
8757         .status         = raid5_status,
8758         .error_handler  = raid5_error,
8759         .hot_add_disk   = raid5_add_disk,
8760         .hot_remove_disk= raid5_remove_disk,
8761         .spare_active   = raid5_spare_active,
8762         .sync_request   = raid5_sync_request,
8763         .resize         = raid5_resize,
8764         .size           = raid5_size,
8765         .check_reshape  = raid5_check_reshape,
8766         .start_reshape  = raid5_start_reshape,
8767         .finish_reshape = raid5_finish_reshape,
8768         .quiesce        = raid5_quiesce,
8769         .takeover       = raid5_takeover,
8770         .change_consistency_policy = raid5_change_consistency_policy,
8771 };
8772
8773 static struct md_personality raid4_personality =
8774 {
8775         .name           = "raid4",
8776         .level          = 4,
8777         .owner          = THIS_MODULE,
8778         .make_request   = raid5_make_request,
8779         .run            = raid5_run,
8780         .start          = raid5_start,
8781         .free           = raid5_free,
8782         .status         = raid5_status,
8783         .error_handler  = raid5_error,
8784         .hot_add_disk   = raid5_add_disk,
8785         .hot_remove_disk= raid5_remove_disk,
8786         .spare_active   = raid5_spare_active,
8787         .sync_request   = raid5_sync_request,
8788         .resize         = raid5_resize,
8789         .size           = raid5_size,
8790         .check_reshape  = raid5_check_reshape,
8791         .start_reshape  = raid5_start_reshape,
8792         .finish_reshape = raid5_finish_reshape,
8793         .quiesce        = raid5_quiesce,
8794         .takeover       = raid4_takeover,
8795         .change_consistency_policy = raid5_change_consistency_policy,
8796 };
8797
8798 static int __init raid5_init(void)
8799 {
8800         int ret;
8801
8802         raid5_wq = alloc_workqueue("raid5wq",
8803                 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
8804         if (!raid5_wq)
8805                 return -ENOMEM;
8806
8807         ret = cpuhp_setup_state_multi(CPUHP_MD_RAID5_PREPARE,
8808                                       "md/raid5:prepare",
8809                                       raid456_cpu_up_prepare,
8810                                       raid456_cpu_dead);
8811         if (ret) {
8812                 destroy_workqueue(raid5_wq);
8813                 return ret;
8814         }
8815         register_md_personality(&raid6_personality);
8816         register_md_personality(&raid5_personality);
8817         register_md_personality(&raid4_personality);
8818         return 0;
8819 }
8820
8821 static void raid5_exit(void)
8822 {
8823         unregister_md_personality(&raid6_personality);
8824         unregister_md_personality(&raid5_personality);
8825         unregister_md_personality(&raid4_personality);
8826         cpuhp_remove_multi_state(CPUHP_MD_RAID5_PREPARE);
8827         destroy_workqueue(raid5_wq);
8828 }
8829
8830 module_init(raid5_init);
8831 module_exit(raid5_exit);
8832 MODULE_LICENSE("GPL");
8833 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
8834 MODULE_ALIAS("md-personality-4"); /* RAID5 */
8835 MODULE_ALIAS("md-raid5");
8836 MODULE_ALIAS("md-raid4");
8837 MODULE_ALIAS("md-level-5");
8838 MODULE_ALIAS("md-level-4");
8839 MODULE_ALIAS("md-personality-8"); /* RAID6 */
8840 MODULE_ALIAS("md-raid6");
8841 MODULE_ALIAS("md-level-6");
8842
8843 /* This used to be two separate modules, they were: */
8844 MODULE_ALIAS("raid5");
8845 MODULE_ALIAS("raid6");