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