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