7c22e19aca82f5cc312c8b14fe49a9fc7ec55cea
[pandora-kernel.git] / drivers / md / raid5.c
1 /*
2  * raid5.c : Multiple Devices driver for Linux
3  *         Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
4  *         Copyright (C) 1999, 2000 Ingo Molnar
5  *         Copyright (C) 2002, 2003 H. Peter Anvin
6  *
7  * RAID-4/5/6 management functions.
8  * Thanks to Penguin Computing for making the RAID-6 development possible
9  * by donating a test server!
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2, or (at your option)
14  * any later version.
15  *
16  * You should have received a copy of the GNU General Public License
17  * (for example /usr/src/linux/COPYING); if not, write to the Free
18  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 /*
22  * BITMAP UNPLUGGING:
23  *
24  * The sequencing for updating the bitmap reliably is a little
25  * subtle (and I got it wrong the first time) so it deserves some
26  * explanation.
27  *
28  * We group bitmap updates into batches.  Each batch has a number.
29  * We may write out several batches at once, but that isn't very important.
30  * conf->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 static void
1931 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
1932                          int rcw, int expand)
1933 {
1934         int i, pd_idx = sh->pd_idx, disks = sh->disks;
1935         raid5_conf_t *conf = sh->raid_conf;
1936         int level = conf->level;
1937
1938         if (rcw) {
1939                 /* if we are not expanding this is a proper write request, and
1940                  * there will be bios with new data to be drained into the
1941                  * stripe cache
1942                  */
1943                 if (!expand) {
1944                         sh->reconstruct_state = reconstruct_state_drain_run;
1945                         set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
1946                 } else
1947                         sh->reconstruct_state = reconstruct_state_run;
1948
1949                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
1950
1951                 for (i = disks; i--; ) {
1952                         struct r5dev *dev = &sh->dev[i];
1953
1954                         if (dev->towrite) {
1955                                 set_bit(R5_LOCKED, &dev->flags);
1956                                 set_bit(R5_Wantdrain, &dev->flags);
1957                                 if (!expand)
1958                                         clear_bit(R5_UPTODATE, &dev->flags);
1959                                 s->locked++;
1960                         }
1961                 }
1962                 if (s->locked + conf->max_degraded == disks)
1963                         if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
1964                                 atomic_inc(&conf->pending_full_writes);
1965         } else {
1966                 BUG_ON(level == 6);
1967                 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
1968                         test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
1969
1970                 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
1971                 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
1972                 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
1973                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
1974
1975                 for (i = disks; i--; ) {
1976                         struct r5dev *dev = &sh->dev[i];
1977                         if (i == pd_idx)
1978                                 continue;
1979
1980                         if (dev->towrite &&
1981                             (test_bit(R5_UPTODATE, &dev->flags) ||
1982                              test_bit(R5_Wantcompute, &dev->flags))) {
1983                                 set_bit(R5_Wantdrain, &dev->flags);
1984                                 set_bit(R5_LOCKED, &dev->flags);
1985                                 clear_bit(R5_UPTODATE, &dev->flags);
1986                                 s->locked++;
1987                         }
1988                 }
1989         }
1990
1991         /* keep the parity disk(s) locked while asynchronous operations
1992          * are in flight
1993          */
1994         set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
1995         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
1996         s->locked++;
1997
1998         if (level == 6) {
1999                 int qd_idx = sh->qd_idx;
2000                 struct r5dev *dev = &sh->dev[qd_idx];
2001
2002                 set_bit(R5_LOCKED, &dev->flags);
2003                 clear_bit(R5_UPTODATE, &dev->flags);
2004                 s->locked++;
2005         }
2006
2007         pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2008                 __func__, (unsigned long long)sh->sector,
2009                 s->locked, s->ops_request);
2010 }
2011
2012 /*
2013  * Each stripe/dev can have one or more bion attached.
2014  * toread/towrite point to the first in a chain.
2015  * The bi_next chain must be in order.
2016  */
2017 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx, int forwrite)
2018 {
2019         struct bio **bip;
2020         raid5_conf_t *conf = sh->raid_conf;
2021         int firstwrite=0;
2022
2023         pr_debug("adding bh b#%llu to stripe s#%llu\n",
2024                 (unsigned long long)bi->bi_sector,
2025                 (unsigned long long)sh->sector);
2026
2027
2028         spin_lock(&sh->lock);
2029         spin_lock_irq(&conf->device_lock);
2030         if (forwrite) {
2031                 bip = &sh->dev[dd_idx].towrite;
2032                 if (*bip == NULL && sh->dev[dd_idx].written == NULL)
2033                         firstwrite = 1;
2034         } else
2035                 bip = &sh->dev[dd_idx].toread;
2036         while (*bip && (*bip)->bi_sector < bi->bi_sector) {
2037                 if ((*bip)->bi_sector + ((*bip)->bi_size >> 9) > bi->bi_sector)
2038                         goto overlap;
2039                 bip = & (*bip)->bi_next;
2040         }
2041         if (*bip && (*bip)->bi_sector < bi->bi_sector + ((bi->bi_size)>>9))
2042                 goto overlap;
2043
2044         BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
2045         if (*bip)
2046                 bi->bi_next = *bip;
2047         *bip = bi;
2048         bi->bi_phys_segments++;
2049         spin_unlock_irq(&conf->device_lock);
2050         spin_unlock(&sh->lock);
2051
2052         pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
2053                 (unsigned long long)bi->bi_sector,
2054                 (unsigned long long)sh->sector, dd_idx);
2055
2056         if (conf->mddev->bitmap && firstwrite) {
2057                 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
2058                                   STRIPE_SECTORS, 0);
2059                 sh->bm_seq = conf->seq_flush+1;
2060                 set_bit(STRIPE_BIT_DELAY, &sh->state);
2061         }
2062
2063         if (forwrite) {
2064                 /* check if page is covered */
2065                 sector_t sector = sh->dev[dd_idx].sector;
2066                 for (bi=sh->dev[dd_idx].towrite;
2067                      sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
2068                              bi && bi->bi_sector <= sector;
2069                      bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
2070                         if (bi->bi_sector + (bi->bi_size>>9) >= sector)
2071                                 sector = bi->bi_sector + (bi->bi_size>>9);
2072                 }
2073                 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
2074                         set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags);
2075         }
2076         return 1;
2077
2078  overlap:
2079         set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
2080         spin_unlock_irq(&conf->device_lock);
2081         spin_unlock(&sh->lock);
2082         return 0;
2083 }
2084
2085 static void end_reshape(raid5_conf_t *conf);
2086
2087 static void stripe_set_idx(sector_t stripe, raid5_conf_t *conf, int previous,
2088                             struct stripe_head *sh)
2089 {
2090         int sectors_per_chunk =
2091                 previous ? (conf->prev_chunk >> 9)
2092                          : (conf->chunk_size >> 9);
2093         int dd_idx;
2094         int chunk_offset = sector_div(stripe, sectors_per_chunk);
2095         int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
2096
2097         raid5_compute_sector(conf,
2098                              stripe * (disks - conf->max_degraded)
2099                              *sectors_per_chunk + chunk_offset,
2100                              previous,
2101                              &dd_idx, sh);
2102 }
2103
2104 static void
2105 handle_failed_stripe(raid5_conf_t *conf, struct stripe_head *sh,
2106                                 struct stripe_head_state *s, int disks,
2107                                 struct bio **return_bi)
2108 {
2109         int i;
2110         for (i = disks; i--; ) {
2111                 struct bio *bi;
2112                 int bitmap_end = 0;
2113
2114                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2115                         mdk_rdev_t *rdev;
2116                         rcu_read_lock();
2117                         rdev = rcu_dereference(conf->disks[i].rdev);
2118                         if (rdev && test_bit(In_sync, &rdev->flags))
2119                                 /* multiple read failures in one stripe */
2120                                 md_error(conf->mddev, rdev);
2121                         rcu_read_unlock();
2122                 }
2123                 spin_lock_irq(&conf->device_lock);
2124                 /* fail all writes first */
2125                 bi = sh->dev[i].towrite;
2126                 sh->dev[i].towrite = NULL;
2127                 if (bi) {
2128                         s->to_write--;
2129                         bitmap_end = 1;
2130                 }
2131
2132                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2133                         wake_up(&conf->wait_for_overlap);
2134
2135                 while (bi && bi->bi_sector <
2136                         sh->dev[i].sector + STRIPE_SECTORS) {
2137                         struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
2138                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
2139                         if (!raid5_dec_bi_phys_segments(bi)) {
2140                                 md_write_end(conf->mddev);
2141                                 bi->bi_next = *return_bi;
2142                                 *return_bi = bi;
2143                         }
2144                         bi = nextbi;
2145                 }
2146                 /* and fail all 'written' */
2147                 bi = sh->dev[i].written;
2148                 sh->dev[i].written = NULL;
2149                 if (bi) bitmap_end = 1;
2150                 while (bi && bi->bi_sector <
2151                        sh->dev[i].sector + STRIPE_SECTORS) {
2152                         struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
2153                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
2154                         if (!raid5_dec_bi_phys_segments(bi)) {
2155                                 md_write_end(conf->mddev);
2156                                 bi->bi_next = *return_bi;
2157                                 *return_bi = bi;
2158                         }
2159                         bi = bi2;
2160                 }
2161
2162                 /* fail any reads if this device is non-operational and
2163                  * the data has not reached the cache yet.
2164                  */
2165                 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
2166                     (!test_bit(R5_Insync, &sh->dev[i].flags) ||
2167                       test_bit(R5_ReadError, &sh->dev[i].flags))) {
2168                         bi = sh->dev[i].toread;
2169                         sh->dev[i].toread = NULL;
2170                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2171                                 wake_up(&conf->wait_for_overlap);
2172                         if (bi) s->to_read--;
2173                         while (bi && bi->bi_sector <
2174                                sh->dev[i].sector + STRIPE_SECTORS) {
2175                                 struct bio *nextbi =
2176                                         r5_next_bio(bi, sh->dev[i].sector);
2177                                 clear_bit(BIO_UPTODATE, &bi->bi_flags);
2178                                 if (!raid5_dec_bi_phys_segments(bi)) {
2179                                         bi->bi_next = *return_bi;
2180                                         *return_bi = bi;
2181                                 }
2182                                 bi = nextbi;
2183                         }
2184                 }
2185                 spin_unlock_irq(&conf->device_lock);
2186                 if (bitmap_end)
2187                         bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2188                                         STRIPE_SECTORS, 0, 0);
2189         }
2190
2191         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2192                 if (atomic_dec_and_test(&conf->pending_full_writes))
2193                         md_wakeup_thread(conf->mddev->thread);
2194 }
2195
2196 /* fetch_block5 - checks the given member device to see if its data needs
2197  * to be read or computed to satisfy a request.
2198  *
2199  * Returns 1 when no more member devices need to be checked, otherwise returns
2200  * 0 to tell the loop in handle_stripe_fill5 to continue
2201  */
2202 static int fetch_block5(struct stripe_head *sh, struct stripe_head_state *s,
2203                         int disk_idx, int disks)
2204 {
2205         struct r5dev *dev = &sh->dev[disk_idx];
2206         struct r5dev *failed_dev = &sh->dev[s->failed_num];
2207
2208         /* is the data in this block needed, and can we get it? */
2209         if (!test_bit(R5_LOCKED, &dev->flags) &&
2210             !test_bit(R5_UPTODATE, &dev->flags) &&
2211             (dev->toread ||
2212              (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
2213              s->syncing || s->expanding ||
2214              (s->failed &&
2215               (failed_dev->toread ||
2216                (failed_dev->towrite &&
2217                 !test_bit(R5_OVERWRITE, &failed_dev->flags)))))) {
2218                 /* We would like to get this block, possibly by computing it,
2219                  * otherwise read it if the backing disk is insync
2220                  */
2221                 if ((s->uptodate == disks - 1) &&
2222                     (s->failed && disk_idx == s->failed_num)) {
2223                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2224                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2225                         set_bit(R5_Wantcompute, &dev->flags);
2226                         sh->ops.target = disk_idx;
2227                         sh->ops.target2 = -1;
2228                         s->req_compute = 1;
2229                         /* Careful: from this point on 'uptodate' is in the eye
2230                          * of raid_run_ops which services 'compute' operations
2231                          * before writes. R5_Wantcompute flags a block that will
2232                          * be R5_UPTODATE by the time it is needed for a
2233                          * subsequent operation.
2234                          */
2235                         s->uptodate++;
2236                         return 1; /* uptodate + compute == disks */
2237                 } else if (test_bit(R5_Insync, &dev->flags)) {
2238                         set_bit(R5_LOCKED, &dev->flags);
2239                         set_bit(R5_Wantread, &dev->flags);
2240                         s->locked++;
2241                         pr_debug("Reading block %d (sync=%d)\n", disk_idx,
2242                                 s->syncing);
2243                 }
2244         }
2245
2246         return 0;
2247 }
2248
2249 /**
2250  * handle_stripe_fill5 - read or compute data to satisfy pending requests.
2251  */
2252 static void handle_stripe_fill5(struct stripe_head *sh,
2253                         struct stripe_head_state *s, int disks)
2254 {
2255         int i;
2256
2257         /* look for blocks to read/compute, skip this if a compute
2258          * is already in flight, or if the stripe contents are in the
2259          * midst of changing due to a write
2260          */
2261         if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
2262             !sh->reconstruct_state)
2263                 for (i = disks; i--; )
2264                         if (fetch_block5(sh, s, i, disks))
2265                                 break;
2266         set_bit(STRIPE_HANDLE, &sh->state);
2267 }
2268
2269 /* fetch_block6 - checks the given member device to see if its data needs
2270  * to be read or computed to satisfy a request.
2271  *
2272  * Returns 1 when no more member devices need to be checked, otherwise returns
2273  * 0 to tell the loop in handle_stripe_fill6 to continue
2274  */
2275 static int fetch_block6(struct stripe_head *sh, struct stripe_head_state *s,
2276                          struct r6_state *r6s, int disk_idx, int disks)
2277 {
2278         struct r5dev *dev = &sh->dev[disk_idx];
2279         struct r5dev *fdev[2] = { &sh->dev[r6s->failed_num[0]],
2280                                   &sh->dev[r6s->failed_num[1]] };
2281
2282         if (!test_bit(R5_LOCKED, &dev->flags) &&
2283             !test_bit(R5_UPTODATE, &dev->flags) &&
2284             (dev->toread ||
2285              (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
2286              s->syncing || s->expanding ||
2287              (s->failed >= 1 &&
2288               (fdev[0]->toread || s->to_write)) ||
2289              (s->failed >= 2 &&
2290               (fdev[1]->toread || s->to_write)))) {
2291                 /* we would like to get this block, possibly by computing it,
2292                  * otherwise read it if the backing disk is insync
2293                  */
2294                 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
2295                 BUG_ON(test_bit(R5_Wantread, &dev->flags));
2296                 if ((s->uptodate == disks - 1) &&
2297                     (s->failed && (disk_idx == r6s->failed_num[0] ||
2298                                    disk_idx == r6s->failed_num[1]))) {
2299                         /* have disk failed, and we're requested to fetch it;
2300                          * do compute it
2301                          */
2302                         pr_debug("Computing stripe %llu block %d\n",
2303                                (unsigned long long)sh->sector, disk_idx);
2304                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2305                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2306                         set_bit(R5_Wantcompute, &dev->flags);
2307                         sh->ops.target = disk_idx;
2308                         sh->ops.target2 = -1; /* no 2nd target */
2309                         s->req_compute = 1;
2310                         s->uptodate++;
2311                         return 1;
2312                 } else if (s->uptodate == disks-2 && s->failed >= 2) {
2313                         /* Computing 2-failure is *very* expensive; only
2314                          * do it if failed >= 2
2315                          */
2316                         int other;
2317                         for (other = disks; other--; ) {
2318                                 if (other == disk_idx)
2319                                         continue;
2320                                 if (!test_bit(R5_UPTODATE,
2321                                       &sh->dev[other].flags))
2322                                         break;
2323                         }
2324                         BUG_ON(other < 0);
2325                         pr_debug("Computing stripe %llu blocks %d,%d\n",
2326                                (unsigned long long)sh->sector,
2327                                disk_idx, other);
2328                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2329                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2330                         set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
2331                         set_bit(R5_Wantcompute, &sh->dev[other].flags);
2332                         sh->ops.target = disk_idx;
2333                         sh->ops.target2 = other;
2334                         s->uptodate += 2;
2335                         s->req_compute = 1;
2336                         return 1;
2337                 } else if (test_bit(R5_Insync, &dev->flags)) {
2338                         set_bit(R5_LOCKED, &dev->flags);
2339                         set_bit(R5_Wantread, &dev->flags);
2340                         s->locked++;
2341                         pr_debug("Reading block %d (sync=%d)\n",
2342                                 disk_idx, s->syncing);
2343                 }
2344         }
2345
2346         return 0;
2347 }
2348
2349 /**
2350  * handle_stripe_fill6 - read or compute data to satisfy pending requests.
2351  */
2352 static void handle_stripe_fill6(struct stripe_head *sh,
2353                         struct stripe_head_state *s, struct r6_state *r6s,
2354                         int disks)
2355 {
2356         int i;
2357
2358         /* look for blocks to read/compute, skip this if a compute
2359          * is already in flight, or if the stripe contents are in the
2360          * midst of changing due to a write
2361          */
2362         if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
2363             !sh->reconstruct_state)
2364                 for (i = disks; i--; )
2365                         if (fetch_block6(sh, s, r6s, i, disks))
2366                                 break;
2367         set_bit(STRIPE_HANDLE, &sh->state);
2368 }
2369
2370
2371 /* handle_stripe_clean_event
2372  * any written block on an uptodate or failed drive can be returned.
2373  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
2374  * never LOCKED, so we don't need to test 'failed' directly.
2375  */
2376 static void handle_stripe_clean_event(raid5_conf_t *conf,
2377         struct stripe_head *sh, int disks, struct bio **return_bi)
2378 {
2379         int i;
2380         struct r5dev *dev;
2381
2382         for (i = disks; i--; )
2383                 if (sh->dev[i].written) {
2384                         dev = &sh->dev[i];
2385                         if (!test_bit(R5_LOCKED, &dev->flags) &&
2386                                 test_bit(R5_UPTODATE, &dev->flags)) {
2387                                 /* We can return any write requests */
2388                                 struct bio *wbi, *wbi2;
2389                                 int bitmap_end = 0;
2390                                 pr_debug("Return write for disc %d\n", i);
2391                                 spin_lock_irq(&conf->device_lock);
2392                                 wbi = dev->written;
2393                                 dev->written = NULL;
2394                                 while (wbi && wbi->bi_sector <
2395                                         dev->sector + STRIPE_SECTORS) {
2396                                         wbi2 = r5_next_bio(wbi, dev->sector);
2397                                         if (!raid5_dec_bi_phys_segments(wbi)) {
2398                                                 md_write_end(conf->mddev);
2399                                                 wbi->bi_next = *return_bi;
2400                                                 *return_bi = wbi;
2401                                         }
2402                                         wbi = wbi2;
2403                                 }
2404                                 if (dev->towrite == NULL)
2405                                         bitmap_end = 1;
2406                                 spin_unlock_irq(&conf->device_lock);
2407                                 if (bitmap_end)
2408                                         bitmap_endwrite(conf->mddev->bitmap,
2409                                                         sh->sector,
2410                                                         STRIPE_SECTORS,
2411                                          !test_bit(STRIPE_DEGRADED, &sh->state),
2412                                                         0);
2413                         }
2414                 }
2415
2416         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2417                 if (atomic_dec_and_test(&conf->pending_full_writes))
2418                         md_wakeup_thread(conf->mddev->thread);
2419 }
2420
2421 static void handle_stripe_dirtying5(raid5_conf_t *conf,
2422                 struct stripe_head *sh, struct stripe_head_state *s, int disks)
2423 {
2424         int rmw = 0, rcw = 0, i;
2425         for (i = disks; i--; ) {
2426                 /* would I have to read this buffer for read_modify_write */
2427                 struct r5dev *dev = &sh->dev[i];
2428                 if ((dev->towrite || i == sh->pd_idx) &&
2429                     !test_bit(R5_LOCKED, &dev->flags) &&
2430                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2431                       test_bit(R5_Wantcompute, &dev->flags))) {
2432                         if (test_bit(R5_Insync, &dev->flags))
2433                                 rmw++;
2434                         else
2435                                 rmw += 2*disks;  /* cannot read it */
2436                 }
2437                 /* Would I have to read this buffer for reconstruct_write */
2438                 if (!test_bit(R5_OVERWRITE, &dev->flags) && i != sh->pd_idx &&
2439                     !test_bit(R5_LOCKED, &dev->flags) &&
2440                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2441                     test_bit(R5_Wantcompute, &dev->flags))) {
2442                         if (test_bit(R5_Insync, &dev->flags)) rcw++;
2443                         else
2444                                 rcw += 2*disks;
2445                 }
2446         }
2447         pr_debug("for sector %llu, rmw=%d rcw=%d\n",
2448                 (unsigned long long)sh->sector, rmw, rcw);
2449         set_bit(STRIPE_HANDLE, &sh->state);
2450         if (rmw < rcw && rmw > 0)
2451                 /* prefer read-modify-write, but need to get some data */
2452                 for (i = disks; i--; ) {
2453                         struct r5dev *dev = &sh->dev[i];
2454                         if ((dev->towrite || i == sh->pd_idx) &&
2455                             !test_bit(R5_LOCKED, &dev->flags) &&
2456                             !(test_bit(R5_UPTODATE, &dev->flags) ||
2457                             test_bit(R5_Wantcompute, &dev->flags)) &&
2458                             test_bit(R5_Insync, &dev->flags)) {
2459                                 if (
2460                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2461                                         pr_debug("Read_old block "
2462                                                 "%d for r-m-w\n", i);
2463                                         set_bit(R5_LOCKED, &dev->flags);
2464                                         set_bit(R5_Wantread, &dev->flags);
2465                                         s->locked++;
2466                                 } else {
2467                                         set_bit(STRIPE_DELAYED, &sh->state);
2468                                         set_bit(STRIPE_HANDLE, &sh->state);
2469                                 }
2470                         }
2471                 }
2472         if (rcw <= rmw && rcw > 0)
2473                 /* want reconstruct write, but need to get some data */
2474                 for (i = disks; i--; ) {
2475                         struct r5dev *dev = &sh->dev[i];
2476                         if (!test_bit(R5_OVERWRITE, &dev->flags) &&
2477                             i != sh->pd_idx &&
2478                             !test_bit(R5_LOCKED, &dev->flags) &&
2479                             !(test_bit(R5_UPTODATE, &dev->flags) ||
2480                             test_bit(R5_Wantcompute, &dev->flags)) &&
2481                             test_bit(R5_Insync, &dev->flags)) {
2482                                 if (
2483                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2484                                         pr_debug("Read_old block "
2485                                                 "%d for Reconstruct\n", i);
2486                                         set_bit(R5_LOCKED, &dev->flags);
2487                                         set_bit(R5_Wantread, &dev->flags);
2488                                         s->locked++;
2489                                 } else {
2490                                         set_bit(STRIPE_DELAYED, &sh->state);
2491                                         set_bit(STRIPE_HANDLE, &sh->state);
2492                                 }
2493                         }
2494                 }
2495         /* now if nothing is locked, and if we have enough data,
2496          * we can start a write request
2497          */
2498         /* since handle_stripe can be called at any time we need to handle the
2499          * case where a compute block operation has been submitted and then a
2500          * subsequent call wants to start a write request.  raid_run_ops only
2501          * handles the case where compute block and reconstruct are requested
2502          * simultaneously.  If this is not the case then new writes need to be
2503          * held off until the compute completes.
2504          */
2505         if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
2506             (s->locked == 0 && (rcw == 0 || rmw == 0) &&
2507             !test_bit(STRIPE_BIT_DELAY, &sh->state)))
2508                 schedule_reconstruction(sh, s, rcw == 0, 0);
2509 }
2510
2511 static void handle_stripe_dirtying6(raid5_conf_t *conf,
2512                 struct stripe_head *sh, struct stripe_head_state *s,
2513                 struct r6_state *r6s, int disks)
2514 {
2515         int rcw = 0, pd_idx = sh->pd_idx, i;
2516         int qd_idx = sh->qd_idx;
2517
2518         set_bit(STRIPE_HANDLE, &sh->state);
2519         for (i = disks; i--; ) {
2520                 struct r5dev *dev = &sh->dev[i];
2521                 /* check if we haven't enough data */
2522                 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
2523                     i != pd_idx && i != qd_idx &&
2524                     !test_bit(R5_LOCKED, &dev->flags) &&
2525                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2526                       test_bit(R5_Wantcompute, &dev->flags))) {
2527                         rcw++;
2528                         if (!test_bit(R5_Insync, &dev->flags))
2529                                 continue; /* it's a failed drive */
2530
2531                         if (
2532                           test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2533                                 pr_debug("Read_old stripe %llu "
2534                                         "block %d for Reconstruct\n",
2535                                      (unsigned long long)sh->sector, i);
2536                                 set_bit(R5_LOCKED, &dev->flags);
2537                                 set_bit(R5_Wantread, &dev->flags);
2538                                 s->locked++;
2539                         } else {
2540                                 pr_debug("Request delayed stripe %llu "
2541                                         "block %d for Reconstruct\n",
2542                                      (unsigned long long)sh->sector, i);
2543                                 set_bit(STRIPE_DELAYED, &sh->state);
2544                                 set_bit(STRIPE_HANDLE, &sh->state);
2545                         }
2546                 }
2547         }
2548         /* now if nothing is locked, and if we have enough data, we can start a
2549          * write request
2550          */
2551         if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
2552             s->locked == 0 && rcw == 0 &&
2553             !test_bit(STRIPE_BIT_DELAY, &sh->state)) {
2554                 schedule_reconstruction(sh, s, 1, 0);
2555         }
2556 }
2557
2558 static void handle_parity_checks5(raid5_conf_t *conf, struct stripe_head *sh,
2559                                 struct stripe_head_state *s, int disks)
2560 {
2561         struct r5dev *dev = NULL;
2562
2563         set_bit(STRIPE_HANDLE, &sh->state);
2564
2565         switch (sh->check_state) {
2566         case check_state_idle:
2567                 /* start a new check operation if there are no failures */
2568                 if (s->failed == 0) {
2569                         BUG_ON(s->uptodate != disks);
2570                         sh->check_state = check_state_run;
2571                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
2572                         clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
2573                         s->uptodate--;
2574                         break;
2575                 }
2576                 dev = &sh->dev[s->failed_num];
2577                 /* fall through */
2578         case check_state_compute_result:
2579                 sh->check_state = check_state_idle;
2580                 if (!dev)
2581                         dev = &sh->dev[sh->pd_idx];
2582
2583                 /* check that a write has not made the stripe insync */
2584                 if (test_bit(STRIPE_INSYNC, &sh->state))
2585                         break;
2586
2587                 /* either failed parity check, or recovery is happening */
2588                 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
2589                 BUG_ON(s->uptodate != disks);
2590
2591                 set_bit(R5_LOCKED, &dev->flags);
2592                 s->locked++;
2593                 set_bit(R5_Wantwrite, &dev->flags);
2594
2595                 clear_bit(STRIPE_DEGRADED, &sh->state);
2596                 set_bit(STRIPE_INSYNC, &sh->state);
2597                 break;
2598         case check_state_run:
2599                 break; /* we will be called again upon completion */
2600         case check_state_check_result:
2601                 sh->check_state = check_state_idle;
2602
2603                 /* if a failure occurred during the check operation, leave
2604                  * STRIPE_INSYNC not set and let the stripe be handled again
2605                  */
2606                 if (s->failed)
2607                         break;
2608
2609                 /* handle a successful check operation, if parity is correct
2610                  * we are done.  Otherwise update the mismatch count and repair
2611                  * parity if !MD_RECOVERY_CHECK
2612                  */
2613                 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
2614                         /* parity is correct (on disc,
2615                          * not in buffer any more)
2616                          */
2617                         set_bit(STRIPE_INSYNC, &sh->state);
2618                 else {
2619                         conf->mddev->resync_mismatches += STRIPE_SECTORS;
2620                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
2621                                 /* don't try to repair!! */
2622                                 set_bit(STRIPE_INSYNC, &sh->state);
2623                         else {
2624                                 sh->check_state = check_state_compute_run;
2625                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2626                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2627                                 set_bit(R5_Wantcompute,
2628                                         &sh->dev[sh->pd_idx].flags);
2629                                 sh->ops.target = sh->pd_idx;
2630                                 sh->ops.target2 = -1;
2631                                 s->uptodate++;
2632                         }
2633                 }
2634                 break;
2635         case check_state_compute_run:
2636                 break;
2637         default:
2638                 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
2639                        __func__, sh->check_state,
2640                        (unsigned long long) sh->sector);
2641                 BUG();
2642         }
2643 }
2644
2645
2646 static void handle_parity_checks6(raid5_conf_t *conf, struct stripe_head *sh,
2647                                   struct stripe_head_state *s,
2648                                   struct r6_state *r6s, int disks)
2649 {
2650         int pd_idx = sh->pd_idx;
2651         int qd_idx = sh->qd_idx;
2652         struct r5dev *dev;
2653
2654         set_bit(STRIPE_HANDLE, &sh->state);
2655
2656         BUG_ON(s->failed > 2);
2657
2658         /* Want to check and possibly repair P and Q.
2659          * However there could be one 'failed' device, in which
2660          * case we can only check one of them, possibly using the
2661          * other to generate missing data
2662          */
2663
2664         switch (sh->check_state) {
2665         case check_state_idle:
2666                 /* start a new check operation if there are < 2 failures */
2667                 if (s->failed == r6s->q_failed) {
2668                         /* The only possible failed device holds Q, so it
2669                          * makes sense to check P (If anything else were failed,
2670                          * we would have used P to recreate it).
2671                          */
2672                         sh->check_state = check_state_run;
2673                 }
2674                 if (!r6s->q_failed && s->failed < 2) {
2675                         /* Q is not failed, and we didn't use it to generate
2676                          * anything, so it makes sense to check it
2677                          */
2678                         if (sh->check_state == check_state_run)
2679                                 sh->check_state = check_state_run_pq;
2680                         else
2681                                 sh->check_state = check_state_run_q;
2682                 }
2683
2684                 /* discard potentially stale zero_sum_result */
2685                 sh->ops.zero_sum_result = 0;
2686
2687                 if (sh->check_state == check_state_run) {
2688                         /* async_xor_zero_sum destroys the contents of P */
2689                         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2690                         s->uptodate--;
2691                 }
2692                 if (sh->check_state >= check_state_run &&
2693                     sh->check_state <= check_state_run_pq) {
2694                         /* async_syndrome_zero_sum preserves P and Q, so
2695                          * no need to mark them !uptodate here
2696                          */
2697                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
2698                         break;
2699                 }
2700
2701                 /* we have 2-disk failure */
2702                 BUG_ON(s->failed != 2);
2703                 /* fall through */
2704         case check_state_compute_result:
2705                 sh->check_state = check_state_idle;
2706
2707                 /* check that a write has not made the stripe insync */
2708                 if (test_bit(STRIPE_INSYNC, &sh->state))
2709                         break;
2710
2711                 /* now write out any block on a failed drive,
2712                  * or P or Q if they were recomputed
2713                  */
2714                 BUG_ON(s->uptodate < disks - 1); /* We don't need Q to recover */
2715                 if (s->failed == 2) {
2716                         dev = &sh->dev[r6s->failed_num[1]];
2717                         s->locked++;
2718                         set_bit(R5_LOCKED, &dev->flags);
2719                         set_bit(R5_Wantwrite, &dev->flags);
2720                 }
2721                 if (s->failed >= 1) {
2722                         dev = &sh->dev[r6s->failed_num[0]];
2723                         s->locked++;
2724                         set_bit(R5_LOCKED, &dev->flags);
2725                         set_bit(R5_Wantwrite, &dev->flags);
2726                 }
2727                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
2728                         dev = &sh->dev[pd_idx];
2729                         s->locked++;
2730                         set_bit(R5_LOCKED, &dev->flags);
2731                         set_bit(R5_Wantwrite, &dev->flags);
2732                 }
2733                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
2734                         dev = &sh->dev[qd_idx];
2735                         s->locked++;
2736                         set_bit(R5_LOCKED, &dev->flags);
2737                         set_bit(R5_Wantwrite, &dev->flags);
2738                 }
2739                 clear_bit(STRIPE_DEGRADED, &sh->state);
2740
2741                 set_bit(STRIPE_INSYNC, &sh->state);
2742                 break;
2743         case check_state_run:
2744         case check_state_run_q:
2745         case check_state_run_pq:
2746                 break; /* we will be called again upon completion */
2747         case check_state_check_result:
2748                 sh->check_state = check_state_idle;
2749
2750                 /* handle a successful check operation, if parity is correct
2751                  * we are done.  Otherwise update the mismatch count and repair
2752                  * parity if !MD_RECOVERY_CHECK
2753                  */
2754                 if (sh->ops.zero_sum_result == 0) {
2755                         /* both parities are correct */
2756                         if (!s->failed)
2757                                 set_bit(STRIPE_INSYNC, &sh->state);
2758                         else {
2759                                 /* in contrast to the raid5 case we can validate
2760                                  * parity, but still have a failure to write
2761                                  * back
2762                                  */
2763                                 sh->check_state = check_state_compute_result;
2764                                 /* Returning at this point means that we may go
2765                                  * off and bring p and/or q uptodate again so
2766                                  * we make sure to check zero_sum_result again
2767                                  * to verify if p or q need writeback
2768                                  */
2769                         }
2770                 } else {
2771                         conf->mddev->resync_mismatches += STRIPE_SECTORS;
2772                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
2773                                 /* don't try to repair!! */
2774                                 set_bit(STRIPE_INSYNC, &sh->state);
2775                         else {
2776                                 int *target = &sh->ops.target;
2777
2778                                 sh->ops.target = -1;
2779                                 sh->ops.target2 = -1;
2780                                 sh->check_state = check_state_compute_run;
2781                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2782                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2783                                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
2784                                         set_bit(R5_Wantcompute,
2785                                                 &sh->dev[pd_idx].flags);
2786                                         *target = pd_idx;
2787                                         target = &sh->ops.target2;
2788                                         s->uptodate++;
2789                                 }
2790                                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
2791                                         set_bit(R5_Wantcompute,
2792                                                 &sh->dev[qd_idx].flags);
2793                                         *target = qd_idx;
2794                                         s->uptodate++;
2795                                 }
2796                         }
2797                 }
2798                 break;
2799         case check_state_compute_run:
2800                 break;
2801         default:
2802                 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
2803                        __func__, sh->check_state,
2804                        (unsigned long long) sh->sector);
2805                 BUG();
2806         }
2807 }
2808
2809 static void handle_stripe_expansion(raid5_conf_t *conf, struct stripe_head *sh,
2810                                 struct r6_state *r6s)
2811 {
2812         int i;
2813
2814         /* We have read all the blocks in this stripe and now we need to
2815          * copy some of them into a target stripe for expand.
2816          */
2817         struct dma_async_tx_descriptor *tx = NULL;
2818         clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
2819         for (i = 0; i < sh->disks; i++)
2820                 if (i != sh->pd_idx && i != sh->qd_idx) {
2821                         int dd_idx, j;
2822                         struct stripe_head *sh2;
2823                         struct async_submit_ctl submit;
2824
2825                         sector_t bn = compute_blocknr(sh, i, 1);
2826                         sector_t s = raid5_compute_sector(conf, bn, 0,
2827                                                           &dd_idx, NULL);
2828                         sh2 = get_active_stripe(conf, s, 0, 1);
2829                         if (sh2 == NULL)
2830                                 /* so far only the early blocks of this stripe
2831                                  * have been requested.  When later blocks
2832                                  * get requested, we will try again
2833                                  */
2834                                 continue;
2835                         if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
2836                            test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
2837                                 /* must have already done this block */
2838                                 release_stripe(sh2);
2839                                 continue;
2840                         }
2841
2842                         /* place all the copies on one channel */
2843                         init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
2844                         tx = async_memcpy(sh2->dev[dd_idx].page,
2845                                           sh->dev[i].page, 0, 0, STRIPE_SIZE,
2846                                           &submit);
2847
2848                         set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
2849                         set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
2850                         for (j = 0; j < conf->raid_disks; j++)
2851                                 if (j != sh2->pd_idx &&
2852                                     (!r6s || j != sh2->qd_idx) &&
2853                                     !test_bit(R5_Expanded, &sh2->dev[j].flags))
2854                                         break;
2855                         if (j == conf->raid_disks) {
2856                                 set_bit(STRIPE_EXPAND_READY, &sh2->state);
2857                                 set_bit(STRIPE_HANDLE, &sh2->state);
2858                         }
2859                         release_stripe(sh2);
2860
2861                 }
2862         /* done submitting copies, wait for them to complete */
2863         if (tx) {
2864                 async_tx_ack(tx);
2865                 dma_wait_for_async_tx(tx);
2866         }
2867 }
2868
2869
2870 /*
2871  * handle_stripe - do things to a stripe.
2872  *
2873  * We lock the stripe and then examine the state of various bits
2874  * to see what needs to be done.
2875  * Possible results:
2876  *    return some read request which now have data
2877  *    return some write requests which are safely on disc
2878  *    schedule a read on some buffers
2879  *    schedule a write of some buffers
2880  *    return confirmation of parity correctness
2881  *
2882  * buffers are taken off read_list or write_list, and bh_cache buffers
2883  * get BH_Lock set before the stripe lock is released.
2884  *
2885  */
2886
2887 static bool handle_stripe5(struct stripe_head *sh)
2888 {
2889         raid5_conf_t *conf = sh->raid_conf;
2890         int disks = sh->disks, i;
2891         struct bio *return_bi = NULL;
2892         struct stripe_head_state s;
2893         struct r5dev *dev;
2894         mdk_rdev_t *blocked_rdev = NULL;
2895         int prexor;
2896
2897         memset(&s, 0, sizeof(s));
2898         pr_debug("handling stripe %llu, state=%#lx cnt=%d, pd_idx=%d check:%d "
2899                  "reconstruct:%d\n", (unsigned long long)sh->sector, sh->state,
2900                  atomic_read(&sh->count), sh->pd_idx, sh->check_state,
2901                  sh->reconstruct_state);
2902
2903         spin_lock(&sh->lock);
2904         clear_bit(STRIPE_HANDLE, &sh->state);
2905         clear_bit(STRIPE_DELAYED, &sh->state);
2906
2907         s.syncing = test_bit(STRIPE_SYNCING, &sh->state);
2908         s.expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
2909         s.expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
2910
2911         /* Now to look around and see what can be done */
2912         rcu_read_lock();
2913         for (i=disks; i--; ) {
2914                 mdk_rdev_t *rdev;
2915                 struct r5dev *dev = &sh->dev[i];
2916                 clear_bit(R5_Insync, &dev->flags);
2917
2918                 pr_debug("check %d: state 0x%lx toread %p read %p write %p "
2919                         "written %p\n", i, dev->flags, dev->toread, dev->read,
2920                         dev->towrite, dev->written);
2921
2922                 /* maybe we can request a biofill operation
2923                  *
2924                  * new wantfill requests are only permitted while
2925                  * ops_complete_biofill is guaranteed to be inactive
2926                  */
2927                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
2928                     !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
2929                         set_bit(R5_Wantfill, &dev->flags);
2930
2931                 /* now count some things */
2932                 if (test_bit(R5_LOCKED, &dev->flags)) s.locked++;
2933                 if (test_bit(R5_UPTODATE, &dev->flags)) s.uptodate++;
2934                 if (test_bit(R5_Wantcompute, &dev->flags)) s.compute++;
2935
2936                 if (test_bit(R5_Wantfill, &dev->flags))
2937                         s.to_fill++;
2938                 else if (dev->toread)
2939                         s.to_read++;
2940                 if (dev->towrite) {
2941                         s.to_write++;
2942                         if (!test_bit(R5_OVERWRITE, &dev->flags))
2943                                 s.non_overwrite++;
2944                 }
2945                 if (dev->written)
2946                         s.written++;
2947                 rdev = rcu_dereference(conf->disks[i].rdev);
2948                 if (blocked_rdev == NULL &&
2949                     rdev && unlikely(test_bit(Blocked, &rdev->flags))) {
2950                         blocked_rdev = rdev;
2951                         atomic_inc(&rdev->nr_pending);
2952                 }
2953                 if (!rdev || !test_bit(In_sync, &rdev->flags)) {
2954                         /* The ReadError flag will just be confusing now */
2955                         clear_bit(R5_ReadError, &dev->flags);
2956                         clear_bit(R5_ReWrite, &dev->flags);
2957                 }
2958                 if (!rdev || !test_bit(In_sync, &rdev->flags)
2959                     || test_bit(R5_ReadError, &dev->flags)) {
2960                         s.failed++;
2961                         s.failed_num = i;
2962                 } else
2963                         set_bit(R5_Insync, &dev->flags);
2964         }
2965         rcu_read_unlock();
2966
2967         if (unlikely(blocked_rdev)) {
2968                 if (s.syncing || s.expanding || s.expanded ||
2969                     s.to_write || s.written) {
2970                         set_bit(STRIPE_HANDLE, &sh->state);
2971                         goto unlock;
2972                 }
2973                 /* There is nothing for the blocked_rdev to block */
2974                 rdev_dec_pending(blocked_rdev, conf->mddev);
2975                 blocked_rdev = NULL;
2976         }
2977
2978         if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
2979                 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
2980                 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
2981         }
2982
2983         pr_debug("locked=%d uptodate=%d to_read=%d"
2984                 " to_write=%d failed=%d failed_num=%d\n",
2985                 s.locked, s.uptodate, s.to_read, s.to_write,
2986                 s.failed, s.failed_num);
2987         /* check if the array has lost two devices and, if so, some requests might
2988          * need to be failed
2989          */
2990         if (s.failed > 1 && s.to_read+s.to_write+s.written)
2991                 handle_failed_stripe(conf, sh, &s, disks, &return_bi);
2992         if (s.failed > 1 && s.syncing) {
2993                 md_done_sync(conf->mddev, STRIPE_SECTORS,0);
2994                 clear_bit(STRIPE_SYNCING, &sh->state);
2995                 s.syncing = 0;
2996         }
2997
2998         /* might be able to return some write requests if the parity block
2999          * is safe, or on a failed drive
3000          */
3001         dev = &sh->dev[sh->pd_idx];
3002         if ( s.written &&
3003              ((test_bit(R5_Insync, &dev->flags) &&
3004                !test_bit(R5_LOCKED, &dev->flags) &&
3005                test_bit(R5_UPTODATE, &dev->flags)) ||
3006                (s.failed == 1 && s.failed_num == sh->pd_idx)))
3007                 handle_stripe_clean_event(conf, sh, disks, &return_bi);
3008
3009         /* Now we might consider reading some blocks, either to check/generate
3010          * parity, or to satisfy requests
3011          * or to load a block that is being partially written.
3012          */
3013         if (s.to_read || s.non_overwrite ||
3014             (s.syncing && (s.uptodate + s.compute < disks)) || s.expanding)
3015                 handle_stripe_fill5(sh, &s, disks);
3016
3017         /* Now we check to see if any write operations have recently
3018          * completed
3019          */
3020         prexor = 0;
3021         if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
3022                 prexor = 1;
3023         if (sh->reconstruct_state == reconstruct_state_drain_result ||
3024             sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
3025                 sh->reconstruct_state = reconstruct_state_idle;
3026
3027                 /* All the 'written' buffers and the parity block are ready to
3028                  * be written back to disk
3029                  */
3030                 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags));
3031                 for (i = disks; i--; ) {
3032                         dev = &sh->dev[i];
3033                         if (test_bit(R5_LOCKED, &dev->flags) &&
3034                                 (i == sh->pd_idx || dev->written)) {
3035                                 pr_debug("Writing block %d\n", i);
3036                                 set_bit(R5_Wantwrite, &dev->flags);
3037                                 if (prexor)
3038                                         continue;
3039                                 if (!test_bit(R5_Insync, &dev->flags) ||
3040                                     (i == sh->pd_idx && s.failed == 0))
3041                                         set_bit(STRIPE_INSYNC, &sh->state);
3042                         }
3043                 }
3044                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
3045                         atomic_dec(&conf->preread_active_stripes);
3046                         if (atomic_read(&conf->preread_active_stripes) <
3047                                 IO_THRESHOLD)
3048                                 md_wakeup_thread(conf->mddev->thread);
3049                 }
3050         }
3051
3052         /* Now to consider new write requests and what else, if anything
3053          * should be read.  We do not handle new writes when:
3054          * 1/ A 'write' operation (copy+xor) is already in flight.
3055          * 2/ A 'check' operation is in flight, as it may clobber the parity
3056          *    block.
3057          */
3058         if (s.to_write && !sh->reconstruct_state && !sh->check_state)
3059                 handle_stripe_dirtying5(conf, sh, &s, disks);
3060
3061         /* maybe we need to check and possibly fix the parity for this stripe
3062          * Any reads will already have been scheduled, so we just see if enough
3063          * data is available.  The parity check is held off while parity
3064          * dependent operations are in flight.
3065          */
3066         if (sh->check_state ||
3067             (s.syncing && s.locked == 0 &&
3068              !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
3069              !test_bit(STRIPE_INSYNC, &sh->state)))
3070                 handle_parity_checks5(conf, sh, &s, disks);
3071
3072         if (s.syncing && s.locked == 0 && test_bit(STRIPE_INSYNC, &sh->state)) {
3073                 md_done_sync(conf->mddev, STRIPE_SECTORS,1);
3074                 clear_bit(STRIPE_SYNCING, &sh->state);
3075         }
3076
3077         /* If the failed drive is just a ReadError, then we might need to progress
3078          * the repair/check process
3079          */
3080         if (s.failed == 1 && !conf->mddev->ro &&
3081             test_bit(R5_ReadError, &sh->dev[s.failed_num].flags)
3082             && !test_bit(R5_LOCKED, &sh->dev[s.failed_num].flags)
3083             && test_bit(R5_UPTODATE, &sh->dev[s.failed_num].flags)
3084                 ) {
3085                 dev = &sh->dev[s.failed_num];
3086                 if (!test_bit(R5_ReWrite, &dev->flags)) {
3087                         set_bit(R5_Wantwrite, &dev->flags);
3088                         set_bit(R5_ReWrite, &dev->flags);
3089                         set_bit(R5_LOCKED, &dev->flags);
3090                         s.locked++;
3091                 } else {
3092                         /* let's read it back */
3093                         set_bit(R5_Wantread, &dev->flags);
3094                         set_bit(R5_LOCKED, &dev->flags);
3095                         s.locked++;
3096                 }
3097         }
3098
3099         /* Finish reconstruct operations initiated by the expansion process */
3100         if (sh->reconstruct_state == reconstruct_state_result) {
3101                 struct stripe_head *sh2
3102                         = get_active_stripe(conf, sh->sector, 1, 1);
3103                 if (sh2 && test_bit(STRIPE_EXPAND_SOURCE, &sh2->state)) {
3104                         /* sh cannot be written until sh2 has been read.
3105                          * so arrange for sh to be delayed a little
3106                          */
3107                         set_bit(STRIPE_DELAYED, &sh->state);
3108                         set_bit(STRIPE_HANDLE, &sh->state);
3109                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
3110                                               &sh2->state))
3111                                 atomic_inc(&conf->preread_active_stripes);
3112                         release_stripe(sh2);
3113                         goto unlock;
3114                 }
3115                 if (sh2)
3116                         release_stripe(sh2);
3117
3118                 sh->reconstruct_state = reconstruct_state_idle;
3119                 clear_bit(STRIPE_EXPANDING, &sh->state);
3120                 for (i = conf->raid_disks; i--; ) {
3121                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
3122                         set_bit(R5_LOCKED, &sh->dev[i].flags);
3123                         s.locked++;
3124                 }
3125         }
3126
3127         if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
3128             !sh->reconstruct_state) {
3129                 /* Need to write out all blocks after computing parity */
3130                 sh->disks = conf->raid_disks;
3131                 stripe_set_idx(sh->sector, conf, 0, sh);
3132                 schedule_reconstruction(sh, &s, 1, 1);
3133         } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
3134                 clear_bit(STRIPE_EXPAND_READY, &sh->state);
3135                 atomic_dec(&conf->reshape_stripes);
3136                 wake_up(&conf->wait_for_overlap);
3137                 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3138         }
3139
3140         if (s.expanding && s.locked == 0 &&
3141             !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
3142                 handle_stripe_expansion(conf, sh, NULL);
3143
3144  unlock:
3145         spin_unlock(&sh->lock);
3146
3147         /* wait for this device to become unblocked */
3148         if (unlikely(blocked_rdev))
3149                 md_wait_for_blocked_rdev(blocked_rdev, conf->mddev);
3150
3151         if (s.ops_request)
3152                 raid_run_ops(sh, s.ops_request);
3153
3154         ops_run_io(sh, &s);
3155
3156         return_io(return_bi);
3157
3158         return blocked_rdev == NULL;
3159 }
3160
3161 static bool handle_stripe6(struct stripe_head *sh)
3162 {
3163         raid5_conf_t *conf = sh->raid_conf;
3164         int disks = sh->disks;
3165         struct bio *return_bi = NULL;
3166         int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx;
3167         struct stripe_head_state s;
3168         struct r6_state r6s;
3169         struct r5dev *dev, *pdev, *qdev;
3170         mdk_rdev_t *blocked_rdev = NULL;
3171
3172         pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
3173                 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
3174                (unsigned long long)sh->sector, sh->state,
3175                atomic_read(&sh->count), pd_idx, qd_idx,
3176                sh->check_state, sh->reconstruct_state);
3177         memset(&s, 0, sizeof(s));
3178
3179         spin_lock(&sh->lock);
3180         clear_bit(STRIPE_HANDLE, &sh->state);
3181         clear_bit(STRIPE_DELAYED, &sh->state);
3182
3183         s.syncing = test_bit(STRIPE_SYNCING, &sh->state);
3184         s.expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3185         s.expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
3186         /* Now to look around and see what can be done */
3187
3188         rcu_read_lock();
3189         for (i=disks; i--; ) {
3190                 mdk_rdev_t *rdev;
3191                 dev = &sh->dev[i];
3192                 clear_bit(R5_Insync, &dev->flags);
3193
3194                 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
3195                         i, dev->flags, dev->toread, dev->towrite, dev->written);
3196                 /* maybe we can reply to a read
3197                  *
3198                  * new wantfill requests are only permitted while
3199                  * ops_complete_biofill is guaranteed to be inactive
3200                  */
3201                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
3202                     !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
3203                         set_bit(R5_Wantfill, &dev->flags);
3204
3205                 /* now count some things */
3206                 if (test_bit(R5_LOCKED, &dev->flags)) s.locked++;
3207                 if (test_bit(R5_UPTODATE, &dev->flags)) s.uptodate++;
3208                 if (test_bit(R5_Wantcompute, &dev->flags))
3209                         BUG_ON(++s.compute > 2);
3210
3211                 if (test_bit(R5_Wantfill, &dev->flags)) {
3212                         s.to_fill++;
3213                 } else if (dev->toread)
3214                         s.to_read++;
3215                 if (dev->towrite) {
3216                         s.to_write++;
3217                         if (!test_bit(R5_OVERWRITE, &dev->flags))
3218                                 s.non_overwrite++;
3219                 }
3220                 if (dev->written)
3221                         s.written++;
3222                 rdev = rcu_dereference(conf->disks[i].rdev);
3223                 if (blocked_rdev == NULL &&
3224                     rdev && unlikely(test_bit(Blocked, &rdev->flags))) {
3225                         blocked_rdev = rdev;
3226                         atomic_inc(&rdev->nr_pending);
3227                 }
3228                 if (!rdev || !test_bit(In_sync, &rdev->flags)) {
3229                         /* The ReadError flag will just be confusing now */
3230                         clear_bit(R5_ReadError, &dev->flags);
3231                         clear_bit(R5_ReWrite, &dev->flags);
3232                 }
3233                 if (!rdev || !test_bit(In_sync, &rdev->flags)
3234                     || test_bit(R5_ReadError, &dev->flags)) {
3235                         if (s.failed < 2)
3236                                 r6s.failed_num[s.failed] = i;
3237                         s.failed++;
3238                 } else
3239                         set_bit(R5_Insync, &dev->flags);
3240         }
3241         rcu_read_unlock();
3242
3243         if (unlikely(blocked_rdev)) {
3244                 if (s.syncing || s.expanding || s.expanded ||
3245                     s.to_write || s.written) {
3246                         set_bit(STRIPE_HANDLE, &sh->state);
3247                         goto unlock;
3248                 }
3249                 /* There is nothing for the blocked_rdev to block */
3250                 rdev_dec_pending(blocked_rdev, conf->mddev);
3251                 blocked_rdev = NULL;
3252         }
3253
3254         if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
3255                 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
3256                 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
3257         }
3258
3259         pr_debug("locked=%d uptodate=%d to_read=%d"
3260                " to_write=%d failed=%d failed_num=%d,%d\n",
3261                s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
3262                r6s.failed_num[0], r6s.failed_num[1]);
3263         /* check if the array has lost >2 devices and, if so, some requests
3264          * might need to be failed
3265          */
3266         if (s.failed > 2 && s.to_read+s.to_write+s.written)
3267                 handle_failed_stripe(conf, sh, &s, disks, &return_bi);
3268         if (s.failed > 2 && s.syncing) {
3269                 md_done_sync(conf->mddev, STRIPE_SECTORS,0);
3270                 clear_bit(STRIPE_SYNCING, &sh->state);
3271                 s.syncing = 0;
3272         }
3273
3274         /*
3275          * might be able to return some write requests if the parity blocks
3276          * are safe, or on a failed drive
3277          */
3278         pdev = &sh->dev[pd_idx];
3279         r6s.p_failed = (s.failed >= 1 && r6s.failed_num[0] == pd_idx)
3280                 || (s.failed >= 2 && r6s.failed_num[1] == pd_idx);
3281         qdev = &sh->dev[qd_idx];
3282         r6s.q_failed = (s.failed >= 1 && r6s.failed_num[0] == qd_idx)
3283                 || (s.failed >= 2 && r6s.failed_num[1] == qd_idx);
3284
3285         if ( s.written &&
3286              ( r6s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
3287                              && !test_bit(R5_LOCKED, &pdev->flags)
3288                              && test_bit(R5_UPTODATE, &pdev->flags)))) &&
3289              ( r6s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
3290                              && !test_bit(R5_LOCKED, &qdev->flags)
3291                              && test_bit(R5_UPTODATE, &qdev->flags)))))
3292                 handle_stripe_clean_event(conf, sh, disks, &return_bi);
3293
3294         /* Now we might consider reading some blocks, either to check/generate
3295          * parity, or to satisfy requests
3296          * or to load a block that is being partially written.
3297          */
3298         if (s.to_read || s.non_overwrite || (s.to_write && s.failed) ||
3299             (s.syncing && (s.uptodate + s.compute < disks)) || s.expanding)
3300                 handle_stripe_fill6(sh, &s, &r6s, disks);
3301
3302         /* Now we check to see if any write operations have recently
3303          * completed
3304          */
3305         if (sh->reconstruct_state == reconstruct_state_drain_result) {
3306                 int qd_idx = sh->qd_idx;
3307
3308                 sh->reconstruct_state = reconstruct_state_idle;
3309                 /* All the 'written' buffers and the parity blocks are ready to
3310                  * be written back to disk
3311                  */
3312                 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags));
3313                 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags));
3314                 for (i = disks; i--; ) {
3315                         dev = &sh->dev[i];
3316                         if (test_bit(R5_LOCKED, &dev->flags) &&
3317                             (i == sh->pd_idx || i == qd_idx ||
3318                              dev->written)) {
3319                                 pr_debug("Writing block %d\n", i);
3320                                 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
3321                                 set_bit(R5_Wantwrite, &dev->flags);
3322                                 if (!test_bit(R5_Insync, &dev->flags) ||
3323                                     ((i == sh->pd_idx || i == qd_idx) &&
3324                                       s.failed == 0))
3325                                         set_bit(STRIPE_INSYNC, &sh->state);
3326                         }
3327                 }
3328                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
3329                         atomic_dec(&conf->preread_active_stripes);
3330                         if (atomic_read(&conf->preread_active_stripes) <
3331                                 IO_THRESHOLD)
3332                                 md_wakeup_thread(conf->mddev->thread);
3333                 }
3334         }
3335
3336         /* Now to consider new write requests and what else, if anything
3337          * should be read.  We do not handle new writes when:
3338          * 1/ A 'write' operation (copy+gen_syndrome) is already in flight.
3339          * 2/ A 'check' operation is in flight, as it may clobber the parity
3340          *    block.
3341          */
3342         if (s.to_write && !sh->reconstruct_state && !sh->check_state)
3343                 handle_stripe_dirtying6(conf, sh, &s, &r6s, disks);
3344
3345         /* maybe we need to check and possibly fix the parity for this stripe
3346          * Any reads will already have been scheduled, so we just see if enough
3347          * data is available.  The parity check is held off while parity
3348          * dependent operations are in flight.
3349          */
3350         if (sh->check_state ||
3351             (s.syncing && s.locked == 0 &&
3352              !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
3353              !test_bit(STRIPE_INSYNC, &sh->state)))
3354                 handle_parity_checks6(conf, sh, &s, &r6s, disks);
3355
3356         if (s.syncing && s.locked == 0 && test_bit(STRIPE_INSYNC, &sh->state)) {
3357                 md_done_sync(conf->mddev, STRIPE_SECTORS,1);
3358                 clear_bit(STRIPE_SYNCING, &sh->state);
3359         }
3360
3361         /* If the failed drives are just a ReadError, then we might need
3362          * to progress the repair/check process
3363          */
3364         if (s.failed <= 2 && !conf->mddev->ro)
3365                 for (i = 0; i < s.failed; i++) {
3366                         dev = &sh->dev[r6s.failed_num[i]];
3367                         if (test_bit(R5_ReadError, &dev->flags)
3368                             && !test_bit(R5_LOCKED, &dev->flags)
3369                             && test_bit(R5_UPTODATE, &dev->flags)
3370                                 ) {
3371                                 if (!test_bit(R5_ReWrite, &dev->flags)) {
3372                                         set_bit(R5_Wantwrite, &dev->flags);
3373                                         set_bit(R5_ReWrite, &dev->flags);
3374                                         set_bit(R5_LOCKED, &dev->flags);
3375                                         s.locked++;
3376                                 } else {
3377                                         /* let's read it back */
3378                                         set_bit(R5_Wantread, &dev->flags);
3379                                         set_bit(R5_LOCKED, &dev->flags);
3380                                         s.locked++;
3381                                 }
3382                         }
3383                 }
3384
3385         /* Finish reconstruct operations initiated by the expansion process */
3386         if (sh->reconstruct_state == reconstruct_state_result) {
3387                 sh->reconstruct_state = reconstruct_state_idle;
3388                 clear_bit(STRIPE_EXPANDING, &sh->state);
3389                 for (i = conf->raid_disks; i--; ) {
3390                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
3391                         set_bit(R5_LOCKED, &sh->dev[i].flags);
3392                         s.locked++;
3393                 }
3394         }
3395
3396         if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
3397             !sh->reconstruct_state) {
3398                 struct stripe_head *sh2
3399                         = get_active_stripe(conf, sh->sector, 1, 1);
3400                 if (sh2 && test_bit(STRIPE_EXPAND_SOURCE, &sh2->state)) {
3401                         /* sh cannot be written until sh2 has been read.
3402                          * so arrange for sh to be delayed a little
3403                          */
3404                         set_bit(STRIPE_DELAYED, &sh->state);
3405                         set_bit(STRIPE_HANDLE, &sh->state);
3406                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
3407                                               &sh2->state))
3408                                 atomic_inc(&conf->preread_active_stripes);
3409                         release_stripe(sh2);
3410                         goto unlock;
3411                 }
3412                 if (sh2)
3413                         release_stripe(sh2);
3414
3415                 /* Need to write out all blocks after computing P&Q */
3416                 sh->disks = conf->raid_disks;
3417                 stripe_set_idx(sh->sector, conf, 0, sh);
3418                 schedule_reconstruction(sh, &s, 1, 1);
3419         } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
3420                 clear_bit(STRIPE_EXPAND_READY, &sh->state);
3421                 atomic_dec(&conf->reshape_stripes);
3422                 wake_up(&conf->wait_for_overlap);
3423                 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3424         }
3425
3426         if (s.expanding && s.locked == 0 &&
3427             !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
3428                 handle_stripe_expansion(conf, sh, &r6s);
3429
3430  unlock:
3431         spin_unlock(&sh->lock);
3432
3433         /* wait for this device to become unblocked */
3434         if (unlikely(blocked_rdev))
3435                 md_wait_for_blocked_rdev(blocked_rdev, conf->mddev);
3436
3437         if (s.ops_request)
3438                 raid_run_ops(sh, s.ops_request);
3439
3440         ops_run_io(sh, &s);
3441
3442         return_io(return_bi);
3443
3444         return blocked_rdev == NULL;
3445 }
3446
3447 /* returns true if the stripe was handled */
3448 static bool handle_stripe(struct stripe_head *sh)
3449 {
3450         if (sh->raid_conf->level == 6)
3451                 return handle_stripe6(sh);
3452         else
3453                 return handle_stripe5(sh);
3454 }
3455
3456 static void raid5_activate_delayed(raid5_conf_t *conf)
3457 {
3458         if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
3459                 while (!list_empty(&conf->delayed_list)) {
3460                         struct list_head *l = conf->delayed_list.next;
3461                         struct stripe_head *sh;
3462                         sh = list_entry(l, struct stripe_head, lru);
3463                         list_del_init(l);
3464                         clear_bit(STRIPE_DELAYED, &sh->state);
3465                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3466                                 atomic_inc(&conf->preread_active_stripes);
3467                         list_add_tail(&sh->lru, &conf->hold_list);
3468                 }
3469         } else
3470                 blk_plug_device(conf->mddev->queue);
3471 }
3472
3473 static void activate_bit_delay(raid5_conf_t *conf)
3474 {
3475         /* device_lock is held */
3476         struct list_head head;
3477         list_add(&head, &conf->bitmap_list);
3478         list_del_init(&conf->bitmap_list);
3479         while (!list_empty(&head)) {
3480                 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
3481                 list_del_init(&sh->lru);
3482                 atomic_inc(&sh->count);
3483                 __release_stripe(conf, sh);
3484         }
3485 }
3486
3487 static void unplug_slaves(mddev_t *mddev)
3488 {
3489         raid5_conf_t *conf = mddev_to_conf(mddev);
3490         int i;
3491
3492         rcu_read_lock();
3493         for (i=0; i<mddev->raid_disks; i++) {
3494                 mdk_rdev_t *rdev = rcu_dereference(conf->disks[i].rdev);
3495                 if (rdev && !test_bit(Faulty, &rdev->flags) && atomic_read(&rdev->nr_pending)) {
3496                         struct request_queue *r_queue = bdev_get_queue(rdev->bdev);
3497
3498                         atomic_inc(&rdev->nr_pending);
3499                         rcu_read_unlock();
3500
3501                         blk_unplug(r_queue);
3502
3503                         rdev_dec_pending(rdev, mddev);
3504                         rcu_read_lock();
3505                 }
3506         }
3507         rcu_read_unlock();
3508 }
3509
3510 static void raid5_unplug_device(struct request_queue *q)
3511 {
3512         mddev_t *mddev = q->queuedata;
3513         raid5_conf_t *conf = mddev_to_conf(mddev);
3514         unsigned long flags;
3515
3516         spin_lock_irqsave(&conf->device_lock, flags);
3517
3518         if (blk_remove_plug(q)) {
3519                 conf->seq_flush++;
3520                 raid5_activate_delayed(conf);
3521         }
3522         md_wakeup_thread(mddev->thread);
3523
3524         spin_unlock_irqrestore(&conf->device_lock, flags);
3525
3526         unplug_slaves(mddev);
3527 }
3528
3529 static int raid5_congested(void *data, int bits)
3530 {
3531         mddev_t *mddev = data;
3532         raid5_conf_t *conf = mddev_to_conf(mddev);
3533
3534         /* No difference between reads and writes.  Just check
3535          * how busy the stripe_cache is
3536          */
3537         if (conf->inactive_blocked)
3538                 return 1;
3539         if (conf->quiesce)
3540                 return 1;
3541         if (list_empty_careful(&conf->inactive_list))
3542                 return 1;
3543
3544         return 0;
3545 }
3546
3547 /* We want read requests to align with chunks where possible,
3548  * but write requests don't need to.
3549  */
3550 static int raid5_mergeable_bvec(struct request_queue *q,
3551                                 struct bvec_merge_data *bvm,
3552                                 struct bio_vec *biovec)
3553 {
3554         mddev_t *mddev = q->queuedata;
3555         sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
3556         int max;
3557         unsigned int chunk_sectors = mddev->chunk_size >> 9;
3558         unsigned int bio_sectors = bvm->bi_size >> 9;
3559
3560         if ((bvm->bi_rw & 1) == WRITE)
3561                 return biovec->bv_len; /* always allow writes to be mergeable */
3562
3563         if (mddev->new_chunk < mddev->chunk_size)
3564                 chunk_sectors = mddev->new_chunk >> 9;
3565         max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
3566         if (max < 0) max = 0;
3567         if (max <= biovec->bv_len && bio_sectors == 0)
3568                 return biovec->bv_len;
3569         else
3570                 return max;
3571 }
3572
3573
3574 static int in_chunk_boundary(mddev_t *mddev, struct bio *bio)
3575 {
3576         sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
3577         unsigned int chunk_sectors = mddev->chunk_size >> 9;
3578         unsigned int bio_sectors = bio->bi_size >> 9;
3579
3580         if (mddev->new_chunk < mddev->chunk_size)
3581                 chunk_sectors = mddev->new_chunk >> 9;
3582         return  chunk_sectors >=
3583                 ((sector & (chunk_sectors - 1)) + bio_sectors);
3584 }
3585
3586 /*
3587  *  add bio to the retry LIFO  ( in O(1) ... we are in interrupt )
3588  *  later sampled by raid5d.
3589  */
3590 static void add_bio_to_retry(struct bio *bi,raid5_conf_t *conf)
3591 {
3592         unsigned long flags;
3593
3594         spin_lock_irqsave(&conf->device_lock, flags);
3595
3596         bi->bi_next = conf->retry_read_aligned_list;
3597         conf->retry_read_aligned_list = bi;
3598
3599         spin_unlock_irqrestore(&conf->device_lock, flags);
3600         md_wakeup_thread(conf->mddev->thread);
3601 }
3602
3603
3604 static struct bio *remove_bio_from_retry(raid5_conf_t *conf)
3605 {
3606         struct bio *bi;
3607
3608         bi = conf->retry_read_aligned;
3609         if (bi) {
3610                 conf->retry_read_aligned = NULL;
3611                 return bi;
3612         }
3613         bi = conf->retry_read_aligned_list;
3614         if(bi) {
3615                 conf->retry_read_aligned_list = bi->bi_next;
3616                 bi->bi_next = NULL;
3617                 /*
3618                  * this sets the active strip count to 1 and the processed
3619                  * strip count to zero (upper 8 bits)
3620                  */
3621                 bi->bi_phys_segments = 1; /* biased count of active stripes */
3622         }
3623
3624         return bi;
3625 }
3626
3627
3628 /*
3629  *  The "raid5_align_endio" should check if the read succeeded and if it
3630  *  did, call bio_endio on the original bio (having bio_put the new bio
3631  *  first).
3632  *  If the read failed..
3633  */
3634 static void raid5_align_endio(struct bio *bi, int error)
3635 {
3636         struct bio* raid_bi  = bi->bi_private;
3637         mddev_t *mddev;
3638         raid5_conf_t *conf;
3639         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
3640         mdk_rdev_t *rdev;
3641
3642         bio_put(bi);
3643
3644         mddev = raid_bi->bi_bdev->bd_disk->queue->queuedata;
3645         conf = mddev_to_conf(mddev);
3646         rdev = (void*)raid_bi->bi_next;
3647         raid_bi->bi_next = NULL;
3648
3649         rdev_dec_pending(rdev, conf->mddev);
3650
3651         if (!error && uptodate) {
3652                 bio_endio(raid_bi, 0);
3653                 if (atomic_dec_and_test(&conf->active_aligned_reads))
3654                         wake_up(&conf->wait_for_stripe);
3655                 return;
3656         }
3657
3658
3659         pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
3660
3661         add_bio_to_retry(raid_bi, conf);
3662 }
3663
3664 static int bio_fits_rdev(struct bio *bi)
3665 {
3666         struct request_queue *q = bdev_get_queue(bi->bi_bdev);
3667
3668         if ((bi->bi_size>>9) > q->max_sectors)
3669                 return 0;
3670         blk_recount_segments(q, bi);
3671         if (bi->bi_phys_segments > q->max_phys_segments)
3672                 return 0;
3673
3674         if (q->merge_bvec_fn)
3675                 /* it's too hard to apply the merge_bvec_fn at this stage,
3676                  * just just give up
3677                  */
3678                 return 0;
3679
3680         return 1;
3681 }
3682
3683
3684 static int chunk_aligned_read(struct request_queue *q, struct bio * raid_bio)
3685 {
3686         mddev_t *mddev = q->queuedata;
3687         raid5_conf_t *conf = mddev_to_conf(mddev);
3688         unsigned int dd_idx;
3689         struct bio* align_bi;
3690         mdk_rdev_t *rdev;
3691
3692         if (!in_chunk_boundary(mddev, raid_bio)) {
3693                 pr_debug("chunk_aligned_read : non aligned\n");
3694                 return 0;
3695         }
3696         /*
3697          * use bio_clone to make a copy of the bio
3698          */
3699         align_bi = bio_clone(raid_bio, GFP_NOIO);
3700         if (!align_bi)
3701                 return 0;
3702         /*
3703          *   set bi_end_io to a new function, and set bi_private to the
3704          *     original bio.
3705          */
3706         align_bi->bi_end_io  = raid5_align_endio;
3707         align_bi->bi_private = raid_bio;
3708         /*
3709          *      compute position
3710          */
3711         align_bi->bi_sector =  raid5_compute_sector(conf, raid_bio->bi_sector,
3712                                                     0,
3713                                                     &dd_idx, NULL);
3714
3715         rcu_read_lock();
3716         rdev = rcu_dereference(conf->disks[dd_idx].rdev);
3717         if (rdev && test_bit(In_sync, &rdev->flags)) {
3718                 atomic_inc(&rdev->nr_pending);
3719                 rcu_read_unlock();
3720                 raid_bio->bi_next = (void*)rdev;
3721                 align_bi->bi_bdev =  rdev->bdev;
3722                 align_bi->bi_flags &= ~(1 << BIO_SEG_VALID);
3723                 align_bi->bi_sector += rdev->data_offset;
3724
3725                 if (!bio_fits_rdev(align_bi)) {
3726                         /* too big in some way */
3727                         bio_put(align_bi);
3728                         rdev_dec_pending(rdev, mddev);
3729                         return 0;
3730                 }
3731
3732                 spin_lock_irq(&conf->device_lock);
3733                 wait_event_lock_irq(conf->wait_for_stripe,
3734                                     conf->quiesce == 0,
3735                                     conf->device_lock, /* nothing */);
3736                 atomic_inc(&conf->active_aligned_reads);
3737                 spin_unlock_irq(&conf->device_lock);
3738
3739                 generic_make_request(align_bi);
3740                 return 1;
3741         } else {
3742                 rcu_read_unlock();
3743                 bio_put(align_bi);
3744                 return 0;
3745         }
3746 }
3747
3748 /* __get_priority_stripe - get the next stripe to process
3749  *
3750  * Full stripe writes are allowed to pass preread active stripes up until
3751  * the bypass_threshold is exceeded.  In general the bypass_count
3752  * increments when the handle_list is handled before the hold_list; however, it
3753  * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
3754  * stripe with in flight i/o.  The bypass_count will be reset when the
3755  * head of the hold_list has changed, i.e. the head was promoted to the
3756  * handle_list.
3757  */
3758 static struct stripe_head *__get_priority_stripe(raid5_conf_t *conf)
3759 {
3760         struct stripe_head *sh;
3761
3762         pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
3763                   __func__,
3764                   list_empty(&conf->handle_list) ? "empty" : "busy",
3765                   list_empty(&conf->hold_list) ? "empty" : "busy",
3766                   atomic_read(&conf->pending_full_writes), conf->bypass_count);
3767
3768         if (!list_empty(&conf->handle_list)) {
3769                 sh = list_entry(conf->handle_list.next, typeof(*sh), lru);
3770
3771                 if (list_empty(&conf->hold_list))
3772                         conf->bypass_count = 0;
3773                 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
3774                         if (conf->hold_list.next == conf->last_hold)
3775                                 conf->bypass_count++;
3776                         else {
3777                                 conf->last_hold = conf->hold_list.next;
3778                                 conf->bypass_count -= conf->bypass_threshold;
3779                                 if (conf->bypass_count < 0)
3780                                         conf->bypass_count = 0;
3781                         }
3782                 }
3783         } else if (!list_empty(&conf->hold_list) &&
3784                    ((conf->bypass_threshold &&
3785                      conf->bypass_count > conf->bypass_threshold) ||
3786                     atomic_read(&conf->pending_full_writes) == 0)) {
3787                 sh = list_entry(conf->hold_list.next,
3788                                 typeof(*sh), lru);
3789                 conf->bypass_count -= conf->bypass_threshold;
3790                 if (conf->bypass_count < 0)
3791                         conf->bypass_count = 0;
3792         } else
3793                 return NULL;
3794
3795         list_del_init(&sh->lru);
3796         atomic_inc(&sh->count);
3797         BUG_ON(atomic_read(&sh->count) != 1);
3798         return sh;
3799 }
3800
3801 static int make_request(struct request_queue *q, struct bio * bi)
3802 {
3803         mddev_t *mddev = q->queuedata;
3804         raid5_conf_t *conf = mddev_to_conf(mddev);
3805         int dd_idx;
3806         sector_t new_sector;
3807         sector_t logical_sector, last_sector;
3808         struct stripe_head *sh;
3809         const int rw = bio_data_dir(bi);
3810         int cpu, remaining;
3811
3812         if (unlikely(bio_barrier(bi))) {
3813                 bio_endio(bi, -EOPNOTSUPP);
3814                 return 0;
3815         }
3816
3817         md_write_start(mddev, bi);
3818
3819         cpu = part_stat_lock();
3820         part_stat_inc(cpu, &mddev->gendisk->part0, ios[rw]);
3821         part_stat_add(cpu, &mddev->gendisk->part0, sectors[rw],
3822                       bio_sectors(bi));
3823         part_stat_unlock();
3824
3825         if (rw == READ &&
3826              mddev->reshape_position == MaxSector &&
3827              chunk_aligned_read(q,bi))
3828                 return 0;
3829
3830         logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
3831         last_sector = bi->bi_sector + (bi->bi_size>>9);
3832         bi->bi_next = NULL;
3833         bi->bi_phys_segments = 1;       /* over-loaded to count active stripes */
3834
3835         for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
3836                 DEFINE_WAIT(w);
3837                 int disks, data_disks;
3838                 int previous;
3839
3840         retry:
3841                 previous = 0;
3842                 disks = conf->raid_disks;
3843                 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
3844                 if (unlikely(conf->reshape_progress != MaxSector)) {
3845                         /* spinlock is needed as reshape_progress may be
3846                          * 64bit on a 32bit platform, and so it might be
3847                          * possible to see a half-updated value
3848                          * Ofcourse reshape_progress could change after
3849                          * the lock is dropped, so once we get a reference
3850                          * to the stripe that we think it is, we will have
3851                          * to check again.
3852                          */
3853                         spin_lock_irq(&conf->device_lock);
3854                         if (mddev->delta_disks < 0
3855                             ? logical_sector < conf->reshape_progress
3856                             : logical_sector >= conf->reshape_progress) {
3857                                 disks = conf->previous_raid_disks;
3858                                 previous = 1;
3859                         } else {
3860                                 if (mddev->delta_disks < 0
3861                                     ? logical_sector < conf->reshape_safe
3862                                     : logical_sector >= conf->reshape_safe) {
3863                                         spin_unlock_irq(&conf->device_lock);
3864                                         schedule();
3865                                         goto retry;
3866                                 }
3867                         }
3868                         spin_unlock_irq(&conf->device_lock);
3869                 }
3870                 data_disks = disks - conf->max_degraded;
3871
3872                 new_sector = raid5_compute_sector(conf, logical_sector,
3873                                                   previous,
3874                                                   &dd_idx, NULL);
3875                 pr_debug("raid5: make_request, sector %llu logical %llu\n",
3876                         (unsigned long long)new_sector, 
3877                         (unsigned long long)logical_sector);
3878
3879                 sh = get_active_stripe(conf, new_sector, previous,
3880                                        (bi->bi_rw&RWA_MASK));
3881                 if (sh) {
3882                         if (unlikely(previous)) {
3883                                 /* expansion might have moved on while waiting for a
3884                                  * stripe, so we must do the range check again.
3885                                  * Expansion could still move past after this
3886                                  * test, but as we are holding a reference to
3887                                  * 'sh', we know that if that happens,
3888                                  *  STRIPE_EXPANDING will get set and the expansion
3889                                  * won't proceed until we finish with the stripe.
3890                                  */
3891                                 int must_retry = 0;
3892                                 spin_lock_irq(&conf->device_lock);
3893                                 if (mddev->delta_disks < 0
3894                                     ? logical_sector >= conf->reshape_progress
3895                                     : logical_sector < conf->reshape_progress)
3896                                         /* mismatch, need to try again */
3897                                         must_retry = 1;
3898                                 spin_unlock_irq(&conf->device_lock);
3899                                 if (must_retry) {
3900                                         release_stripe(sh);
3901                                         goto retry;
3902                                 }
3903                         }
3904                         /* FIXME what if we get a false positive because these
3905                          * are being updated.
3906                          */
3907                         if (logical_sector >= mddev->suspend_lo &&
3908                             logical_sector < mddev->suspend_hi) {
3909                                 release_stripe(sh);
3910                                 schedule();
3911                                 goto retry;
3912                         }
3913
3914                         if (test_bit(STRIPE_EXPANDING, &sh->state) ||
3915                             !add_stripe_bio(sh, bi, dd_idx, (bi->bi_rw&RW_MASK))) {
3916                                 /* Stripe is busy expanding or
3917                                  * add failed due to overlap.  Flush everything
3918                                  * and wait a while
3919                                  */
3920                                 raid5_unplug_device(mddev->queue);
3921                                 release_stripe(sh);
3922                                 schedule();
3923                                 goto retry;
3924                         }
3925                         finish_wait(&conf->wait_for_overlap, &w);
3926                         set_bit(STRIPE_HANDLE, &sh->state);
3927                         clear_bit(STRIPE_DELAYED, &sh->state);
3928                         release_stripe(sh);
3929                 } else {
3930                         /* cannot get stripe for read-ahead, just give-up */
3931                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
3932                         finish_wait(&conf->wait_for_overlap, &w);
3933                         break;
3934                 }
3935                         
3936         }
3937         spin_lock_irq(&conf->device_lock);
3938         remaining = raid5_dec_bi_phys_segments(bi);
3939         spin_unlock_irq(&conf->device_lock);
3940         if (remaining == 0) {
3941
3942                 if ( rw == WRITE )
3943                         md_write_end(mddev);
3944
3945                 bio_endio(bi, 0);
3946         }
3947         return 0;
3948 }
3949
3950 static sector_t raid5_size(mddev_t *mddev, sector_t sectors, int raid_disks);
3951
3952 static sector_t reshape_request(mddev_t *mddev, sector_t sector_nr, int *skipped)
3953 {
3954         /* reshaping is quite different to recovery/resync so it is
3955          * handled quite separately ... here.
3956          *
3957          * On each call to sync_request, we gather one chunk worth of
3958          * destination stripes and flag them as expanding.
3959          * Then we find all the source stripes and request reads.
3960          * As the reads complete, handle_stripe will copy the data
3961          * into the destination stripe and release that stripe.
3962          */
3963         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
3964         struct stripe_head *sh;
3965         sector_t first_sector, last_sector;
3966         int raid_disks = conf->previous_raid_disks;
3967         int data_disks = raid_disks - conf->max_degraded;
3968         int new_data_disks = conf->raid_disks - conf->max_degraded;
3969         int i;
3970         int dd_idx;
3971         sector_t writepos, readpos, safepos;
3972         sector_t stripe_addr;
3973         int reshape_sectors;
3974         struct list_head stripes;
3975
3976         if (sector_nr == 0) {
3977                 /* If restarting in the middle, skip the initial sectors */
3978                 if (mddev->delta_disks < 0 &&
3979                     conf->reshape_progress < raid5_size(mddev, 0, 0)) {
3980                         sector_nr = raid5_size(mddev, 0, 0)
3981                                 - conf->reshape_progress;
3982                 } else if (mddev->delta_disks > 0 &&
3983                            conf->reshape_progress > 0)
3984                         sector_nr = conf->reshape_progress;
3985                 sector_div(sector_nr, new_data_disks);
3986                 if (sector_nr) {
3987                         *skipped = 1;
3988                         return sector_nr;
3989                 }
3990         }
3991
3992         /* We need to process a full chunk at a time.
3993          * If old and new chunk sizes differ, we need to process the
3994          * largest of these
3995          */
3996         if (mddev->new_chunk > mddev->chunk_size)
3997                 reshape_sectors = mddev->new_chunk / 512;
3998         else
3999                 reshape_sectors = mddev->chunk_size / 512;
4000
4001         /* we update the metadata when there is more than 3Meg
4002          * in the block range (that is rather arbitrary, should
4003          * probably be time based) or when the data about to be
4004          * copied would over-write the source of the data at
4005          * the front of the range.
4006          * i.e. one new_stripe along from reshape_progress new_maps
4007          * to after where reshape_safe old_maps to
4008          */
4009         writepos = conf->reshape_progress;
4010         sector_div(writepos, new_data_disks);
4011         readpos = conf->reshape_progress;
4012         sector_div(readpos, data_disks);
4013         safepos = conf->reshape_safe;
4014         sector_div(safepos, data_disks);
4015         if (mddev->delta_disks < 0) {
4016                 writepos -= reshape_sectors;
4017                 readpos += reshape_sectors;
4018                 safepos += reshape_sectors;
4019         } else {
4020                 writepos += reshape_sectors;
4021                 readpos -= reshape_sectors;
4022                 safepos -= reshape_sectors;
4023         }
4024
4025         /* 'writepos' is the most advanced device address we might write.
4026          * 'readpos' is the least advanced device address we might read.
4027          * 'safepos' is the least address recorded in the metadata as having
4028          *     been reshaped.
4029          * If 'readpos' is behind 'writepos', then there is no way that we can
4030          * ensure safety in the face of a crash - that must be done by userspace
4031          * making a backup of the data.  So in that case there is no particular
4032          * rush to update metadata.
4033          * Otherwise if 'safepos' is behind 'writepos', then we really need to
4034          * update the metadata to advance 'safepos' to match 'readpos' so that
4035          * we can be safe in the event of a crash.
4036          * So we insist on updating metadata if safepos is behind writepos and
4037          * readpos is beyond writepos.
4038          * In any case, update the metadata every 10 seconds.
4039          * Maybe that number should be configurable, but I'm not sure it is
4040          * worth it.... maybe it could be a multiple of safemode_delay???
4041          */
4042         if ((mddev->delta_disks < 0
4043              ? (safepos > writepos && readpos < writepos)
4044              : (safepos < writepos && readpos > writepos)) ||
4045             time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
4046                 /* Cannot proceed until we've updated the superblock... */
4047                 wait_event(conf->wait_for_overlap,
4048                            atomic_read(&conf->reshape_stripes)==0);
4049                 mddev->reshape_position = conf->reshape_progress;
4050                 conf->reshape_checkpoint = jiffies;
4051                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
4052                 md_wakeup_thread(mddev->thread);
4053                 wait_event(mddev->sb_wait, mddev->flags == 0 ||
4054                            kthread_should_stop());
4055                 spin_lock_irq(&conf->device_lock);
4056                 conf->reshape_safe = mddev->reshape_position;
4057                 spin_unlock_irq(&conf->device_lock);
4058                 wake_up(&conf->wait_for_overlap);
4059         }
4060
4061         if (mddev->delta_disks < 0) {
4062                 BUG_ON(conf->reshape_progress == 0);
4063                 stripe_addr = writepos;
4064                 BUG_ON((mddev->dev_sectors &
4065                         ~((sector_t)reshape_sectors - 1))
4066                        - reshape_sectors - stripe_addr
4067                        != sector_nr);
4068         } else {
4069                 BUG_ON(writepos != sector_nr + reshape_sectors);
4070                 stripe_addr = sector_nr;
4071         }
4072         INIT_LIST_HEAD(&stripes);
4073         for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
4074                 int j;
4075                 int skipped = 0;
4076                 sh = get_active_stripe(conf, stripe_addr+i, 0, 0);
4077                 set_bit(STRIPE_EXPANDING, &sh->state);
4078                 atomic_inc(&conf->reshape_stripes);
4079                 /* If any of this stripe is beyond the end of the old
4080                  * array, then we need to zero those blocks
4081                  */
4082                 for (j=sh->disks; j--;) {
4083                         sector_t s;
4084                         if (j == sh->pd_idx)
4085                                 continue;
4086                         if (conf->level == 6 &&
4087                             j == sh->qd_idx)
4088                                 continue;
4089                         s = compute_blocknr(sh, j, 0);
4090                         if (s < raid5_size(mddev, 0, 0)) {
4091                                 skipped = 1;
4092                                 continue;
4093                         }
4094                         memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
4095                         set_bit(R5_Expanded, &sh->dev[j].flags);
4096                         set_bit(R5_UPTODATE, &sh->dev[j].flags);
4097                 }
4098                 if (!skipped) {
4099                         set_bit(STRIPE_EXPAND_READY, &sh->state);
4100                         set_bit(STRIPE_HANDLE, &sh->state);
4101                 }
4102                 list_add(&sh->lru, &stripes);
4103         }
4104         spin_lock_irq(&conf->device_lock);
4105         if (mddev->delta_disks < 0)
4106                 conf->reshape_progress -= reshape_sectors * new_data_disks;
4107         else
4108                 conf->reshape_progress += reshape_sectors * new_data_disks;
4109         spin_unlock_irq(&conf->device_lock);
4110         /* Ok, those stripe are ready. We can start scheduling
4111          * reads on the source stripes.
4112          * The source stripes are determined by mapping the first and last
4113          * block on the destination stripes.
4114          */
4115         first_sector =
4116                 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
4117                                      1, &dd_idx, NULL);
4118         last_sector =
4119                 raid5_compute_sector(conf, ((stripe_addr+conf->chunk_size/512)
4120                                             *(new_data_disks) - 1),
4121                                      1, &dd_idx, NULL);
4122         if (last_sector >= mddev->dev_sectors)
4123                 last_sector = mddev->dev_sectors - 1;
4124         while (first_sector <= last_sector) {
4125                 sh = get_active_stripe(conf, first_sector, 1, 0);
4126                 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4127                 set_bit(STRIPE_HANDLE, &sh->state);
4128                 release_stripe(sh);
4129                 first_sector += STRIPE_SECTORS;
4130         }
4131         /* Now that the sources are clearly marked, we can release
4132          * the destination stripes
4133          */
4134         while (!list_empty(&stripes)) {
4135                 sh = list_entry(stripes.next, struct stripe_head, lru);
4136                 list_del_init(&sh->lru);
4137                 release_stripe(sh);
4138         }
4139         /* If this takes us to the resync_max point where we have to pause,
4140          * then we need to write out the superblock.
4141          */
4142         sector_nr += reshape_sectors;
4143         if (sector_nr >= mddev->resync_max) {
4144                 /* Cannot proceed until we've updated the superblock... */
4145                 wait_event(conf->wait_for_overlap,
4146                            atomic_read(&conf->reshape_stripes) == 0);
4147                 mddev->reshape_position = conf->reshape_progress;
4148                 conf->reshape_checkpoint = jiffies;
4149                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
4150                 md_wakeup_thread(mddev->thread);
4151                 wait_event(mddev->sb_wait,
4152                            !test_bit(MD_CHANGE_DEVS, &mddev->flags)
4153                            || kthread_should_stop());
4154                 spin_lock_irq(&conf->device_lock);
4155                 conf->reshape_safe = mddev->reshape_position;
4156                 spin_unlock_irq(&conf->device_lock);
4157                 wake_up(&conf->wait_for_overlap);
4158         }
4159         return reshape_sectors;
4160 }
4161
4162 /* FIXME go_faster isn't used */
4163 static inline sector_t sync_request(mddev_t *mddev, sector_t sector_nr, int *skipped, int go_faster)
4164 {
4165         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
4166         struct stripe_head *sh;
4167         sector_t max_sector = mddev->dev_sectors;
4168         int sync_blocks;
4169         int still_degraded = 0;
4170         int i;
4171
4172         if (sector_nr >= max_sector) {
4173                 /* just being told to finish up .. nothing much to do */
4174                 unplug_slaves(mddev);
4175
4176                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
4177                         end_reshape(conf);
4178                         return 0;
4179                 }
4180
4181                 if (mddev->curr_resync < max_sector) /* aborted */
4182                         bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
4183                                         &sync_blocks, 1);
4184                 else /* completed sync */
4185                         conf->fullsync = 0;
4186                 bitmap_close_sync(mddev->bitmap);
4187
4188                 return 0;
4189         }
4190
4191         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4192                 return reshape_request(mddev, sector_nr, skipped);
4193
4194         /* No need to check resync_max as we never do more than one
4195          * stripe, and as resync_max will always be on a chunk boundary,
4196          * if the check in md_do_sync didn't fire, there is no chance
4197          * of overstepping resync_max here
4198          */
4199
4200         /* if there is too many failed drives and we are trying
4201          * to resync, then assert that we are finished, because there is
4202          * nothing we can do.
4203          */
4204         if (mddev->degraded >= conf->max_degraded &&
4205             test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4206                 sector_t rv = mddev->dev_sectors - sector_nr;
4207                 *skipped = 1;
4208                 return rv;
4209         }
4210         if (!bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
4211             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
4212             !conf->fullsync && sync_blocks >= STRIPE_SECTORS) {
4213                 /* we can skip this block, and probably more */
4214                 sync_blocks /= STRIPE_SECTORS;
4215                 *skipped = 1;
4216                 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
4217         }
4218
4219
4220         bitmap_cond_end_sync(mddev->bitmap, sector_nr);
4221
4222         sh = get_active_stripe(conf, sector_nr, 0, 1);
4223         if (sh == NULL) {
4224                 sh = get_active_stripe(conf, sector_nr, 0, 0);
4225                 /* make sure we don't swamp the stripe cache if someone else
4226                  * is trying to get access
4227                  */
4228                 schedule_timeout_uninterruptible(1);
4229         }
4230         /* Need to check if array will still be degraded after recovery/resync
4231          * We don't need to check the 'failed' flag as when that gets set,
4232          * recovery aborts.
4233          */
4234         for (i=0; i<mddev->raid_disks; i++)
4235                 if (conf->disks[i].rdev == NULL)
4236                         still_degraded = 1;
4237
4238         bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
4239
4240         spin_lock(&sh->lock);
4241         set_bit(STRIPE_SYNCING, &sh->state);
4242         clear_bit(STRIPE_INSYNC, &sh->state);
4243         spin_unlock(&sh->lock);
4244
4245         /* wait for any blocked device to be handled */
4246         while (unlikely(!handle_stripe(sh)))
4247                 ;
4248         release_stripe(sh);
4249
4250         return STRIPE_SECTORS;
4251 }
4252
4253 static int  retry_aligned_read(raid5_conf_t *conf, struct bio *raid_bio)
4254 {
4255         /* We may not be able to submit a whole bio at once as there
4256          * may not be enough stripe_heads available.
4257          * We cannot pre-allocate enough stripe_heads as we may need
4258          * more than exist in the cache (if we allow ever large chunks).
4259          * So we do one stripe head at a time and record in
4260          * ->bi_hw_segments how many have been done.
4261          *
4262          * We *know* that this entire raid_bio is in one chunk, so
4263          * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
4264          */
4265         struct stripe_head *sh;
4266         int dd_idx;
4267         sector_t sector, logical_sector, last_sector;
4268         int scnt = 0;
4269         int remaining;
4270         int handled = 0;
4271
4272         logical_sector = raid_bio->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4273         sector = raid5_compute_sector(conf, logical_sector,
4274                                       0, &dd_idx, NULL);
4275         last_sector = raid_bio->bi_sector + (raid_bio->bi_size>>9);
4276
4277         for (; logical_sector < last_sector;
4278              logical_sector += STRIPE_SECTORS,
4279                      sector += STRIPE_SECTORS,
4280                      scnt++) {
4281
4282                 if (scnt < raid5_bi_hw_segments(raid_bio))
4283                         /* already done this stripe */
4284                         continue;
4285
4286                 sh = get_active_stripe(conf, sector, 0, 1);
4287
4288                 if (!sh) {
4289                         /* failed to get a stripe - must wait */
4290                         raid5_set_bi_hw_segments(raid_bio, scnt);
4291                         conf->retry_read_aligned = raid_bio;
4292                         return handled;
4293                 }
4294
4295                 set_bit(R5_ReadError, &sh->dev[dd_idx].flags);
4296                 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0)) {
4297                         release_stripe(sh);
4298                         raid5_set_bi_hw_segments(raid_bio, scnt);
4299                         conf->retry_read_aligned = raid_bio;
4300                         return handled;
4301                 }
4302
4303                 handle_stripe(sh);
4304                 release_stripe(sh);
4305                 handled++;
4306         }
4307         spin_lock_irq(&conf->device_lock);
4308         remaining = raid5_dec_bi_phys_segments(raid_bio);
4309         spin_unlock_irq(&conf->device_lock);
4310         if (remaining == 0)
4311                 bio_endio(raid_bio, 0);
4312         if (atomic_dec_and_test(&conf->active_aligned_reads))
4313                 wake_up(&conf->wait_for_stripe);
4314         return handled;
4315 }
4316
4317
4318
4319 /*
4320  * This is our raid5 kernel thread.
4321  *
4322  * We scan the hash table for stripes which can be handled now.
4323  * During the scan, completed stripes are saved for us by the interrupt
4324  * handler, so that they will not have to wait for our next wakeup.
4325  */
4326 static void raid5d(mddev_t *mddev)
4327 {
4328         struct stripe_head *sh;
4329         raid5_conf_t *conf = mddev_to_conf(mddev);
4330         int handled;
4331
4332         pr_debug("+++ raid5d active\n");
4333
4334         md_check_recovery(mddev);
4335
4336         handled = 0;
4337         spin_lock_irq(&conf->device_lock);
4338         while (1) {
4339                 struct bio *bio;
4340
4341                 if (conf->seq_flush != conf->seq_write) {
4342                         int seq = conf->seq_flush;
4343                         spin_unlock_irq(&conf->device_lock);
4344                         bitmap_unplug(mddev->bitmap);
4345                         spin_lock_irq(&conf->device_lock);
4346                         conf->seq_write = seq;
4347                         activate_bit_delay(conf);
4348                 }
4349
4350                 while ((bio = remove_bio_from_retry(conf))) {
4351                         int ok;
4352                         spin_unlock_irq(&conf->device_lock);
4353                         ok = retry_aligned_read(conf, bio);
4354                         spin_lock_irq(&conf->device_lock);
4355                         if (!ok)
4356                                 break;
4357                         handled++;
4358                 }
4359
4360                 sh = __get_priority_stripe(conf);
4361
4362                 if (!sh)
4363                         break;
4364                 spin_unlock_irq(&conf->device_lock);
4365                 
4366                 handled++;
4367                 handle_stripe(sh);
4368                 release_stripe(sh);
4369
4370                 spin_lock_irq(&conf->device_lock);
4371         }
4372         pr_debug("%d stripes handled\n", handled);
4373
4374         spin_unlock_irq(&conf->device_lock);
4375
4376         async_tx_issue_pending_all();
4377         unplug_slaves(mddev);
4378
4379         pr_debug("--- raid5d inactive\n");
4380 }
4381
4382 static ssize_t
4383 raid5_show_stripe_cache_size(mddev_t *mddev, char *page)
4384 {
4385         raid5_conf_t *conf = mddev_to_conf(mddev);
4386         if (conf)
4387                 return sprintf(page, "%d\n", conf->max_nr_stripes);
4388         else
4389                 return 0;
4390 }
4391
4392 static ssize_t
4393 raid5_store_stripe_cache_size(mddev_t *mddev, const char *page, size_t len)
4394 {
4395         raid5_conf_t *conf = mddev_to_conf(mddev);
4396         unsigned long new;
4397         int err;
4398
4399         if (len >= PAGE_SIZE)
4400                 return -EINVAL;
4401         if (!conf)
4402                 return -ENODEV;
4403
4404         if (strict_strtoul(page, 10, &new))
4405                 return -EINVAL;
4406         if (new <= 16 || new > 32768)
4407                 return -EINVAL;
4408         while (new < conf->max_nr_stripes) {
4409                 if (drop_one_stripe(conf))
4410                         conf->max_nr_stripes--;
4411                 else
4412                         break;
4413         }
4414         err = md_allow_write(mddev);
4415         if (err)
4416                 return err;
4417         while (new > conf->max_nr_stripes) {
4418                 if (grow_one_stripe(conf))
4419                         conf->max_nr_stripes++;
4420                 else break;
4421         }
4422         return len;
4423 }
4424
4425 static struct md_sysfs_entry
4426 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
4427                                 raid5_show_stripe_cache_size,
4428                                 raid5_store_stripe_cache_size);
4429
4430 static ssize_t
4431 raid5_show_preread_threshold(mddev_t *mddev, char *page)
4432 {
4433         raid5_conf_t *conf = mddev_to_conf(mddev);
4434         if (conf)
4435                 return sprintf(page, "%d\n", conf->bypass_threshold);
4436         else
4437                 return 0;
4438 }
4439
4440 static ssize_t
4441 raid5_store_preread_threshold(mddev_t *mddev, const char *page, size_t len)
4442 {
4443         raid5_conf_t *conf = mddev_to_conf(mddev);
4444         unsigned long new;
4445         if (len >= PAGE_SIZE)
4446                 return -EINVAL;
4447         if (!conf)
4448                 return -ENODEV;
4449
4450         if (strict_strtoul(page, 10, &new))
4451                 return -EINVAL;
4452         if (new > conf->max_nr_stripes)
4453                 return -EINVAL;
4454         conf->bypass_threshold = new;
4455         return len;
4456 }
4457
4458 static struct md_sysfs_entry
4459 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
4460                                         S_IRUGO | S_IWUSR,
4461                                         raid5_show_preread_threshold,
4462                                         raid5_store_preread_threshold);
4463
4464 static ssize_t
4465 stripe_cache_active_show(mddev_t *mddev, char *page)
4466 {
4467         raid5_conf_t *conf = mddev_to_conf(mddev);
4468         if (conf)
4469                 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
4470         else
4471                 return 0;
4472 }
4473
4474 static struct md_sysfs_entry
4475 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
4476
4477 static struct attribute *raid5_attrs[] =  {
4478         &raid5_stripecache_size.attr,
4479         &raid5_stripecache_active.attr,
4480         &raid5_preread_bypass_threshold.attr,
4481         NULL,
4482 };
4483 static struct attribute_group raid5_attrs_group = {
4484         .name = NULL,
4485         .attrs = raid5_attrs,
4486 };
4487
4488 static sector_t
4489 raid5_size(mddev_t *mddev, sector_t sectors, int raid_disks)
4490 {
4491         raid5_conf_t *conf = mddev_to_conf(mddev);
4492
4493         if (!sectors)
4494                 sectors = mddev->dev_sectors;
4495         if (!raid_disks) {
4496                 /* size is defined by the smallest of previous and new size */
4497                 if (conf->raid_disks < conf->previous_raid_disks)
4498                         raid_disks = conf->raid_disks;
4499                 else
4500                         raid_disks = conf->previous_raid_disks;
4501         }
4502
4503         sectors &= ~((sector_t)mddev->chunk_size/512 - 1);
4504         sectors &= ~((sector_t)mddev->new_chunk/512 - 1);
4505         return sectors * (raid_disks - conf->max_degraded);
4506 }
4507
4508 static void raid5_free_percpu(raid5_conf_t *conf)
4509 {
4510         struct raid5_percpu *percpu;
4511         unsigned long cpu;
4512
4513         if (!conf->percpu)
4514                 return;
4515
4516         get_online_cpus();
4517         for_each_possible_cpu(cpu) {
4518                 percpu = per_cpu_ptr(conf->percpu, cpu);
4519                 safe_put_page(percpu->spare_page);
4520                 kfree(percpu->scribble);
4521         }
4522 #ifdef CONFIG_HOTPLUG_CPU
4523         unregister_cpu_notifier(&conf->cpu_notify);
4524 #endif
4525         put_online_cpus();
4526
4527         free_percpu(conf->percpu);
4528 }
4529
4530 static void free_conf(raid5_conf_t *conf)
4531 {
4532         shrink_stripes(conf);
4533         raid5_free_percpu(conf);
4534         kfree(conf->disks);
4535         kfree(conf->stripe_hashtbl);
4536         kfree(conf);
4537 }
4538
4539 #ifdef CONFIG_HOTPLUG_CPU
4540 static int raid456_cpu_notify(struct notifier_block *nfb, unsigned long action,
4541                               void *hcpu)
4542 {
4543         raid5_conf_t *conf = container_of(nfb, raid5_conf_t, cpu_notify);
4544         long cpu = (long)hcpu;
4545         struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
4546
4547         switch (action) {
4548         case CPU_UP_PREPARE:
4549         case CPU_UP_PREPARE_FROZEN:
4550                 if (conf->level == 6 && !percpu->spare_page)
4551                         percpu->spare_page = alloc_page(GFP_KERNEL);
4552                 if (!percpu->scribble)
4553                         percpu->scribble = kmalloc(conf->scribble_len, GFP_KERNEL);
4554
4555                 if (!percpu->scribble ||
4556                     (conf->level == 6 && !percpu->spare_page)) {
4557                         safe_put_page(percpu->spare_page);
4558                         kfree(percpu->scribble);
4559                         pr_err("%s: failed memory allocation for cpu%ld\n",
4560                                __func__, cpu);
4561                         return NOTIFY_BAD;
4562                 }
4563                 break;
4564         case CPU_DEAD:
4565         case CPU_DEAD_FROZEN:
4566                 safe_put_page(percpu->spare_page);
4567                 kfree(percpu->scribble);
4568                 percpu->spare_page = NULL;
4569                 percpu->scribble = NULL;
4570                 break;
4571         default:
4572                 break;
4573         }
4574         return NOTIFY_OK;
4575 }
4576 #endif
4577
4578 static int raid5_alloc_percpu(raid5_conf_t *conf)
4579 {
4580         unsigned long cpu;
4581         struct page *spare_page;
4582         struct raid5_percpu *allcpus;
4583         void *scribble;
4584         int err;
4585
4586         allcpus = alloc_percpu(struct raid5_percpu);
4587         if (!allcpus)
4588                 return -ENOMEM;
4589         conf->percpu = allcpus;
4590
4591         get_online_cpus();
4592         err = 0;
4593         for_each_present_cpu(cpu) {
4594                 if (conf->level == 6) {
4595                         spare_page = alloc_page(GFP_KERNEL);
4596                         if (!spare_page) {
4597                                 err = -ENOMEM;
4598                                 break;
4599                         }
4600                         per_cpu_ptr(conf->percpu, cpu)->spare_page = spare_page;
4601                 }
4602                 scribble = kmalloc(scribble_len(conf->raid_disks), GFP_KERNEL);
4603                 if (!scribble) {
4604                         err = -ENOMEM;
4605                         break;
4606                 }
4607                 per_cpu_ptr(conf->percpu, cpu)->scribble = scribble;
4608         }
4609 #ifdef CONFIG_HOTPLUG_CPU
4610         conf->cpu_notify.notifier_call = raid456_cpu_notify;
4611         conf->cpu_notify.priority = 0;
4612         if (err == 0)
4613                 err = register_cpu_notifier(&conf->cpu_notify);
4614 #endif
4615         put_online_cpus();
4616
4617         return err;
4618 }
4619
4620 static raid5_conf_t *setup_conf(mddev_t *mddev)
4621 {
4622         raid5_conf_t *conf;
4623         int raid_disk, memory;
4624         mdk_rdev_t *rdev;
4625         struct disk_info *disk;
4626
4627         if (mddev->new_level != 5
4628             && mddev->new_level != 4
4629             && mddev->new_level != 6) {
4630                 printk(KERN_ERR "raid5: %s: raid level not set to 4/5/6 (%d)\n",
4631                        mdname(mddev), mddev->new_level);
4632                 return ERR_PTR(-EIO);
4633         }
4634         if ((mddev->new_level == 5
4635              && !algorithm_valid_raid5(mddev->new_layout)) ||
4636             (mddev->new_level == 6
4637              && !algorithm_valid_raid6(mddev->new_layout))) {
4638                 printk(KERN_ERR "raid5: %s: layout %d not supported\n",
4639                        mdname(mddev), mddev->new_layout);
4640                 return ERR_PTR(-EIO);
4641         }
4642         if (mddev->new_level == 6 && mddev->raid_disks < 4) {
4643                 printk(KERN_ERR "raid6: not enough configured devices for %s (%d, minimum 4)\n",
4644                        mdname(mddev), mddev->raid_disks);
4645                 return ERR_PTR(-EINVAL);
4646         }
4647
4648         if (!mddev->new_chunk || mddev->new_chunk % PAGE_SIZE) {
4649                 printk(KERN_ERR "raid5: invalid chunk size %d for %s\n",
4650                         mddev->new_chunk, mdname(mddev));
4651                 return ERR_PTR(-EINVAL);
4652         }
4653
4654         conf = kzalloc(sizeof(raid5_conf_t), GFP_KERNEL);
4655         if (conf == NULL)
4656                 goto abort;
4657
4658         conf->raid_disks = mddev->raid_disks;
4659         conf->scribble_len = scribble_len(conf->raid_disks);
4660         if (mddev->reshape_position == MaxSector)
4661                 conf->previous_raid_disks = mddev->raid_disks;
4662         else
4663                 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
4664
4665         conf->disks = kzalloc(conf->raid_disks * sizeof(struct disk_info),
4666                               GFP_KERNEL);
4667         if (!conf->disks)
4668                 goto abort;
4669
4670         conf->mddev = mddev;
4671
4672         if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
4673                 goto abort;
4674
4675         conf->level = mddev->new_level;
4676         if (raid5_alloc_percpu(conf) != 0)
4677                 goto abort;
4678
4679         spin_lock_init(&conf->device_lock);
4680         init_waitqueue_head(&conf->wait_for_stripe);
4681         init_waitqueue_head(&conf->wait_for_overlap);
4682         INIT_LIST_HEAD(&conf->handle_list);
4683         INIT_LIST_HEAD(&conf->hold_list);
4684         INIT_LIST_HEAD(&conf->delayed_list);
4685         INIT_LIST_HEAD(&conf->bitmap_list);
4686         INIT_LIST_HEAD(&conf->inactive_list);
4687         atomic_set(&conf->active_stripes, 0);
4688         atomic_set(&conf->preread_active_stripes, 0);
4689         atomic_set(&conf->active_aligned_reads, 0);
4690         conf->bypass_threshold = BYPASS_THRESHOLD;
4691
4692         pr_debug("raid5: run(%s) called.\n", mdname(mddev));
4693
4694         list_for_each_entry(rdev, &mddev->disks, same_set) {
4695                 raid_disk = rdev->raid_disk;
4696                 if (raid_disk >= conf->raid_disks
4697                     || raid_disk < 0)
4698                         continue;
4699                 disk = conf->disks + raid_disk;
4700
4701                 disk->rdev = rdev;
4702
4703                 if (test_bit(In_sync, &rdev->flags)) {
4704                         char b[BDEVNAME_SIZE];
4705                         printk(KERN_INFO "raid5: device %s operational as raid"
4706                                 " disk %d\n", bdevname(rdev->bdev,b),
4707                                 raid_disk);
4708                 } else
4709                         /* Cannot rely on bitmap to complete recovery */
4710                         conf->fullsync = 1;
4711         }
4712
4713         conf->chunk_size = mddev->new_chunk;
4714         if (conf->level == 6)
4715                 conf->max_degraded = 2;
4716         else
4717                 conf->max_degraded = 1;
4718         conf->algorithm = mddev->new_layout;
4719         conf->max_nr_stripes = NR_STRIPES;
4720         conf->reshape_progress = mddev->reshape_position;
4721         if (conf->reshape_progress != MaxSector) {
4722                 conf->prev_chunk = mddev->chunk_size;
4723                 conf->prev_algo = mddev->layout;
4724         }
4725
4726         memory = conf->max_nr_stripes * (sizeof(struct stripe_head) +
4727                  conf->raid_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
4728         if (grow_stripes(conf, conf->max_nr_stripes)) {
4729                 printk(KERN_ERR
4730                         "raid5: couldn't allocate %dkB for buffers\n", memory);
4731                 goto abort;
4732         } else
4733                 printk(KERN_INFO "raid5: allocated %dkB for %s\n",
4734                         memory, mdname(mddev));
4735
4736         conf->thread = md_register_thread(raid5d, mddev, "%s_raid5");
4737         if (!conf->thread) {
4738                 printk(KERN_ERR
4739                        "raid5: couldn't allocate thread for %s\n",
4740                        mdname(mddev));
4741                 goto abort;
4742         }
4743
4744         return conf;
4745
4746  abort:
4747         if (conf) {
4748                 free_conf(conf);
4749                 return ERR_PTR(-EIO);
4750         } else
4751                 return ERR_PTR(-ENOMEM);
4752 }
4753
4754 static int run(mddev_t *mddev)
4755 {
4756         raid5_conf_t *conf;
4757         int working_disks = 0;
4758         mdk_rdev_t *rdev;
4759
4760         if (mddev->reshape_position != MaxSector) {
4761                 /* Check that we can continue the reshape.
4762                  * Currently only disks can change, it must
4763                  * increase, and we must be past the point where
4764                  * a stripe over-writes itself
4765                  */
4766                 sector_t here_new, here_old;
4767                 int old_disks;
4768                 int max_degraded = (mddev->level == 6 ? 2 : 1);
4769
4770                 if (mddev->new_level != mddev->level) {
4771                         printk(KERN_ERR "raid5: %s: unsupported reshape "
4772                                "required - aborting.\n",
4773                                mdname(mddev));
4774                         return -EINVAL;
4775                 }
4776                 old_disks = mddev->raid_disks - mddev->delta_disks;
4777                 /* reshape_position must be on a new-stripe boundary, and one
4778                  * further up in new geometry must map after here in old
4779                  * geometry.
4780                  */
4781                 here_new = mddev->reshape_position;
4782                 if (sector_div(here_new, (mddev->new_chunk>>9)*
4783                                (mddev->raid_disks - max_degraded))) {
4784                         printk(KERN_ERR "raid5: reshape_position not "
4785                                "on a stripe boundary\n");
4786                         return -EINVAL;
4787                 }
4788                 /* here_new is the stripe we will write to */
4789                 here_old = mddev->reshape_position;
4790                 sector_div(here_old, (mddev->chunk_size>>9)*
4791                            (old_disks-max_degraded));
4792                 /* here_old is the first stripe that we might need to read
4793                  * from */
4794                 if (here_new >= here_old) {
4795                         /* Reading from the same stripe as writing to - bad */
4796                         printk(KERN_ERR "raid5: reshape_position too early for "
4797                                "auto-recovery - aborting.\n");
4798                         return -EINVAL;
4799                 }
4800                 printk(KERN_INFO "raid5: reshape will continue\n");
4801                 /* OK, we should be able to continue; */
4802         } else {
4803                 BUG_ON(mddev->level != mddev->new_level);
4804                 BUG_ON(mddev->layout != mddev->new_layout);
4805                 BUG_ON(mddev->chunk_size != mddev->new_chunk);
4806                 BUG_ON(mddev->delta_disks != 0);
4807         }
4808
4809         if (mddev->private == NULL)
4810                 conf = setup_conf(mddev);
4811         else
4812                 conf = mddev->private;
4813
4814         if (IS_ERR(conf))
4815                 return PTR_ERR(conf);
4816
4817         mddev->thread = conf->thread;
4818         conf->thread = NULL;
4819         mddev->private = conf;
4820
4821         /*
4822          * 0 for a fully functional array, 1 or 2 for a degraded array.
4823          */
4824         list_for_each_entry(rdev, &mddev->disks, same_set)
4825                 if (rdev->raid_disk >= 0 &&
4826                     test_bit(In_sync, &rdev->flags))
4827                         working_disks++;
4828
4829         mddev->degraded = conf->raid_disks - working_disks;
4830
4831         if (mddev->degraded > conf->max_degraded) {
4832                 printk(KERN_ERR "raid5: not enough operational devices for %s"
4833                         " (%d/%d failed)\n",
4834                         mdname(mddev), mddev->degraded, conf->raid_disks);
4835                 goto abort;
4836         }
4837
4838         /* device size must be a multiple of chunk size */
4839         mddev->dev_sectors &= ~(mddev->chunk_size / 512 - 1);
4840         mddev->resync_max_sectors = mddev->dev_sectors;
4841
4842         if (mddev->degraded > 0 &&
4843             mddev->recovery_cp != MaxSector) {
4844                 if (mddev->ok_start_degraded)
4845                         printk(KERN_WARNING
4846                                "raid5: starting dirty degraded array: %s"
4847                                "- data corruption possible.\n",
4848                                mdname(mddev));
4849                 else {
4850                         printk(KERN_ERR
4851                                "raid5: cannot start dirty degraded array for %s\n",
4852                                mdname(mddev));
4853                         goto abort;
4854                 }
4855         }
4856
4857         if (mddev->degraded == 0)
4858                 printk("raid5: raid level %d set %s active with %d out of %d"
4859                        " devices, algorithm %d\n", conf->level, mdname(mddev),
4860                        mddev->raid_disks-mddev->degraded, mddev->raid_disks,
4861                        mddev->new_layout);
4862         else
4863                 printk(KERN_ALERT "raid5: raid level %d set %s active with %d"
4864                         " out of %d devices, algorithm %d\n", conf->level,
4865                         mdname(mddev), mddev->raid_disks - mddev->degraded,
4866                         mddev->raid_disks, mddev->new_layout);
4867
4868         print_raid5_conf(conf);
4869
4870         if (conf->reshape_progress != MaxSector) {
4871                 printk("...ok start reshape thread\n");
4872                 conf->reshape_safe = conf->reshape_progress;
4873                 atomic_set(&conf->reshape_stripes, 0);
4874                 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4875                 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4876                 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
4877                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
4878                 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
4879                                                         "%s_reshape");
4880         }
4881
4882         /* read-ahead size must cover two whole stripes, which is
4883          * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
4884          */
4885         {
4886                 int data_disks = conf->previous_raid_disks - conf->max_degraded;
4887                 int stripe = data_disks *
4888                         (mddev->chunk_size / PAGE_SIZE);
4889                 if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
4890                         mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
4891         }
4892
4893         /* Ok, everything is just fine now */
4894         if (sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
4895                 printk(KERN_WARNING
4896                        "raid5: failed to create sysfs attributes for %s\n",
4897                        mdname(mddev));
4898
4899         mddev->queue->queue_lock = &conf->device_lock;
4900
4901         mddev->queue->unplug_fn = raid5_unplug_device;
4902         mddev->queue->backing_dev_info.congested_data = mddev;
4903         mddev->queue->backing_dev_info.congested_fn = raid5_congested;
4904
4905         md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
4906
4907         blk_queue_merge_bvec(mddev->queue, raid5_mergeable_bvec);
4908
4909         return 0;
4910 abort:
4911         md_unregister_thread(mddev->thread);
4912         mddev->thread = NULL;
4913         if (conf) {
4914                 print_raid5_conf(conf);
4915                 free_conf(conf);
4916         }
4917         mddev->private = NULL;
4918         printk(KERN_ALERT "raid5: failed to run raid set %s\n", mdname(mddev));
4919         return -EIO;
4920 }
4921
4922
4923
4924 static int stop(mddev_t *mddev)
4925 {
4926         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
4927
4928         md_unregister_thread(mddev->thread);
4929         mddev->thread = NULL;
4930         mddev->queue->backing_dev_info.congested_fn = NULL;
4931         blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
4932         sysfs_remove_group(&mddev->kobj, &raid5_attrs_group);
4933         free_conf(conf);
4934         mddev->private = NULL;
4935         return 0;
4936 }
4937
4938 #ifdef DEBUG
4939 static void print_sh(struct seq_file *seq, struct stripe_head *sh)
4940 {
4941         int i;
4942
4943         seq_printf(seq, "sh %llu, pd_idx %d, state %ld.\n",
4944                    (unsigned long long)sh->sector, sh->pd_idx, sh->state);
4945         seq_printf(seq, "sh %llu,  count %d.\n",
4946                    (unsigned long long)sh->sector, atomic_read(&sh->count));
4947         seq_printf(seq, "sh %llu, ", (unsigned long long)sh->sector);
4948         for (i = 0; i < sh->disks; i++) {
4949                 seq_printf(seq, "(cache%d: %p %ld) ",
4950                            i, sh->dev[i].page, sh->dev[i].flags);
4951         }
4952         seq_printf(seq, "\n");
4953 }
4954
4955 static void printall(struct seq_file *seq, raid5_conf_t *conf)
4956 {
4957         struct stripe_head *sh;
4958         struct hlist_node *hn;
4959         int i;
4960
4961         spin_lock_irq(&conf->device_lock);
4962         for (i = 0; i < NR_HASH; i++) {
4963                 hlist_for_each_entry(sh, hn, &conf->stripe_hashtbl[i], hash) {
4964                         if (sh->raid_conf != conf)
4965                                 continue;
4966                         print_sh(seq, sh);
4967                 }
4968         }
4969         spin_unlock_irq(&conf->device_lock);
4970 }
4971 #endif
4972
4973 static void status(struct seq_file *seq, mddev_t *mddev)
4974 {
4975         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
4976         int i;
4977
4978         seq_printf (seq, " level %d, %dk chunk, algorithm %d", mddev->level, mddev->chunk_size >> 10, mddev->layout);
4979         seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
4980         for (i = 0; i < conf->raid_disks; i++)
4981                 seq_printf (seq, "%s",
4982                                conf->disks[i].rdev &&
4983                                test_bit(In_sync, &conf->disks[i].rdev->flags) ? "U" : "_");
4984         seq_printf (seq, "]");
4985 #ifdef DEBUG
4986         seq_printf (seq, "\n");
4987         printall(seq, conf);
4988 #endif
4989 }
4990
4991 static void print_raid5_conf (raid5_conf_t *conf)
4992 {
4993         int i;
4994         struct disk_info *tmp;
4995
4996         printk("RAID5 conf printout:\n");
4997         if (!conf) {
4998                 printk("(conf==NULL)\n");
4999                 return;
5000         }
5001         printk(" --- rd:%d wd:%d\n", conf->raid_disks,
5002                  conf->raid_disks - conf->mddev->degraded);
5003
5004         for (i = 0; i < conf->raid_disks; i++) {
5005                 char b[BDEVNAME_SIZE];
5006                 tmp = conf->disks + i;
5007                 if (tmp->rdev)
5008                 printk(" disk %d, o:%d, dev:%s\n",
5009                         i, !test_bit(Faulty, &tmp->rdev->flags),
5010                         bdevname(tmp->rdev->bdev,b));
5011         }
5012 }
5013
5014 static int raid5_spare_active(mddev_t *mddev)
5015 {
5016         int i;
5017         raid5_conf_t *conf = mddev->private;
5018         struct disk_info *tmp;
5019
5020         for (i = 0; i < conf->raid_disks; i++) {
5021                 tmp = conf->disks + i;
5022                 if (tmp->rdev
5023                     && !test_bit(Faulty, &tmp->rdev->flags)
5024                     && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
5025                         unsigned long flags;
5026                         spin_lock_irqsave(&conf->device_lock, flags);
5027                         mddev->degraded--;
5028                         spin_unlock_irqrestore(&conf->device_lock, flags);
5029                 }
5030         }
5031         print_raid5_conf(conf);
5032         return 0;
5033 }
5034
5035 static int raid5_remove_disk(mddev_t *mddev, int number)
5036 {
5037         raid5_conf_t *conf = mddev->private;
5038         int err = 0;
5039         mdk_rdev_t *rdev;
5040         struct disk_info *p = conf->disks + number;
5041
5042         print_raid5_conf(conf);
5043         rdev = p->rdev;
5044         if (rdev) {
5045                 if (number >= conf->raid_disks &&
5046                     conf->reshape_progress == MaxSector)
5047                         clear_bit(In_sync, &rdev->flags);
5048
5049                 if (test_bit(In_sync, &rdev->flags) ||
5050                     atomic_read(&rdev->nr_pending)) {
5051                         err = -EBUSY;
5052                         goto abort;
5053                 }
5054                 /* Only remove non-faulty devices if recovery
5055                  * isn't possible.
5056                  */
5057                 if (!test_bit(Faulty, &rdev->flags) &&
5058                     mddev->degraded <= conf->max_degraded &&
5059                     number < conf->raid_disks) {
5060                         err = -EBUSY;
5061                         goto abort;
5062                 }
5063                 p->rdev = NULL;
5064                 synchronize_rcu();
5065                 if (atomic_read(&rdev->nr_pending)) {
5066                         /* lost the race, try later */
5067                         err = -EBUSY;
5068                         p->rdev = rdev;
5069                 }
5070         }
5071 abort:
5072
5073         print_raid5_conf(conf);
5074         return err;
5075 }
5076
5077 static int raid5_add_disk(mddev_t *mddev, mdk_rdev_t *rdev)
5078 {
5079         raid5_conf_t *conf = mddev->private;
5080         int err = -EEXIST;
5081         int disk;
5082         struct disk_info *p;
5083         int first = 0;
5084         int last = conf->raid_disks - 1;
5085
5086         if (mddev->degraded > conf->max_degraded)
5087                 /* no point adding a device */
5088                 return -EINVAL;
5089
5090         if (rdev->raid_disk >= 0)
5091                 first = last = rdev->raid_disk;
5092
5093         /*
5094          * find the disk ... but prefer rdev->saved_raid_disk
5095          * if possible.
5096          */
5097         if (rdev->saved_raid_disk >= 0 &&
5098             rdev->saved_raid_disk >= first &&
5099             conf->disks[rdev->saved_raid_disk].rdev == NULL)
5100                 disk = rdev->saved_raid_disk;
5101         else
5102                 disk = first;
5103         for ( ; disk <= last ; disk++)
5104                 if ((p=conf->disks + disk)->rdev == NULL) {
5105                         clear_bit(In_sync, &rdev->flags);
5106                         rdev->raid_disk = disk;
5107                         err = 0;
5108                         if (rdev->saved_raid_disk != disk)
5109                                 conf->fullsync = 1;
5110                         rcu_assign_pointer(p->rdev, rdev);
5111                         break;
5112                 }
5113         print_raid5_conf(conf);
5114         return err;
5115 }
5116
5117 static int raid5_resize(mddev_t *mddev, sector_t sectors)
5118 {
5119         /* no resync is happening, and there is enough space
5120          * on all devices, so we can resize.
5121          * We need to make sure resync covers any new space.
5122          * If the array is shrinking we should possibly wait until
5123          * any io in the removed space completes, but it hardly seems
5124          * worth it.
5125          */
5126         sectors &= ~((sector_t)mddev->chunk_size/512 - 1);
5127         md_set_array_sectors(mddev, raid5_size(mddev, sectors,
5128                                                mddev->raid_disks));
5129         if (mddev->array_sectors >
5130             raid5_size(mddev, sectors, mddev->raid_disks))
5131                 return -EINVAL;
5132         set_capacity(mddev->gendisk, mddev->array_sectors);
5133         mddev->changed = 1;
5134         if (sectors > mddev->dev_sectors && mddev->recovery_cp == MaxSector) {
5135                 mddev->recovery_cp = mddev->dev_sectors;
5136                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5137         }
5138         mddev->dev_sectors = sectors;
5139         mddev->resync_max_sectors = sectors;
5140         return 0;
5141 }
5142
5143 static int raid5_check_reshape(mddev_t *mddev)
5144 {
5145         raid5_conf_t *conf = mddev_to_conf(mddev);
5146
5147         if (mddev->delta_disks == 0 &&
5148             mddev->new_layout == mddev->layout &&
5149             mddev->new_chunk == mddev->chunk_size)
5150                 return -EINVAL; /* nothing to do */
5151         if (mddev->bitmap)
5152                 /* Cannot grow a bitmap yet */
5153                 return -EBUSY;
5154         if (mddev->degraded > conf->max_degraded)
5155                 return -EINVAL;
5156         if (mddev->delta_disks < 0) {
5157                 /* We might be able to shrink, but the devices must
5158                  * be made bigger first.
5159                  * For raid6, 4 is the minimum size.
5160                  * Otherwise 2 is the minimum
5161                  */
5162                 int min = 2;
5163                 if (mddev->level == 6)
5164                         min = 4;
5165                 if (mddev->raid_disks + mddev->delta_disks < min)
5166                         return -EINVAL;
5167         }
5168
5169         /* Can only proceed if there are plenty of stripe_heads.
5170          * We need a minimum of one full stripe,, and for sensible progress
5171          * it is best to have about 4 times that.
5172          * If we require 4 times, then the default 256 4K stripe_heads will
5173          * allow for chunk sizes up to 256K, which is probably OK.
5174          * If the chunk size is greater, user-space should request more
5175          * stripe_heads first.
5176          */
5177         if ((mddev->chunk_size / STRIPE_SIZE) * 4 > conf->max_nr_stripes ||
5178             (mddev->new_chunk / STRIPE_SIZE) * 4 > conf->max_nr_stripes) {
5179                 printk(KERN_WARNING "raid5: reshape: not enough stripes.  Needed %lu\n",
5180                        (max(mddev->chunk_size, mddev->new_chunk)
5181                         / STRIPE_SIZE)*4);
5182                 return -ENOSPC;
5183         }
5184
5185         return resize_stripes(conf, conf->raid_disks + mddev->delta_disks);
5186 }
5187
5188 static int raid5_start_reshape(mddev_t *mddev)
5189 {
5190         raid5_conf_t *conf = mddev_to_conf(mddev);
5191         mdk_rdev_t *rdev;
5192         int spares = 0;
5193         int added_devices = 0;
5194         unsigned long flags;
5195
5196         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5197                 return -EBUSY;
5198
5199         list_for_each_entry(rdev, &mddev->disks, same_set)
5200                 if (rdev->raid_disk < 0 &&
5201                     !test_bit(Faulty, &rdev->flags))
5202                         spares++;
5203
5204         if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
5205                 /* Not enough devices even to make a degraded array
5206                  * of that size
5207                  */
5208                 return -EINVAL;
5209
5210         /* Refuse to reduce size of the array.  Any reductions in
5211          * array size must be through explicit setting of array_size
5212          * attribute.
5213          */
5214         if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
5215             < mddev->array_sectors) {
5216                 printk(KERN_ERR "md: %s: array size must be reduced "
5217                        "before number of disks\n", mdname(mddev));
5218                 return -EINVAL;
5219         }
5220
5221         atomic_set(&conf->reshape_stripes, 0);
5222         spin_lock_irq(&conf->device_lock);
5223         conf->previous_raid_disks = conf->raid_disks;
5224         conf->raid_disks += mddev->delta_disks;
5225         conf->prev_chunk = conf->chunk_size;
5226         conf->chunk_size = mddev->new_chunk;
5227         conf->prev_algo = conf->algorithm;
5228         conf->algorithm = mddev->new_layout;
5229         if (mddev->delta_disks < 0)
5230                 conf->reshape_progress = raid5_size(mddev, 0, 0);
5231         else
5232                 conf->reshape_progress = 0;
5233         conf->reshape_safe = conf->reshape_progress;
5234         conf->generation++;
5235         spin_unlock_irq(&conf->device_lock);
5236
5237         /* Add some new drives, as many as will fit.
5238          * We know there are enough to make the newly sized array work.
5239          */
5240         list_for_each_entry(rdev, &mddev->disks, same_set)
5241                 if (rdev->raid_disk < 0 &&
5242                     !test_bit(Faulty, &rdev->flags)) {
5243                         if (raid5_add_disk(mddev, rdev) == 0) {
5244                                 char nm[20];
5245                                 set_bit(In_sync, &rdev->flags);
5246                                 added_devices++;
5247                                 rdev->recovery_offset = 0;
5248                                 sprintf(nm, "rd%d", rdev->raid_disk);
5249                                 if (sysfs_create_link(&mddev->kobj,
5250                                                       &rdev->kobj, nm))
5251                                         printk(KERN_WARNING
5252                                                "raid5: failed to create "
5253                                                " link %s for %s\n",
5254                                                nm, mdname(mddev));
5255                         } else
5256                                 break;
5257                 }
5258
5259         if (mddev->delta_disks > 0) {
5260                 spin_lock_irqsave(&conf->device_lock, flags);
5261                 mddev->degraded = (conf->raid_disks - conf->previous_raid_disks)
5262                         - added_devices;
5263                 spin_unlock_irqrestore(&conf->device_lock, flags);
5264         }
5265         mddev->raid_disks = conf->raid_disks;
5266         mddev->reshape_position = 0;
5267         set_bit(MD_CHANGE_DEVS, &mddev->flags);
5268
5269         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
5270         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
5271         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
5272         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
5273         mddev->sync_thread = md_register_thread(md_do_sync, mddev,
5274                                                 "%s_reshape");
5275         if (!mddev->sync_thread) {
5276                 mddev->recovery = 0;
5277                 spin_lock_irq(&conf->device_lock);
5278                 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
5279                 conf->reshape_progress = MaxSector;
5280                 spin_unlock_irq(&conf->device_lock);
5281                 return -EAGAIN;
5282         }
5283         conf->reshape_checkpoint = jiffies;
5284         md_wakeup_thread(mddev->sync_thread);
5285         md_new_event(mddev);
5286         return 0;
5287 }
5288
5289 /* This is called from the reshape thread and should make any
5290  * changes needed in 'conf'
5291  */
5292 static void end_reshape(raid5_conf_t *conf)
5293 {
5294
5295         if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
5296
5297                 spin_lock_irq(&conf->device_lock);
5298                 conf->previous_raid_disks = conf->raid_disks;
5299                 conf->reshape_progress = MaxSector;
5300                 spin_unlock_irq(&conf->device_lock);
5301                 wake_up(&conf->wait_for_overlap);
5302
5303                 /* read-ahead size must cover two whole stripes, which is
5304                  * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
5305                  */
5306                 {
5307                         int data_disks = conf->raid_disks - conf->max_degraded;
5308                         int stripe = data_disks * (conf->chunk_size
5309                                                    / PAGE_SIZE);
5310                         if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
5311                                 conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
5312                 }
5313         }
5314 }
5315
5316 /* This is called from the raid5d thread with mddev_lock held.
5317  * It makes config changes to the device.
5318  */
5319 static void raid5_finish_reshape(mddev_t *mddev)
5320 {
5321         struct block_device *bdev;
5322         raid5_conf_t *conf = mddev_to_conf(mddev);
5323
5324         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
5325
5326                 if (mddev->delta_disks > 0) {
5327                         md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
5328                         set_capacity(mddev->gendisk, mddev->array_sectors);
5329                         mddev->changed = 1;
5330
5331                         bdev = bdget_disk(mddev->gendisk, 0);
5332                         if (bdev) {
5333                                 mutex_lock(&bdev->bd_inode->i_mutex);
5334                                 i_size_write(bdev->bd_inode,
5335                                              (loff_t)mddev->array_sectors << 9);
5336                                 mutex_unlock(&bdev->bd_inode->i_mutex);
5337                                 bdput(bdev);
5338                         }
5339                 } else {
5340                         int d;
5341                         mddev->degraded = conf->raid_disks;
5342                         for (d = 0; d < conf->raid_disks ; d++)
5343                                 if (conf->disks[d].rdev &&
5344                                     test_bit(In_sync,
5345                                              &conf->disks[d].rdev->flags))
5346                                         mddev->degraded--;
5347                         for (d = conf->raid_disks ;
5348                              d < conf->raid_disks - mddev->delta_disks;
5349                              d++)
5350                                 raid5_remove_disk(mddev, d);
5351                 }
5352                 mddev->layout = conf->algorithm;
5353                 mddev->chunk_size = conf->chunk_size;
5354                 mddev->reshape_position = MaxSector;
5355                 mddev->delta_disks = 0;
5356         }
5357 }
5358
5359 static void raid5_quiesce(mddev_t *mddev, int state)
5360 {
5361         raid5_conf_t *conf = mddev_to_conf(mddev);
5362
5363         switch(state) {
5364         case 2: /* resume for a suspend */
5365                 wake_up(&conf->wait_for_overlap);
5366                 break;
5367
5368         case 1: /* stop all writes */
5369                 spin_lock_irq(&conf->device_lock);
5370                 conf->quiesce = 1;
5371                 wait_event_lock_irq(conf->wait_for_stripe,
5372                                     atomic_read(&conf->active_stripes) == 0 &&
5373                                     atomic_read(&conf->active_aligned_reads) == 0,
5374                                     conf->device_lock, /* nothing */);
5375                 spin_unlock_irq(&conf->device_lock);
5376                 break;
5377
5378         case 0: /* re-enable writes */
5379                 spin_lock_irq(&conf->device_lock);
5380                 conf->quiesce = 0;
5381                 wake_up(&conf->wait_for_stripe);
5382                 wake_up(&conf->wait_for_overlap);
5383                 spin_unlock_irq(&conf->device_lock);
5384                 break;
5385         }
5386 }
5387
5388
5389 static void *raid5_takeover_raid1(mddev_t *mddev)
5390 {
5391         int chunksect;
5392
5393         if (mddev->raid_disks != 2 ||
5394             mddev->degraded > 1)
5395                 return ERR_PTR(-EINVAL);
5396
5397         /* Should check if there are write-behind devices? */
5398
5399         chunksect = 64*2; /* 64K by default */
5400
5401         /* The array must be an exact multiple of chunksize */
5402         while (chunksect && (mddev->array_sectors & (chunksect-1)))
5403                 chunksect >>= 1;
5404
5405         if ((chunksect<<9) < STRIPE_SIZE)
5406                 /* array size does not allow a suitable chunk size */
5407                 return ERR_PTR(-EINVAL);
5408
5409         mddev->new_level = 5;
5410         mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
5411         mddev->new_chunk = chunksect << 9;
5412
5413         return setup_conf(mddev);
5414 }
5415
5416 static void *raid5_takeover_raid6(mddev_t *mddev)
5417 {
5418         int new_layout;
5419
5420         switch (mddev->layout) {
5421         case ALGORITHM_LEFT_ASYMMETRIC_6:
5422                 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
5423                 break;
5424         case ALGORITHM_RIGHT_ASYMMETRIC_6:
5425                 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
5426                 break;
5427         case ALGORITHM_LEFT_SYMMETRIC_6:
5428                 new_layout = ALGORITHM_LEFT_SYMMETRIC;
5429                 break;
5430         case ALGORITHM_RIGHT_SYMMETRIC_6:
5431                 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
5432                 break;
5433         case ALGORITHM_PARITY_0_6:
5434                 new_layout = ALGORITHM_PARITY_0;
5435                 break;
5436         case ALGORITHM_PARITY_N:
5437                 new_layout = ALGORITHM_PARITY_N;
5438                 break;
5439         default:
5440                 return ERR_PTR(-EINVAL);
5441         }
5442         mddev->new_level = 5;
5443         mddev->new_layout = new_layout;
5444         mddev->delta_disks = -1;
5445         mddev->raid_disks -= 1;
5446         return setup_conf(mddev);
5447 }
5448
5449
5450 static int raid5_reconfig(mddev_t *mddev, int new_layout, int new_chunk)
5451 {
5452         /* For a 2-drive array, the layout and chunk size can be changed
5453          * immediately as not restriping is needed.
5454          * For larger arrays we record the new value - after validation
5455          * to be used by a reshape pass.
5456          */
5457         raid5_conf_t *conf = mddev_to_conf(mddev);
5458
5459         if (new_layout >= 0 && !algorithm_valid_raid5(new_layout))
5460                 return -EINVAL;
5461         if (new_chunk > 0) {
5462                 if (new_chunk & (new_chunk-1))
5463                         /* not a power of 2 */
5464                         return -EINVAL;
5465                 if (new_chunk < PAGE_SIZE)
5466                         return -EINVAL;
5467                 if (mddev->array_sectors & ((new_chunk>>9)-1))
5468                         /* not factor of array size */
5469                         return -EINVAL;
5470         }
5471
5472         /* They look valid */
5473
5474         if (mddev->raid_disks == 2) {
5475
5476                 if (new_layout >= 0) {
5477                         conf->algorithm = new_layout;
5478                         mddev->layout = mddev->new_layout = new_layout;
5479                 }
5480                 if (new_chunk > 0) {
5481                         conf->chunk_size = new_chunk;
5482                         mddev->chunk_size = mddev->new_chunk = new_chunk;
5483                 }
5484                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5485                 md_wakeup_thread(mddev->thread);
5486         } else {
5487                 if (new_layout >= 0)
5488                         mddev->new_layout = new_layout;
5489                 if (new_chunk > 0)
5490                         mddev->new_chunk = new_chunk;
5491         }
5492         return 0;
5493 }
5494
5495 static int raid6_reconfig(mddev_t *mddev, int new_layout, int new_chunk)
5496 {
5497         if (new_layout >= 0 && !algorithm_valid_raid6(new_layout))
5498                 return -EINVAL;
5499         if (new_chunk > 0) {
5500                 if (new_chunk & (new_chunk-1))
5501                         /* not a power of 2 */
5502                         return -EINVAL;
5503                 if (new_chunk < PAGE_SIZE)
5504                         return -EINVAL;
5505                 if (mddev->array_sectors & ((new_chunk>>9)-1))
5506                         /* not factor of array size */
5507                         return -EINVAL;
5508         }
5509
5510         /* They look valid */
5511
5512         if (new_layout >= 0)
5513                 mddev->new_layout = new_layout;
5514         if (new_chunk > 0)
5515                 mddev->new_chunk = new_chunk;
5516
5517         return 0;
5518 }
5519
5520 static void *raid5_takeover(mddev_t *mddev)
5521 {
5522         /* raid5 can take over:
5523          *  raid0 - if all devices are the same - make it a raid4 layout
5524          *  raid1 - if there are two drives.  We need to know the chunk size
5525          *  raid4 - trivial - just use a raid4 layout.
5526          *  raid6 - Providing it is a *_6 layout
5527          *
5528          * For now, just do raid1
5529          */
5530
5531         if (mddev->level == 1)
5532                 return raid5_takeover_raid1(mddev);
5533         if (mddev->level == 4) {
5534                 mddev->new_layout = ALGORITHM_PARITY_N;
5535                 mddev->new_level = 5;
5536                 return setup_conf(mddev);
5537         }
5538         if (mddev->level == 6)
5539                 return raid5_takeover_raid6(mddev);
5540
5541         return ERR_PTR(-EINVAL);
5542 }
5543
5544
5545 static struct mdk_personality raid5_personality;
5546
5547 static void *raid6_takeover(mddev_t *mddev)
5548 {
5549         /* Currently can only take over a raid5.  We map the
5550          * personality to an equivalent raid6 personality
5551          * with the Q block at the end.
5552          */
5553         int new_layout;
5554
5555         if (mddev->pers != &raid5_personality)
5556                 return ERR_PTR(-EINVAL);
5557         if (mddev->degraded > 1)
5558                 return ERR_PTR(-EINVAL);
5559         if (mddev->raid_disks > 253)
5560                 return ERR_PTR(-EINVAL);
5561         if (mddev->raid_disks < 3)
5562                 return ERR_PTR(-EINVAL);
5563
5564         switch (mddev->layout) {
5565         case ALGORITHM_LEFT_ASYMMETRIC:
5566                 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
5567                 break;
5568         case ALGORITHM_RIGHT_ASYMMETRIC:
5569                 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
5570                 break;
5571         case ALGORITHM_LEFT_SYMMETRIC:
5572                 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
5573                 break;
5574         case ALGORITHM_RIGHT_SYMMETRIC:
5575                 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
5576                 break;
5577         case ALGORITHM_PARITY_0:
5578                 new_layout = ALGORITHM_PARITY_0_6;
5579                 break;
5580         case ALGORITHM_PARITY_N:
5581                 new_layout = ALGORITHM_PARITY_N;
5582                 break;
5583         default:
5584                 return ERR_PTR(-EINVAL);
5585         }
5586         mddev->new_level = 6;
5587         mddev->new_layout = new_layout;
5588         mddev->delta_disks = 1;
5589         mddev->raid_disks += 1;
5590         return setup_conf(mddev);
5591 }
5592
5593
5594 static struct mdk_personality raid6_personality =
5595 {
5596         .name           = "raid6",
5597         .level          = 6,
5598         .owner          = THIS_MODULE,
5599         .make_request   = make_request,
5600         .run            = run,
5601         .stop           = stop,
5602         .status         = status,
5603         .error_handler  = error,
5604         .hot_add_disk   = raid5_add_disk,
5605         .hot_remove_disk= raid5_remove_disk,
5606         .spare_active   = raid5_spare_active,
5607         .sync_request   = sync_request,
5608         .resize         = raid5_resize,
5609         .size           = raid5_size,
5610         .check_reshape  = raid5_check_reshape,
5611         .start_reshape  = raid5_start_reshape,
5612         .finish_reshape = raid5_finish_reshape,
5613         .quiesce        = raid5_quiesce,
5614         .takeover       = raid6_takeover,
5615         .reconfig       = raid6_reconfig,
5616 };
5617 static struct mdk_personality raid5_personality =
5618 {
5619         .name           = "raid5",
5620         .level          = 5,
5621         .owner          = THIS_MODULE,
5622         .make_request   = make_request,
5623         .run            = run,
5624         .stop           = stop,
5625         .status         = status,
5626         .error_handler  = error,
5627         .hot_add_disk   = raid5_add_disk,
5628         .hot_remove_disk= raid5_remove_disk,
5629         .spare_active   = raid5_spare_active,
5630         .sync_request   = sync_request,
5631         .resize         = raid5_resize,
5632         .size           = raid5_size,
5633         .check_reshape  = raid5_check_reshape,
5634         .start_reshape  = raid5_start_reshape,
5635         .finish_reshape = raid5_finish_reshape,
5636         .quiesce        = raid5_quiesce,
5637         .takeover       = raid5_takeover,
5638         .reconfig       = raid5_reconfig,
5639 };
5640
5641 static struct mdk_personality raid4_personality =
5642 {
5643         .name           = "raid4",
5644         .level          = 4,
5645         .owner          = THIS_MODULE,
5646         .make_request   = make_request,
5647         .run            = run,
5648         .stop           = stop,
5649         .status         = status,
5650         .error_handler  = error,
5651         .hot_add_disk   = raid5_add_disk,
5652         .hot_remove_disk= raid5_remove_disk,
5653         .spare_active   = raid5_spare_active,
5654         .sync_request   = sync_request,
5655         .resize         = raid5_resize,
5656         .size           = raid5_size,
5657         .check_reshape  = raid5_check_reshape,
5658         .start_reshape  = raid5_start_reshape,
5659         .finish_reshape = raid5_finish_reshape,
5660         .quiesce        = raid5_quiesce,
5661 };
5662
5663 static int __init raid5_init(void)
5664 {
5665         register_md_personality(&raid6_personality);
5666         register_md_personality(&raid5_personality);
5667         register_md_personality(&raid4_personality);
5668         return 0;
5669 }
5670
5671 static void raid5_exit(void)
5672 {
5673         unregister_md_personality(&raid6_personality);
5674         unregister_md_personality(&raid5_personality);
5675         unregister_md_personality(&raid4_personality);
5676 }
5677
5678 module_init(raid5_init);
5679 module_exit(raid5_exit);
5680 MODULE_LICENSE("GPL");
5681 MODULE_ALIAS("md-personality-4"); /* RAID5 */
5682 MODULE_ALIAS("md-raid5");
5683 MODULE_ALIAS("md-raid4");
5684 MODULE_ALIAS("md-level-5");
5685 MODULE_ALIAS("md-level-4");
5686 MODULE_ALIAS("md-personality-8"); /* RAID6 */
5687 MODULE_ALIAS("md-raid6");
5688 MODULE_ALIAS("md-level-6");
5689
5690 /* This used to be two separate modules, they were: */
5691 MODULE_ALIAS("raid5");
5692 MODULE_ALIAS("raid6");