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