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