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