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