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