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