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