]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/md/raid5.c
md: raid5: fix clearing of biofill operations
[karo-tx-linux.git] / drivers / md / raid5.c
1 /*
2  * raid5.c : Multiple Devices driver for Linux
3  *         Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
4  *         Copyright (C) 1999, 2000 Ingo Molnar
5  *         Copyright (C) 2002, 2003 H. Peter Anvin
6  *
7  * RAID-4/5/6 management functions.
8  * Thanks to Penguin Computing for making the RAID-6 development possible
9  * by donating a test server!
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2, or (at your option)
14  * any later version.
15  *
16  * You should have received a copy of the GNU General Public License
17  * (for example /usr/src/linux/COPYING); if not, write to the Free
18  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 /*
22  * BITMAP UNPLUGGING:
23  *
24  * The sequencing for updating the bitmap reliably is a little
25  * subtle (and I got it wrong the first time) so it deserves some
26  * explanation.
27  *
28  * We group bitmap updates into batches.  Each batch has a number.
29  * We may write out several batches at once, but that isn't very important.
30  * conf->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/module.h>
47 #include <linux/slab.h>
48 #include <linux/highmem.h>
49 #include <linux/bitops.h>
50 #include <linux/kthread.h>
51 #include <asm/atomic.h>
52 #include "raid6.h"
53
54 #include <linux/raid/bitmap.h>
55 #include <linux/async_tx.h>
56
57 /*
58  * Stripe cache
59  */
60
61 #define NR_STRIPES              256
62 #define STRIPE_SIZE             PAGE_SIZE
63 #define STRIPE_SHIFT            (PAGE_SHIFT - 9)
64 #define STRIPE_SECTORS          (STRIPE_SIZE>>9)
65 #define IO_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 #if !RAID6_USE_EMPTY_ZERO_PAGE
97 /* In .bss so it's zeroed */
98 const char raid6_empty_zero_page[PAGE_SIZE] __attribute__((aligned(256)));
99 #endif
100
101 static inline int raid6_next_disk(int disk, int raid_disks)
102 {
103         disk++;
104         return (disk < raid_disks) ? disk : 0;
105 }
106
107 static void return_io(struct bio *return_bi)
108 {
109         struct bio *bi = return_bi;
110         while (bi) {
111                 int bytes = bi->bi_size;
112
113                 return_bi = bi->bi_next;
114                 bi->bi_next = NULL;
115                 bi->bi_size = 0;
116                 bi->bi_end_io(bi, bytes,
117                               test_bit(BIO_UPTODATE, &bi->bi_flags)
118                                 ? 0 : -EIO);
119                 bi = return_bi;
120         }
121 }
122
123 static void print_raid5_conf (raid5_conf_t *conf);
124
125 static void __release_stripe(raid5_conf_t *conf, struct stripe_head *sh)
126 {
127         if (atomic_dec_and_test(&sh->count)) {
128                 BUG_ON(!list_empty(&sh->lru));
129                 BUG_ON(atomic_read(&conf->active_stripes)==0);
130                 if (test_bit(STRIPE_HANDLE, &sh->state)) {
131                         if (test_bit(STRIPE_DELAYED, &sh->state)) {
132                                 list_add_tail(&sh->lru, &conf->delayed_list);
133                                 blk_plug_device(conf->mddev->queue);
134                         } else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
135                                    sh->bm_seq - conf->seq_write > 0) {
136                                 list_add_tail(&sh->lru, &conf->bitmap_list);
137                                 blk_plug_device(conf->mddev->queue);
138                         } else {
139                                 clear_bit(STRIPE_BIT_DELAY, &sh->state);
140                                 list_add_tail(&sh->lru, &conf->handle_list);
141                         }
142                         md_wakeup_thread(conf->mddev->thread);
143                 } else {
144                         BUG_ON(sh->ops.pending);
145                         if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
146                                 atomic_dec(&conf->preread_active_stripes);
147                                 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD)
148                                         md_wakeup_thread(conf->mddev->thread);
149                         }
150                         atomic_dec(&conf->active_stripes);
151                         if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
152                                 list_add_tail(&sh->lru, &conf->inactive_list);
153                                 wake_up(&conf->wait_for_stripe);
154                                 if (conf->retry_read_aligned)
155                                         md_wakeup_thread(conf->mddev->thread);
156                         }
157                 }
158         }
159 }
160 static void release_stripe(struct stripe_head *sh)
161 {
162         raid5_conf_t *conf = sh->raid_conf;
163         unsigned long flags;
164
165         spin_lock_irqsave(&conf->device_lock, flags);
166         __release_stripe(conf, sh);
167         spin_unlock_irqrestore(&conf->device_lock, flags);
168 }
169
170 static inline void remove_hash(struct stripe_head *sh)
171 {
172         pr_debug("remove_hash(), stripe %llu\n",
173                 (unsigned long long)sh->sector);
174
175         hlist_del_init(&sh->hash);
176 }
177
178 static inline void insert_hash(raid5_conf_t *conf, struct stripe_head *sh)
179 {
180         struct hlist_head *hp = stripe_hash(conf, sh->sector);
181
182         pr_debug("insert_hash(), stripe %llu\n",
183                 (unsigned long long)sh->sector);
184
185         CHECK_DEVLOCK();
186         hlist_add_head(&sh->hash, hp);
187 }
188
189
190 /* find an idle stripe, make sure it is unhashed, and return it. */
191 static struct stripe_head *get_free_stripe(raid5_conf_t *conf)
192 {
193         struct stripe_head *sh = NULL;
194         struct list_head *first;
195
196         CHECK_DEVLOCK();
197         if (list_empty(&conf->inactive_list))
198                 goto out;
199         first = conf->inactive_list.next;
200         sh = list_entry(first, struct stripe_head, lru);
201         list_del_init(first);
202         remove_hash(sh);
203         atomic_inc(&conf->active_stripes);
204 out:
205         return sh;
206 }
207
208 static void shrink_buffers(struct stripe_head *sh, int num)
209 {
210         struct page *p;
211         int i;
212
213         for (i=0; i<num ; i++) {
214                 p = sh->dev[i].page;
215                 if (!p)
216                         continue;
217                 sh->dev[i].page = NULL;
218                 put_page(p);
219         }
220 }
221
222 static int grow_buffers(struct stripe_head *sh, int num)
223 {
224         int i;
225
226         for (i=0; i<num; i++) {
227                 struct page *page;
228
229                 if (!(page = alloc_page(GFP_KERNEL))) {
230                         return 1;
231                 }
232                 sh->dev[i].page = page;
233         }
234         return 0;
235 }
236
237 static void raid5_build_block (struct stripe_head *sh, int i);
238
239 static void init_stripe(struct stripe_head *sh, sector_t sector, int pd_idx, int disks)
240 {
241         raid5_conf_t *conf = sh->raid_conf;
242         int i;
243
244         BUG_ON(atomic_read(&sh->count) != 0);
245         BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
246         BUG_ON(sh->ops.pending || sh->ops.ack || sh->ops.complete);
247
248         CHECK_DEVLOCK();
249         pr_debug("init_stripe called, stripe %llu\n",
250                 (unsigned long long)sh->sector);
251
252         remove_hash(sh);
253
254         sh->sector = sector;
255         sh->pd_idx = pd_idx;
256         sh->state = 0;
257
258         sh->disks = disks;
259
260         for (i = sh->disks; i--; ) {
261                 struct r5dev *dev = &sh->dev[i];
262
263                 if (dev->toread || dev->read || dev->towrite || dev->written ||
264                     test_bit(R5_LOCKED, &dev->flags)) {
265                         printk(KERN_ERR "sector=%llx i=%d %p %p %p %p %d\n",
266                                (unsigned long long)sh->sector, i, dev->toread,
267                                dev->read, dev->towrite, dev->written,
268                                test_bit(R5_LOCKED, &dev->flags));
269                         BUG();
270                 }
271                 dev->flags = 0;
272                 raid5_build_block(sh, i);
273         }
274         insert_hash(conf, sh);
275 }
276
277 static struct stripe_head *__find_stripe(raid5_conf_t *conf, sector_t sector, int disks)
278 {
279         struct stripe_head *sh;
280         struct hlist_node *hn;
281
282         CHECK_DEVLOCK();
283         pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
284         hlist_for_each_entry(sh, hn, stripe_hash(conf, sector), hash)
285                 if (sh->sector == sector && sh->disks == disks)
286                         return sh;
287         pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
288         return NULL;
289 }
290
291 static void unplug_slaves(mddev_t *mddev);
292 static void raid5_unplug_device(struct request_queue *q);
293
294 static struct stripe_head *get_active_stripe(raid5_conf_t *conf, sector_t sector, int disks,
295                                              int pd_idx, int noblock)
296 {
297         struct stripe_head *sh;
298
299         pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
300
301         spin_lock_irq(&conf->device_lock);
302
303         do {
304                 wait_event_lock_irq(conf->wait_for_stripe,
305                                     conf->quiesce == 0,
306                                     conf->device_lock, /* nothing */);
307                 sh = __find_stripe(conf, sector, disks);
308                 if (!sh) {
309                         if (!conf->inactive_blocked)
310                                 sh = get_free_stripe(conf);
311                         if (noblock && sh == NULL)
312                                 break;
313                         if (!sh) {
314                                 conf->inactive_blocked = 1;
315                                 wait_event_lock_irq(conf->wait_for_stripe,
316                                                     !list_empty(&conf->inactive_list) &&
317                                                     (atomic_read(&conf->active_stripes)
318                                                      < (conf->max_nr_stripes *3/4)
319                                                      || !conf->inactive_blocked),
320                                                     conf->device_lock,
321                                                     raid5_unplug_device(conf->mddev->queue)
322                                         );
323                                 conf->inactive_blocked = 0;
324                         } else
325                                 init_stripe(sh, sector, pd_idx, disks);
326                 } else {
327                         if (atomic_read(&sh->count)) {
328                           BUG_ON(!list_empty(&sh->lru));
329                         } else {
330                                 if (!test_bit(STRIPE_HANDLE, &sh->state))
331                                         atomic_inc(&conf->active_stripes);
332                                 if (list_empty(&sh->lru) &&
333                                     !test_bit(STRIPE_EXPANDING, &sh->state))
334                                         BUG();
335                                 list_del_init(&sh->lru);
336                         }
337                 }
338         } while (sh == NULL);
339
340         if (sh)
341                 atomic_inc(&sh->count);
342
343         spin_unlock_irq(&conf->device_lock);
344         return sh;
345 }
346
347 /* test_and_ack_op() ensures that we only dequeue an operation once */
348 #define test_and_ack_op(op, pend) \
349 do {                                                    \
350         if (test_bit(op, &sh->ops.pending) &&           \
351                 !test_bit(op, &sh->ops.complete)) {     \
352                 if (test_and_set_bit(op, &sh->ops.ack)) \
353                         clear_bit(op, &pend);           \
354                 else                                    \
355                         ack++;                          \
356         } else                                          \
357                 clear_bit(op, &pend);                   \
358 } while (0)
359
360 /* find new work to run, do not resubmit work that is already
361  * in flight
362  */
363 static unsigned long get_stripe_work(struct stripe_head *sh)
364 {
365         unsigned long pending;
366         int ack = 0;
367
368         pending = sh->ops.pending;
369
370         test_and_ack_op(STRIPE_OP_BIOFILL, pending);
371         test_and_ack_op(STRIPE_OP_COMPUTE_BLK, pending);
372         test_and_ack_op(STRIPE_OP_PREXOR, pending);
373         test_and_ack_op(STRIPE_OP_BIODRAIN, pending);
374         test_and_ack_op(STRIPE_OP_POSTXOR, pending);
375         test_and_ack_op(STRIPE_OP_CHECK, pending);
376         if (test_and_clear_bit(STRIPE_OP_IO, &sh->ops.pending))
377                 ack++;
378
379         sh->ops.count -= ack;
380         if (unlikely(sh->ops.count < 0)) {
381                 printk(KERN_ERR "pending: %#lx ops.pending: %#lx ops.ack: %#lx "
382                         "ops.complete: %#lx\n", pending, sh->ops.pending,
383                         sh->ops.ack, sh->ops.complete);
384                 BUG();
385         }
386
387         return pending;
388 }
389
390 static int
391 raid5_end_read_request(struct bio *bi, unsigned int bytes_done, int error);
392 static int
393 raid5_end_write_request (struct bio *bi, unsigned int bytes_done, int error);
394
395 static void ops_run_io(struct stripe_head *sh)
396 {
397         raid5_conf_t *conf = sh->raid_conf;
398         int i, disks = sh->disks;
399
400         might_sleep();
401
402         for (i = disks; i--; ) {
403                 int rw;
404                 struct bio *bi;
405                 mdk_rdev_t *rdev;
406                 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags))
407                         rw = WRITE;
408                 else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
409                         rw = READ;
410                 else
411                         continue;
412
413                 bi = &sh->dev[i].req;
414
415                 bi->bi_rw = rw;
416                 if (rw == WRITE)
417                         bi->bi_end_io = raid5_end_write_request;
418                 else
419                         bi->bi_end_io = raid5_end_read_request;
420
421                 rcu_read_lock();
422                 rdev = rcu_dereference(conf->disks[i].rdev);
423                 if (rdev && test_bit(Faulty, &rdev->flags))
424                         rdev = NULL;
425                 if (rdev)
426                         atomic_inc(&rdev->nr_pending);
427                 rcu_read_unlock();
428
429                 if (rdev) {
430                         if (test_bit(STRIPE_SYNCING, &sh->state) ||
431                                 test_bit(STRIPE_EXPAND_SOURCE, &sh->state) ||
432                                 test_bit(STRIPE_EXPAND_READY, &sh->state))
433                                 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
434
435                         bi->bi_bdev = rdev->bdev;
436                         pr_debug("%s: for %llu schedule op %ld on disc %d\n",
437                                 __FUNCTION__, (unsigned long long)sh->sector,
438                                 bi->bi_rw, i);
439                         atomic_inc(&sh->count);
440                         bi->bi_sector = sh->sector + rdev->data_offset;
441                         bi->bi_flags = 1 << BIO_UPTODATE;
442                         bi->bi_vcnt = 1;
443                         bi->bi_max_vecs = 1;
444                         bi->bi_idx = 0;
445                         bi->bi_io_vec = &sh->dev[i].vec;
446                         bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
447                         bi->bi_io_vec[0].bv_offset = 0;
448                         bi->bi_size = STRIPE_SIZE;
449                         bi->bi_next = NULL;
450                         if (rw == WRITE &&
451                             test_bit(R5_ReWrite, &sh->dev[i].flags))
452                                 atomic_add(STRIPE_SECTORS,
453                                         &rdev->corrected_errors);
454                         generic_make_request(bi);
455                 } else {
456                         if (rw == WRITE)
457                                 set_bit(STRIPE_DEGRADED, &sh->state);
458                         pr_debug("skip op %ld on disc %d for sector %llu\n",
459                                 bi->bi_rw, i, (unsigned long long)sh->sector);
460                         clear_bit(R5_LOCKED, &sh->dev[i].flags);
461                         set_bit(STRIPE_HANDLE, &sh->state);
462                 }
463         }
464 }
465
466 static struct dma_async_tx_descriptor *
467 async_copy_data(int frombio, struct bio *bio, struct page *page,
468         sector_t sector, struct dma_async_tx_descriptor *tx)
469 {
470         struct bio_vec *bvl;
471         struct page *bio_page;
472         int i;
473         int page_offset;
474
475         if (bio->bi_sector >= sector)
476                 page_offset = (signed)(bio->bi_sector - sector) * 512;
477         else
478                 page_offset = (signed)(sector - bio->bi_sector) * -512;
479         bio_for_each_segment(bvl, bio, i) {
480                 int len = bio_iovec_idx(bio, i)->bv_len;
481                 int clen;
482                 int b_offset = 0;
483
484                 if (page_offset < 0) {
485                         b_offset = -page_offset;
486                         page_offset += b_offset;
487                         len -= b_offset;
488                 }
489
490                 if (len > 0 && page_offset + len > STRIPE_SIZE)
491                         clen = STRIPE_SIZE - page_offset;
492                 else
493                         clen = len;
494
495                 if (clen > 0) {
496                         b_offset += bio_iovec_idx(bio, i)->bv_offset;
497                         bio_page = bio_iovec_idx(bio, i)->bv_page;
498                         if (frombio)
499                                 tx = async_memcpy(page, bio_page, page_offset,
500                                         b_offset, clen,
501                                         ASYNC_TX_DEP_ACK,
502                                         tx, NULL, NULL);
503                         else
504                                 tx = async_memcpy(bio_page, page, b_offset,
505                                         page_offset, clen,
506                                         ASYNC_TX_DEP_ACK,
507                                         tx, NULL, NULL);
508                 }
509                 if (clen < len) /* hit end of page */
510                         break;
511                 page_offset +=  len;
512         }
513
514         return tx;
515 }
516
517 static void ops_complete_biofill(void *stripe_head_ref)
518 {
519         struct stripe_head *sh = stripe_head_ref;
520         struct bio *return_bi = NULL;
521         raid5_conf_t *conf = sh->raid_conf;
522         int i;
523
524         pr_debug("%s: stripe %llu\n", __FUNCTION__,
525                 (unsigned long long)sh->sector);
526
527         /* clear completed biofills */
528         for (i = sh->disks; i--; ) {
529                 struct r5dev *dev = &sh->dev[i];
530
531                 /* acknowledge completion of a biofill operation */
532                 /* and check if we need to reply to a read request,
533                  * new R5_Wantfill requests are held off until
534                  * !test_bit(STRIPE_OP_BIOFILL, &sh->ops.pending)
535                  */
536                 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
537                         struct bio *rbi, *rbi2;
538
539                         /* The access to dev->read is outside of the
540                          * spin_lock_irq(&conf->device_lock), but is protected
541                          * by the STRIPE_OP_BIOFILL pending bit
542                          */
543                         BUG_ON(!dev->read);
544                         rbi = dev->read;
545                         dev->read = NULL;
546                         while (rbi && rbi->bi_sector <
547                                 dev->sector + STRIPE_SECTORS) {
548                                 rbi2 = r5_next_bio(rbi, dev->sector);
549                                 spin_lock_irq(&conf->device_lock);
550                                 if (--rbi->bi_phys_segments == 0) {
551                                         rbi->bi_next = return_bi;
552                                         return_bi = rbi;
553                                 }
554                                 spin_unlock_irq(&conf->device_lock);
555                                 rbi = rbi2;
556                         }
557                 }
558         }
559         set_bit(STRIPE_OP_BIOFILL, &sh->ops.complete);
560
561         return_io(return_bi);
562
563         set_bit(STRIPE_HANDLE, &sh->state);
564         release_stripe(sh);
565 }
566
567 static void ops_run_biofill(struct stripe_head *sh)
568 {
569         struct dma_async_tx_descriptor *tx = NULL;
570         raid5_conf_t *conf = sh->raid_conf;
571         int i;
572
573         pr_debug("%s: stripe %llu\n", __FUNCTION__,
574                 (unsigned long long)sh->sector);
575
576         for (i = sh->disks; i--; ) {
577                 struct r5dev *dev = &sh->dev[i];
578                 if (test_bit(R5_Wantfill, &dev->flags)) {
579                         struct bio *rbi;
580                         spin_lock_irq(&conf->device_lock);
581                         dev->read = rbi = dev->toread;
582                         dev->toread = NULL;
583                         spin_unlock_irq(&conf->device_lock);
584                         while (rbi && rbi->bi_sector <
585                                 dev->sector + STRIPE_SECTORS) {
586                                 tx = async_copy_data(0, rbi, dev->page,
587                                         dev->sector, tx);
588                                 rbi = r5_next_bio(rbi, dev->sector);
589                         }
590                 }
591         }
592
593         atomic_inc(&sh->count);
594         async_trigger_callback(ASYNC_TX_DEP_ACK | ASYNC_TX_ACK, tx,
595                 ops_complete_biofill, sh);
596 }
597
598 static void ops_complete_compute5(void *stripe_head_ref)
599 {
600         struct stripe_head *sh = stripe_head_ref;
601         int target = sh->ops.target;
602         struct r5dev *tgt = &sh->dev[target];
603
604         pr_debug("%s: stripe %llu\n", __FUNCTION__,
605                 (unsigned long long)sh->sector);
606
607         set_bit(R5_UPTODATE, &tgt->flags);
608         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
609         clear_bit(R5_Wantcompute, &tgt->flags);
610         set_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.complete);
611         set_bit(STRIPE_HANDLE, &sh->state);
612         release_stripe(sh);
613 }
614
615 static struct dma_async_tx_descriptor *
616 ops_run_compute5(struct stripe_head *sh, unsigned long pending)
617 {
618         /* kernel stack size limits the total number of disks */
619         int disks = sh->disks;
620         struct page *xor_srcs[disks];
621         int target = sh->ops.target;
622         struct r5dev *tgt = &sh->dev[target];
623         struct page *xor_dest = tgt->page;
624         int count = 0;
625         struct dma_async_tx_descriptor *tx;
626         int i;
627
628         pr_debug("%s: stripe %llu block: %d\n",
629                 __FUNCTION__, (unsigned long long)sh->sector, target);
630         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
631
632         for (i = disks; i--; )
633                 if (i != target)
634                         xor_srcs[count++] = sh->dev[i].page;
635
636         atomic_inc(&sh->count);
637
638         if (unlikely(count == 1))
639                 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE,
640                         0, NULL, ops_complete_compute5, sh);
641         else
642                 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
643                         ASYNC_TX_XOR_ZERO_DST, NULL,
644                         ops_complete_compute5, sh);
645
646         /* ack now if postxor is not set to be run */
647         if (tx && !test_bit(STRIPE_OP_POSTXOR, &pending))
648                 async_tx_ack(tx);
649
650         return tx;
651 }
652
653 static void ops_complete_prexor(void *stripe_head_ref)
654 {
655         struct stripe_head *sh = stripe_head_ref;
656
657         pr_debug("%s: stripe %llu\n", __FUNCTION__,
658                 (unsigned long long)sh->sector);
659
660         set_bit(STRIPE_OP_PREXOR, &sh->ops.complete);
661 }
662
663 static struct dma_async_tx_descriptor *
664 ops_run_prexor(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
665 {
666         /* kernel stack size limits the total number of disks */
667         int disks = sh->disks;
668         struct page *xor_srcs[disks];
669         int count = 0, pd_idx = sh->pd_idx, i;
670
671         /* existing parity data subtracted */
672         struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
673
674         pr_debug("%s: stripe %llu\n", __FUNCTION__,
675                 (unsigned long long)sh->sector);
676
677         for (i = disks; i--; ) {
678                 struct r5dev *dev = &sh->dev[i];
679                 /* Only process blocks that are known to be uptodate */
680                 if (dev->towrite && test_bit(R5_Wantprexor, &dev->flags))
681                         xor_srcs[count++] = dev->page;
682         }
683
684         tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
685                 ASYNC_TX_DEP_ACK | ASYNC_TX_XOR_DROP_DST, tx,
686                 ops_complete_prexor, sh);
687
688         return tx;
689 }
690
691 static struct dma_async_tx_descriptor *
692 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
693 {
694         int disks = sh->disks;
695         int pd_idx = sh->pd_idx, i;
696
697         /* check if prexor is active which means only process blocks
698          * that are part of a read-modify-write (Wantprexor)
699          */
700         int prexor = test_bit(STRIPE_OP_PREXOR, &sh->ops.pending);
701
702         pr_debug("%s: stripe %llu\n", __FUNCTION__,
703                 (unsigned long long)sh->sector);
704
705         for (i = disks; i--; ) {
706                 struct r5dev *dev = &sh->dev[i];
707                 struct bio *chosen;
708                 int towrite;
709
710                 towrite = 0;
711                 if (prexor) { /* rmw */
712                         if (dev->towrite &&
713                             test_bit(R5_Wantprexor, &dev->flags))
714                                 towrite = 1;
715                 } else { /* rcw */
716                         if (i != pd_idx && dev->towrite &&
717                                 test_bit(R5_LOCKED, &dev->flags))
718                                 towrite = 1;
719                 }
720
721                 if (towrite) {
722                         struct bio *wbi;
723
724                         spin_lock(&sh->lock);
725                         chosen = dev->towrite;
726                         dev->towrite = NULL;
727                         BUG_ON(dev->written);
728                         wbi = dev->written = chosen;
729                         spin_unlock(&sh->lock);
730
731                         while (wbi && wbi->bi_sector <
732                                 dev->sector + STRIPE_SECTORS) {
733                                 tx = async_copy_data(1, wbi, dev->page,
734                                         dev->sector, tx);
735                                 wbi = r5_next_bio(wbi, dev->sector);
736                         }
737                 }
738         }
739
740         return tx;
741 }
742
743 static void ops_complete_postxor(void *stripe_head_ref)
744 {
745         struct stripe_head *sh = stripe_head_ref;
746
747         pr_debug("%s: stripe %llu\n", __FUNCTION__,
748                 (unsigned long long)sh->sector);
749
750         set_bit(STRIPE_OP_POSTXOR, &sh->ops.complete);
751         set_bit(STRIPE_HANDLE, &sh->state);
752         release_stripe(sh);
753 }
754
755 static void ops_complete_write(void *stripe_head_ref)
756 {
757         struct stripe_head *sh = stripe_head_ref;
758         int disks = sh->disks, i, pd_idx = sh->pd_idx;
759
760         pr_debug("%s: stripe %llu\n", __FUNCTION__,
761                 (unsigned long long)sh->sector);
762
763         for (i = disks; i--; ) {
764                 struct r5dev *dev = &sh->dev[i];
765                 if (dev->written || i == pd_idx)
766                         set_bit(R5_UPTODATE, &dev->flags);
767         }
768
769         set_bit(STRIPE_OP_BIODRAIN, &sh->ops.complete);
770         set_bit(STRIPE_OP_POSTXOR, &sh->ops.complete);
771
772         set_bit(STRIPE_HANDLE, &sh->state);
773         release_stripe(sh);
774 }
775
776 static void
777 ops_run_postxor(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
778 {
779         /* kernel stack size limits the total number of disks */
780         int disks = sh->disks;
781         struct page *xor_srcs[disks];
782
783         int count = 0, pd_idx = sh->pd_idx, i;
784         struct page *xor_dest;
785         int prexor = test_bit(STRIPE_OP_PREXOR, &sh->ops.pending);
786         unsigned long flags;
787         dma_async_tx_callback callback;
788
789         pr_debug("%s: stripe %llu\n", __FUNCTION__,
790                 (unsigned long long)sh->sector);
791
792         /* check if prexor is active which means only process blocks
793          * that are part of a read-modify-write (written)
794          */
795         if (prexor) {
796                 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
797                 for (i = disks; i--; ) {
798                         struct r5dev *dev = &sh->dev[i];
799                         if (dev->written)
800                                 xor_srcs[count++] = dev->page;
801                 }
802         } else {
803                 xor_dest = sh->dev[pd_idx].page;
804                 for (i = disks; i--; ) {
805                         struct r5dev *dev = &sh->dev[i];
806                         if (i != pd_idx)
807                                 xor_srcs[count++] = dev->page;
808                 }
809         }
810
811         /* check whether this postxor is part of a write */
812         callback = test_bit(STRIPE_OP_BIODRAIN, &sh->ops.pending) ?
813                 ops_complete_write : ops_complete_postxor;
814
815         /* 1/ if we prexor'd then the dest is reused as a source
816          * 2/ if we did not prexor then we are redoing the parity
817          * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
818          * for the synchronous xor case
819          */
820         flags = ASYNC_TX_DEP_ACK | ASYNC_TX_ACK |
821                 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
822
823         atomic_inc(&sh->count);
824
825         if (unlikely(count == 1)) {
826                 flags &= ~(ASYNC_TX_XOR_DROP_DST | ASYNC_TX_XOR_ZERO_DST);
827                 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE,
828                         flags, tx, callback, sh);
829         } else
830                 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
831                         flags, tx, callback, sh);
832 }
833
834 static void ops_complete_check(void *stripe_head_ref)
835 {
836         struct stripe_head *sh = stripe_head_ref;
837         int pd_idx = sh->pd_idx;
838
839         pr_debug("%s: stripe %llu\n", __FUNCTION__,
840                 (unsigned long long)sh->sector);
841
842         if (test_and_clear_bit(STRIPE_OP_MOD_DMA_CHECK, &sh->ops.pending) &&
843                 sh->ops.zero_sum_result == 0)
844                 set_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
845
846         set_bit(STRIPE_OP_CHECK, &sh->ops.complete);
847         set_bit(STRIPE_HANDLE, &sh->state);
848         release_stripe(sh);
849 }
850
851 static void ops_run_check(struct stripe_head *sh)
852 {
853         /* kernel stack size limits the total number of disks */
854         int disks = sh->disks;
855         struct page *xor_srcs[disks];
856         struct dma_async_tx_descriptor *tx;
857
858         int count = 0, pd_idx = sh->pd_idx, i;
859         struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
860
861         pr_debug("%s: stripe %llu\n", __FUNCTION__,
862                 (unsigned long long)sh->sector);
863
864         for (i = disks; i--; ) {
865                 struct r5dev *dev = &sh->dev[i];
866                 if (i != pd_idx)
867                         xor_srcs[count++] = dev->page;
868         }
869
870         tx = async_xor_zero_sum(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
871                 &sh->ops.zero_sum_result, 0, NULL, NULL, NULL);
872
873         if (tx)
874                 set_bit(STRIPE_OP_MOD_DMA_CHECK, &sh->ops.pending);
875         else
876                 clear_bit(STRIPE_OP_MOD_DMA_CHECK, &sh->ops.pending);
877
878         atomic_inc(&sh->count);
879         tx = async_trigger_callback(ASYNC_TX_DEP_ACK | ASYNC_TX_ACK, tx,
880                 ops_complete_check, sh);
881 }
882
883 static void raid5_run_ops(struct stripe_head *sh, unsigned long pending)
884 {
885         int overlap_clear = 0, i, disks = sh->disks;
886         struct dma_async_tx_descriptor *tx = NULL;
887
888         if (test_bit(STRIPE_OP_BIOFILL, &pending)) {
889                 ops_run_biofill(sh);
890                 overlap_clear++;
891         }
892
893         if (test_bit(STRIPE_OP_COMPUTE_BLK, &pending))
894                 tx = ops_run_compute5(sh, pending);
895
896         if (test_bit(STRIPE_OP_PREXOR, &pending))
897                 tx = ops_run_prexor(sh, tx);
898
899         if (test_bit(STRIPE_OP_BIODRAIN, &pending)) {
900                 tx = ops_run_biodrain(sh, tx);
901                 overlap_clear++;
902         }
903
904         if (test_bit(STRIPE_OP_POSTXOR, &pending))
905                 ops_run_postxor(sh, tx);
906
907         if (test_bit(STRIPE_OP_CHECK, &pending))
908                 ops_run_check(sh);
909
910         if (test_bit(STRIPE_OP_IO, &pending))
911                 ops_run_io(sh);
912
913         if (overlap_clear)
914                 for (i = disks; i--; ) {
915                         struct r5dev *dev = &sh->dev[i];
916                         if (test_and_clear_bit(R5_Overlap, &dev->flags))
917                                 wake_up(&sh->raid_conf->wait_for_overlap);
918                 }
919 }
920
921 static int grow_one_stripe(raid5_conf_t *conf)
922 {
923         struct stripe_head *sh;
924         sh = kmem_cache_alloc(conf->slab_cache, GFP_KERNEL);
925         if (!sh)
926                 return 0;
927         memset(sh, 0, sizeof(*sh) + (conf->raid_disks-1)*sizeof(struct r5dev));
928         sh->raid_conf = conf;
929         spin_lock_init(&sh->lock);
930
931         if (grow_buffers(sh, conf->raid_disks)) {
932                 shrink_buffers(sh, conf->raid_disks);
933                 kmem_cache_free(conf->slab_cache, sh);
934                 return 0;
935         }
936         sh->disks = conf->raid_disks;
937         /* we just created an active stripe so... */
938         atomic_set(&sh->count, 1);
939         atomic_inc(&conf->active_stripes);
940         INIT_LIST_HEAD(&sh->lru);
941         release_stripe(sh);
942         return 1;
943 }
944
945 static int grow_stripes(raid5_conf_t *conf, int num)
946 {
947         struct kmem_cache *sc;
948         int devs = conf->raid_disks;
949
950         sprintf(conf->cache_name[0], "raid5-%s", mdname(conf->mddev));
951         sprintf(conf->cache_name[1], "raid5-%s-alt", mdname(conf->mddev));
952         conf->active_name = 0;
953         sc = kmem_cache_create(conf->cache_name[conf->active_name],
954                                sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
955                                0, 0, NULL);
956         if (!sc)
957                 return 1;
958         conf->slab_cache = sc;
959         conf->pool_size = devs;
960         while (num--)
961                 if (!grow_one_stripe(conf))
962                         return 1;
963         return 0;
964 }
965
966 #ifdef CONFIG_MD_RAID5_RESHAPE
967 static int resize_stripes(raid5_conf_t *conf, int newsize)
968 {
969         /* Make all the stripes able to hold 'newsize' devices.
970          * New slots in each stripe get 'page' set to a new page.
971          *
972          * This happens in stages:
973          * 1/ create a new kmem_cache and allocate the required number of
974          *    stripe_heads.
975          * 2/ gather all the old stripe_heads and tranfer the pages across
976          *    to the new stripe_heads.  This will have the side effect of
977          *    freezing the array as once all stripe_heads have been collected,
978          *    no IO will be possible.  Old stripe heads are freed once their
979          *    pages have been transferred over, and the old kmem_cache is
980          *    freed when all stripes are done.
981          * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
982          *    we simple return a failre status - no need to clean anything up.
983          * 4/ allocate new pages for the new slots in the new stripe_heads.
984          *    If this fails, we don't bother trying the shrink the
985          *    stripe_heads down again, we just leave them as they are.
986          *    As each stripe_head is processed the new one is released into
987          *    active service.
988          *
989          * Once step2 is started, we cannot afford to wait for a write,
990          * so we use GFP_NOIO allocations.
991          */
992         struct stripe_head *osh, *nsh;
993         LIST_HEAD(newstripes);
994         struct disk_info *ndisks;
995         int err = 0;
996         struct kmem_cache *sc;
997         int i;
998
999         if (newsize <= conf->pool_size)
1000                 return 0; /* never bother to shrink */
1001
1002         md_allow_write(conf->mddev);
1003
1004         /* Step 1 */
1005         sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
1006                                sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
1007                                0, 0, NULL);
1008         if (!sc)
1009                 return -ENOMEM;
1010
1011         for (i = conf->max_nr_stripes; i; i--) {
1012                 nsh = kmem_cache_alloc(sc, GFP_KERNEL);
1013                 if (!nsh)
1014                         break;
1015
1016                 memset(nsh, 0, sizeof(*nsh) + (newsize-1)*sizeof(struct r5dev));
1017
1018                 nsh->raid_conf = conf;
1019                 spin_lock_init(&nsh->lock);
1020
1021                 list_add(&nsh->lru, &newstripes);
1022         }
1023         if (i) {
1024                 /* didn't get enough, give up */
1025                 while (!list_empty(&newstripes)) {
1026                         nsh = list_entry(newstripes.next, struct stripe_head, lru);
1027                         list_del(&nsh->lru);
1028                         kmem_cache_free(sc, nsh);
1029                 }
1030                 kmem_cache_destroy(sc);
1031                 return -ENOMEM;
1032         }
1033         /* Step 2 - Must use GFP_NOIO now.
1034          * OK, we have enough stripes, start collecting inactive
1035          * stripes and copying them over
1036          */
1037         list_for_each_entry(nsh, &newstripes, lru) {
1038                 spin_lock_irq(&conf->device_lock);
1039                 wait_event_lock_irq(conf->wait_for_stripe,
1040                                     !list_empty(&conf->inactive_list),
1041                                     conf->device_lock,
1042                                     unplug_slaves(conf->mddev)
1043                         );
1044                 osh = get_free_stripe(conf);
1045                 spin_unlock_irq(&conf->device_lock);
1046                 atomic_set(&nsh->count, 1);
1047                 for(i=0; i<conf->pool_size; i++)
1048                         nsh->dev[i].page = osh->dev[i].page;
1049                 for( ; i<newsize; i++)
1050                         nsh->dev[i].page = NULL;
1051                 kmem_cache_free(conf->slab_cache, osh);
1052         }
1053         kmem_cache_destroy(conf->slab_cache);
1054
1055         /* Step 3.
1056          * At this point, we are holding all the stripes so the array
1057          * is completely stalled, so now is a good time to resize
1058          * conf->disks.
1059          */
1060         ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
1061         if (ndisks) {
1062                 for (i=0; i<conf->raid_disks; i++)
1063                         ndisks[i] = conf->disks[i];
1064                 kfree(conf->disks);
1065                 conf->disks = ndisks;
1066         } else
1067                 err = -ENOMEM;
1068
1069         /* Step 4, return new stripes to service */
1070         while(!list_empty(&newstripes)) {
1071                 nsh = list_entry(newstripes.next, struct stripe_head, lru);
1072                 list_del_init(&nsh->lru);
1073                 for (i=conf->raid_disks; i < newsize; i++)
1074                         if (nsh->dev[i].page == NULL) {
1075                                 struct page *p = alloc_page(GFP_NOIO);
1076                                 nsh->dev[i].page = p;
1077                                 if (!p)
1078                                         err = -ENOMEM;
1079                         }
1080                 release_stripe(nsh);
1081         }
1082         /* critical section pass, GFP_NOIO no longer needed */
1083
1084         conf->slab_cache = sc;
1085         conf->active_name = 1-conf->active_name;
1086         conf->pool_size = newsize;
1087         return err;
1088 }
1089 #endif
1090
1091 static int drop_one_stripe(raid5_conf_t *conf)
1092 {
1093         struct stripe_head *sh;
1094
1095         spin_lock_irq(&conf->device_lock);
1096         sh = get_free_stripe(conf);
1097         spin_unlock_irq(&conf->device_lock);
1098         if (!sh)
1099                 return 0;
1100         BUG_ON(atomic_read(&sh->count));
1101         shrink_buffers(sh, conf->pool_size);
1102         kmem_cache_free(conf->slab_cache, sh);
1103         atomic_dec(&conf->active_stripes);
1104         return 1;
1105 }
1106
1107 static void shrink_stripes(raid5_conf_t *conf)
1108 {
1109         while (drop_one_stripe(conf))
1110                 ;
1111
1112         if (conf->slab_cache)
1113                 kmem_cache_destroy(conf->slab_cache);
1114         conf->slab_cache = NULL;
1115 }
1116
1117 static int raid5_end_read_request(struct bio * bi, unsigned int bytes_done,
1118                                    int error)
1119 {
1120         struct stripe_head *sh = bi->bi_private;
1121         raid5_conf_t *conf = sh->raid_conf;
1122         int disks = sh->disks, i;
1123         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1124         char b[BDEVNAME_SIZE];
1125         mdk_rdev_t *rdev;
1126
1127         if (bi->bi_size)
1128                 return 1;
1129
1130         for (i=0 ; i<disks; i++)
1131                 if (bi == &sh->dev[i].req)
1132                         break;
1133
1134         pr_debug("end_read_request %llu/%d, count: %d, uptodate %d.\n",
1135                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
1136                 uptodate);
1137         if (i == disks) {
1138                 BUG();
1139                 return 0;
1140         }
1141
1142         if (uptodate) {
1143                 set_bit(R5_UPTODATE, &sh->dev[i].flags);
1144                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
1145                         rdev = conf->disks[i].rdev;
1146                         printk(KERN_INFO "raid5:%s: read error corrected (%lu sectors at %llu on %s)\n",
1147                                mdname(conf->mddev), STRIPE_SECTORS,
1148                                (unsigned long long)sh->sector + rdev->data_offset,
1149                                bdevname(rdev->bdev, b));
1150                         clear_bit(R5_ReadError, &sh->dev[i].flags);
1151                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
1152                 }
1153                 if (atomic_read(&conf->disks[i].rdev->read_errors))
1154                         atomic_set(&conf->disks[i].rdev->read_errors, 0);
1155         } else {
1156                 const char *bdn = bdevname(conf->disks[i].rdev->bdev, b);
1157                 int retry = 0;
1158                 rdev = conf->disks[i].rdev;
1159
1160                 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
1161                 atomic_inc(&rdev->read_errors);
1162                 if (conf->mddev->degraded)
1163                         printk(KERN_WARNING "raid5:%s: read error not correctable (sector %llu on %s).\n",
1164                                mdname(conf->mddev),
1165                                (unsigned long long)sh->sector + rdev->data_offset,
1166                                bdn);
1167                 else if (test_bit(R5_ReWrite, &sh->dev[i].flags))
1168                         /* Oh, no!!! */
1169                         printk(KERN_WARNING "raid5:%s: read error NOT corrected!! (sector %llu on %s).\n",
1170                                mdname(conf->mddev),
1171                                (unsigned long long)sh->sector + rdev->data_offset,
1172                                bdn);
1173                 else if (atomic_read(&rdev->read_errors)
1174                          > conf->max_nr_stripes)
1175                         printk(KERN_WARNING
1176                                "raid5:%s: Too many read errors, failing device %s.\n",
1177                                mdname(conf->mddev), bdn);
1178                 else
1179                         retry = 1;
1180                 if (retry)
1181                         set_bit(R5_ReadError, &sh->dev[i].flags);
1182                 else {
1183                         clear_bit(R5_ReadError, &sh->dev[i].flags);
1184                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
1185                         md_error(conf->mddev, rdev);
1186                 }
1187         }
1188         rdev_dec_pending(conf->disks[i].rdev, conf->mddev);
1189         clear_bit(R5_LOCKED, &sh->dev[i].flags);
1190         set_bit(STRIPE_HANDLE, &sh->state);
1191         release_stripe(sh);
1192         return 0;
1193 }
1194
1195 static int raid5_end_write_request (struct bio *bi, unsigned int bytes_done,
1196                                     int error)
1197 {
1198         struct stripe_head *sh = bi->bi_private;
1199         raid5_conf_t *conf = sh->raid_conf;
1200         int disks = sh->disks, i;
1201         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1202
1203         if (bi->bi_size)
1204                 return 1;
1205
1206         for (i=0 ; i<disks; i++)
1207                 if (bi == &sh->dev[i].req)
1208                         break;
1209
1210         pr_debug("end_write_request %llu/%d, count %d, uptodate: %d.\n",
1211                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
1212                 uptodate);
1213         if (i == disks) {
1214                 BUG();
1215                 return 0;
1216         }
1217
1218         if (!uptodate)
1219                 md_error(conf->mddev, conf->disks[i].rdev);
1220
1221         rdev_dec_pending(conf->disks[i].rdev, conf->mddev);
1222         
1223         clear_bit(R5_LOCKED, &sh->dev[i].flags);
1224         set_bit(STRIPE_HANDLE, &sh->state);
1225         release_stripe(sh);
1226         return 0;
1227 }
1228
1229
1230 static sector_t compute_blocknr(struct stripe_head *sh, int i);
1231         
1232 static void raid5_build_block (struct stripe_head *sh, int i)
1233 {
1234         struct r5dev *dev = &sh->dev[i];
1235
1236         bio_init(&dev->req);
1237         dev->req.bi_io_vec = &dev->vec;
1238         dev->req.bi_vcnt++;
1239         dev->req.bi_max_vecs++;
1240         dev->vec.bv_page = dev->page;
1241         dev->vec.bv_len = STRIPE_SIZE;
1242         dev->vec.bv_offset = 0;
1243
1244         dev->req.bi_sector = sh->sector;
1245         dev->req.bi_private = sh;
1246
1247         dev->flags = 0;
1248         dev->sector = compute_blocknr(sh, i);
1249 }
1250
1251 static void error(mddev_t *mddev, mdk_rdev_t *rdev)
1252 {
1253         char b[BDEVNAME_SIZE];
1254         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
1255         pr_debug("raid5: error called\n");
1256
1257         if (!test_bit(Faulty, &rdev->flags)) {
1258                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
1259                 if (test_and_clear_bit(In_sync, &rdev->flags)) {
1260                         unsigned long flags;
1261                         spin_lock_irqsave(&conf->device_lock, flags);
1262                         mddev->degraded++;
1263                         spin_unlock_irqrestore(&conf->device_lock, flags);
1264                         /*
1265                          * if recovery was running, make sure it aborts.
1266                          */
1267                         set_bit(MD_RECOVERY_ERR, &mddev->recovery);
1268                 }
1269                 set_bit(Faulty, &rdev->flags);
1270                 printk (KERN_ALERT
1271                         "raid5: Disk failure on %s, disabling device."
1272                         " Operation continuing on %d devices\n",
1273                         bdevname(rdev->bdev,b), conf->raid_disks - mddev->degraded);
1274         }
1275 }
1276
1277 /*
1278  * Input: a 'big' sector number,
1279  * Output: index of the data and parity disk, and the sector # in them.
1280  */
1281 static sector_t raid5_compute_sector(sector_t r_sector, unsigned int raid_disks,
1282                         unsigned int data_disks, unsigned int * dd_idx,
1283                         unsigned int * pd_idx, raid5_conf_t *conf)
1284 {
1285         long stripe;
1286         unsigned long chunk_number;
1287         unsigned int chunk_offset;
1288         sector_t new_sector;
1289         int sectors_per_chunk = conf->chunk_size >> 9;
1290
1291         /* First compute the information on this sector */
1292
1293         /*
1294          * Compute the chunk number and the sector offset inside the chunk
1295          */
1296         chunk_offset = sector_div(r_sector, sectors_per_chunk);
1297         chunk_number = r_sector;
1298         BUG_ON(r_sector != chunk_number);
1299
1300         /*
1301          * Compute the stripe number
1302          */
1303         stripe = chunk_number / data_disks;
1304
1305         /*
1306          * Compute the data disk and parity disk indexes inside the stripe
1307          */
1308         *dd_idx = chunk_number % data_disks;
1309
1310         /*
1311          * Select the parity disk based on the user selected algorithm.
1312          */
1313         switch(conf->level) {
1314         case 4:
1315                 *pd_idx = data_disks;
1316                 break;
1317         case 5:
1318                 switch (conf->algorithm) {
1319                 case ALGORITHM_LEFT_ASYMMETRIC:
1320                         *pd_idx = data_disks - stripe % raid_disks;
1321                         if (*dd_idx >= *pd_idx)
1322                                 (*dd_idx)++;
1323                         break;
1324                 case ALGORITHM_RIGHT_ASYMMETRIC:
1325                         *pd_idx = stripe % raid_disks;
1326                         if (*dd_idx >= *pd_idx)
1327                                 (*dd_idx)++;
1328                         break;
1329                 case ALGORITHM_LEFT_SYMMETRIC:
1330                         *pd_idx = data_disks - stripe % raid_disks;
1331                         *dd_idx = (*pd_idx + 1 + *dd_idx) % raid_disks;
1332                         break;
1333                 case ALGORITHM_RIGHT_SYMMETRIC:
1334                         *pd_idx = stripe % raid_disks;
1335                         *dd_idx = (*pd_idx + 1 + *dd_idx) % raid_disks;
1336                         break;
1337                 default:
1338                         printk(KERN_ERR "raid5: unsupported algorithm %d\n",
1339                                 conf->algorithm);
1340                 }
1341                 break;
1342         case 6:
1343
1344                 /**** FIX THIS ****/
1345                 switch (conf->algorithm) {
1346                 case ALGORITHM_LEFT_ASYMMETRIC:
1347                         *pd_idx = raid_disks - 1 - (stripe % raid_disks);
1348                         if (*pd_idx == raid_disks-1)
1349                                 (*dd_idx)++;    /* Q D D D P */
1350                         else if (*dd_idx >= *pd_idx)
1351                                 (*dd_idx) += 2; /* D D P Q D */
1352                         break;
1353                 case ALGORITHM_RIGHT_ASYMMETRIC:
1354                         *pd_idx = stripe % raid_disks;
1355                         if (*pd_idx == raid_disks-1)
1356                                 (*dd_idx)++;    /* Q D D D P */
1357                         else if (*dd_idx >= *pd_idx)
1358                                 (*dd_idx) += 2; /* D D P Q D */
1359                         break;
1360                 case ALGORITHM_LEFT_SYMMETRIC:
1361                         *pd_idx = raid_disks - 1 - (stripe % raid_disks);
1362                         *dd_idx = (*pd_idx + 2 + *dd_idx) % raid_disks;
1363                         break;
1364                 case ALGORITHM_RIGHT_SYMMETRIC:
1365                         *pd_idx = stripe % raid_disks;
1366                         *dd_idx = (*pd_idx + 2 + *dd_idx) % raid_disks;
1367                         break;
1368                 default:
1369                         printk (KERN_CRIT "raid6: unsupported algorithm %d\n",
1370                                 conf->algorithm);
1371                 }
1372                 break;
1373         }
1374
1375         /*
1376          * Finally, compute the new sector number
1377          */
1378         new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
1379         return new_sector;
1380 }
1381
1382
1383 static sector_t compute_blocknr(struct stripe_head *sh, int i)
1384 {
1385         raid5_conf_t *conf = sh->raid_conf;
1386         int raid_disks = sh->disks;
1387         int data_disks = raid_disks - conf->max_degraded;
1388         sector_t new_sector = sh->sector, check;
1389         int sectors_per_chunk = conf->chunk_size >> 9;
1390         sector_t stripe;
1391         int chunk_offset;
1392         int chunk_number, dummy1, dummy2, dd_idx = i;
1393         sector_t r_sector;
1394
1395
1396         chunk_offset = sector_div(new_sector, sectors_per_chunk);
1397         stripe = new_sector;
1398         BUG_ON(new_sector != stripe);
1399
1400         if (i == sh->pd_idx)
1401                 return 0;
1402         switch(conf->level) {
1403         case 4: break;
1404         case 5:
1405                 switch (conf->algorithm) {
1406                 case ALGORITHM_LEFT_ASYMMETRIC:
1407                 case ALGORITHM_RIGHT_ASYMMETRIC:
1408                         if (i > sh->pd_idx)
1409                                 i--;
1410                         break;
1411                 case ALGORITHM_LEFT_SYMMETRIC:
1412                 case ALGORITHM_RIGHT_SYMMETRIC:
1413                         if (i < sh->pd_idx)
1414                                 i += raid_disks;
1415                         i -= (sh->pd_idx + 1);
1416                         break;
1417                 default:
1418                         printk(KERN_ERR "raid5: unsupported algorithm %d\n",
1419                                conf->algorithm);
1420                 }
1421                 break;
1422         case 6:
1423                 if (i == raid6_next_disk(sh->pd_idx, raid_disks))
1424                         return 0; /* It is the Q disk */
1425                 switch (conf->algorithm) {
1426                 case ALGORITHM_LEFT_ASYMMETRIC:
1427                 case ALGORITHM_RIGHT_ASYMMETRIC:
1428                         if (sh->pd_idx == raid_disks-1)
1429                                 i--;    /* Q D D D P */
1430                         else if (i > sh->pd_idx)
1431                                 i -= 2; /* D D P Q D */
1432                         break;
1433                 case ALGORITHM_LEFT_SYMMETRIC:
1434                 case ALGORITHM_RIGHT_SYMMETRIC:
1435                         if (sh->pd_idx == raid_disks-1)
1436                                 i--; /* Q D D D P */
1437                         else {
1438                                 /* D D P Q D */
1439                                 if (i < sh->pd_idx)
1440                                         i += raid_disks;
1441                                 i -= (sh->pd_idx + 2);
1442                         }
1443                         break;
1444                 default:
1445                         printk (KERN_CRIT "raid6: unsupported algorithm %d\n",
1446                                 conf->algorithm);
1447                 }
1448                 break;
1449         }
1450
1451         chunk_number = stripe * data_disks + i;
1452         r_sector = (sector_t)chunk_number * sectors_per_chunk + chunk_offset;
1453
1454         check = raid5_compute_sector (r_sector, raid_disks, data_disks, &dummy1, &dummy2, conf);
1455         if (check != sh->sector || dummy1 != dd_idx || dummy2 != sh->pd_idx) {
1456                 printk(KERN_ERR "compute_blocknr: map not correct\n");
1457                 return 0;
1458         }
1459         return r_sector;
1460 }
1461
1462
1463
1464 /*
1465  * Copy data between a page in the stripe cache, and one or more bion
1466  * The page could align with the middle of the bio, or there could be
1467  * several bion, each with several bio_vecs, which cover part of the page
1468  * Multiple bion are linked together on bi_next.  There may be extras
1469  * at the end of this list.  We ignore them.
1470  */
1471 static void copy_data(int frombio, struct bio *bio,
1472                      struct page *page,
1473                      sector_t sector)
1474 {
1475         char *pa = page_address(page);
1476         struct bio_vec *bvl;
1477         int i;
1478         int page_offset;
1479
1480         if (bio->bi_sector >= sector)
1481                 page_offset = (signed)(bio->bi_sector - sector) * 512;
1482         else
1483                 page_offset = (signed)(sector - bio->bi_sector) * -512;
1484         bio_for_each_segment(bvl, bio, i) {
1485                 int len = bio_iovec_idx(bio,i)->bv_len;
1486                 int clen;
1487                 int b_offset = 0;
1488
1489                 if (page_offset < 0) {
1490                         b_offset = -page_offset;
1491                         page_offset += b_offset;
1492                         len -= b_offset;
1493                 }
1494
1495                 if (len > 0 && page_offset + len > STRIPE_SIZE)
1496                         clen = STRIPE_SIZE - page_offset;
1497                 else clen = len;
1498
1499                 if (clen > 0) {
1500                         char *ba = __bio_kmap_atomic(bio, i, KM_USER0);
1501                         if (frombio)
1502                                 memcpy(pa+page_offset, ba+b_offset, clen);
1503                         else
1504                                 memcpy(ba+b_offset, pa+page_offset, clen);
1505                         __bio_kunmap_atomic(ba, KM_USER0);
1506                 }
1507                 if (clen < len) /* hit end of page */
1508                         break;
1509                 page_offset +=  len;
1510         }
1511 }
1512
1513 #define check_xor()     do {                                              \
1514                                 if (count == MAX_XOR_BLOCKS) {            \
1515                                 xor_blocks(count, STRIPE_SIZE, dest, ptr);\
1516                                 count = 0;                                \
1517                            }                                              \
1518                         } while(0)
1519
1520 static void compute_parity6(struct stripe_head *sh, int method)
1521 {
1522         raid6_conf_t *conf = sh->raid_conf;
1523         int i, pd_idx = sh->pd_idx, qd_idx, d0_idx, disks = sh->disks, count;
1524         struct bio *chosen;
1525         /**** FIX THIS: This could be very bad if disks is close to 256 ****/
1526         void *ptrs[disks];
1527
1528         qd_idx = raid6_next_disk(pd_idx, disks);
1529         d0_idx = raid6_next_disk(qd_idx, disks);
1530
1531         pr_debug("compute_parity, stripe %llu, method %d\n",
1532                 (unsigned long long)sh->sector, method);
1533
1534         switch(method) {
1535         case READ_MODIFY_WRITE:
1536                 BUG();          /* READ_MODIFY_WRITE N/A for RAID-6 */
1537         case RECONSTRUCT_WRITE:
1538                 for (i= disks; i-- ;)
1539                         if ( i != pd_idx && i != qd_idx && sh->dev[i].towrite ) {
1540                                 chosen = sh->dev[i].towrite;
1541                                 sh->dev[i].towrite = NULL;
1542
1543                                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
1544                                         wake_up(&conf->wait_for_overlap);
1545
1546                                 BUG_ON(sh->dev[i].written);
1547                                 sh->dev[i].written = chosen;
1548                         }
1549                 break;
1550         case CHECK_PARITY:
1551                 BUG();          /* Not implemented yet */
1552         }
1553
1554         for (i = disks; i--;)
1555                 if (sh->dev[i].written) {
1556                         sector_t sector = sh->dev[i].sector;
1557                         struct bio *wbi = sh->dev[i].written;
1558                         while (wbi && wbi->bi_sector < sector + STRIPE_SECTORS) {
1559                                 copy_data(1, wbi, sh->dev[i].page, sector);
1560                                 wbi = r5_next_bio(wbi, sector);
1561                         }
1562
1563                         set_bit(R5_LOCKED, &sh->dev[i].flags);
1564                         set_bit(R5_UPTODATE, &sh->dev[i].flags);
1565                 }
1566
1567 //      switch(method) {
1568 //      case RECONSTRUCT_WRITE:
1569 //      case CHECK_PARITY:
1570 //      case UPDATE_PARITY:
1571                 /* Note that unlike RAID-5, the ordering of the disks matters greatly. */
1572                 /* FIX: Is this ordering of drives even remotely optimal? */
1573                 count = 0;
1574                 i = d0_idx;
1575                 do {
1576                         ptrs[count++] = page_address(sh->dev[i].page);
1577                         if (count <= disks-2 && !test_bit(R5_UPTODATE, &sh->dev[i].flags))
1578                                 printk("block %d/%d not uptodate on parity calc\n", i,count);
1579                         i = raid6_next_disk(i, disks);
1580                 } while ( i != d0_idx );
1581 //              break;
1582 //      }
1583
1584         raid6_call.gen_syndrome(disks, STRIPE_SIZE, ptrs);
1585
1586         switch(method) {
1587         case RECONSTRUCT_WRITE:
1588                 set_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
1589                 set_bit(R5_UPTODATE, &sh->dev[qd_idx].flags);
1590                 set_bit(R5_LOCKED,   &sh->dev[pd_idx].flags);
1591                 set_bit(R5_LOCKED,   &sh->dev[qd_idx].flags);
1592                 break;
1593         case UPDATE_PARITY:
1594                 set_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
1595                 set_bit(R5_UPTODATE, &sh->dev[qd_idx].flags);
1596                 break;
1597         }
1598 }
1599
1600
1601 /* Compute one missing block */
1602 static void compute_block_1(struct stripe_head *sh, int dd_idx, int nozero)
1603 {
1604         int i, count, disks = sh->disks;
1605         void *ptr[MAX_XOR_BLOCKS], *dest, *p;
1606         int pd_idx = sh->pd_idx;
1607         int qd_idx = raid6_next_disk(pd_idx, disks);
1608
1609         pr_debug("compute_block_1, stripe %llu, idx %d\n",
1610                 (unsigned long long)sh->sector, dd_idx);
1611
1612         if ( dd_idx == qd_idx ) {
1613                 /* We're actually computing the Q drive */
1614                 compute_parity6(sh, UPDATE_PARITY);
1615         } else {
1616                 dest = page_address(sh->dev[dd_idx].page);
1617                 if (!nozero) memset(dest, 0, STRIPE_SIZE);
1618                 count = 0;
1619                 for (i = disks ; i--; ) {
1620                         if (i == dd_idx || i == qd_idx)
1621                                 continue;
1622                         p = page_address(sh->dev[i].page);
1623                         if (test_bit(R5_UPTODATE, &sh->dev[i].flags))
1624                                 ptr[count++] = p;
1625                         else
1626                                 printk("compute_block() %d, stripe %llu, %d"
1627                                        " not present\n", dd_idx,
1628                                        (unsigned long long)sh->sector, i);
1629
1630                         check_xor();
1631                 }
1632                 if (count)
1633                         xor_blocks(count, STRIPE_SIZE, dest, ptr);
1634                 if (!nozero) set_bit(R5_UPTODATE, &sh->dev[dd_idx].flags);
1635                 else clear_bit(R5_UPTODATE, &sh->dev[dd_idx].flags);
1636         }
1637 }
1638
1639 /* Compute two missing blocks */
1640 static void compute_block_2(struct stripe_head *sh, int dd_idx1, int dd_idx2)
1641 {
1642         int i, count, disks = sh->disks;
1643         int pd_idx = sh->pd_idx;
1644         int qd_idx = raid6_next_disk(pd_idx, disks);
1645         int d0_idx = raid6_next_disk(qd_idx, disks);
1646         int faila, failb;
1647
1648         /* faila and failb are disk numbers relative to d0_idx */
1649         /* pd_idx become disks-2 and qd_idx become disks-1 */
1650         faila = (dd_idx1 < d0_idx) ? dd_idx1+(disks-d0_idx) : dd_idx1-d0_idx;
1651         failb = (dd_idx2 < d0_idx) ? dd_idx2+(disks-d0_idx) : dd_idx2-d0_idx;
1652
1653         BUG_ON(faila == failb);
1654         if ( failb < faila ) { int tmp = faila; faila = failb; failb = tmp; }
1655
1656         pr_debug("compute_block_2, stripe %llu, idx %d,%d (%d,%d)\n",
1657                (unsigned long long)sh->sector, dd_idx1, dd_idx2, faila, failb);
1658
1659         if ( failb == disks-1 ) {
1660                 /* Q disk is one of the missing disks */
1661                 if ( faila == disks-2 ) {
1662                         /* Missing P+Q, just recompute */
1663                         compute_parity6(sh, UPDATE_PARITY);
1664                         return;
1665                 } else {
1666                         /* We're missing D+Q; recompute D from P */
1667                         compute_block_1(sh, (dd_idx1 == qd_idx) ? dd_idx2 : dd_idx1, 0);
1668                         compute_parity6(sh, UPDATE_PARITY); /* Is this necessary? */
1669                         return;
1670                 }
1671         }
1672
1673         /* We're missing D+P or D+D; build pointer table */
1674         {
1675                 /**** FIX THIS: This could be very bad if disks is close to 256 ****/
1676                 void *ptrs[disks];
1677
1678                 count = 0;
1679                 i = d0_idx;
1680                 do {
1681                         ptrs[count++] = page_address(sh->dev[i].page);
1682                         i = raid6_next_disk(i, disks);
1683                         if (i != dd_idx1 && i != dd_idx2 &&
1684                             !test_bit(R5_UPTODATE, &sh->dev[i].flags))
1685                                 printk("compute_2 with missing block %d/%d\n", count, i);
1686                 } while ( i != d0_idx );
1687
1688                 if ( failb == disks-2 ) {
1689                         /* We're missing D+P. */
1690                         raid6_datap_recov(disks, STRIPE_SIZE, faila, ptrs);
1691                 } else {
1692                         /* We're missing D+D. */
1693                         raid6_2data_recov(disks, STRIPE_SIZE, faila, failb, ptrs);
1694                 }
1695
1696                 /* Both the above update both missing blocks */
1697                 set_bit(R5_UPTODATE, &sh->dev[dd_idx1].flags);
1698                 set_bit(R5_UPTODATE, &sh->dev[dd_idx2].flags);
1699         }
1700 }
1701
1702 static int
1703 handle_write_operations5(struct stripe_head *sh, int rcw, int expand)
1704 {
1705         int i, pd_idx = sh->pd_idx, disks = sh->disks;
1706         int locked = 0;
1707
1708         if (rcw) {
1709                 /* if we are not expanding this is a proper write request, and
1710                  * there will be bios with new data to be drained into the
1711                  * stripe cache
1712                  */
1713                 if (!expand) {
1714                         set_bit(STRIPE_OP_BIODRAIN, &sh->ops.pending);
1715                         sh->ops.count++;
1716                 }
1717
1718                 set_bit(STRIPE_OP_POSTXOR, &sh->ops.pending);
1719                 sh->ops.count++;
1720
1721                 for (i = disks; i--; ) {
1722                         struct r5dev *dev = &sh->dev[i];
1723
1724                         if (dev->towrite) {
1725                                 set_bit(R5_LOCKED, &dev->flags);
1726                                 if (!expand)
1727                                         clear_bit(R5_UPTODATE, &dev->flags);
1728                                 locked++;
1729                         }
1730                 }
1731         } else {
1732                 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
1733                         test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
1734
1735                 set_bit(STRIPE_OP_PREXOR, &sh->ops.pending);
1736                 set_bit(STRIPE_OP_BIODRAIN, &sh->ops.pending);
1737                 set_bit(STRIPE_OP_POSTXOR, &sh->ops.pending);
1738
1739                 sh->ops.count += 3;
1740
1741                 for (i = disks; i--; ) {
1742                         struct r5dev *dev = &sh->dev[i];
1743                         if (i == pd_idx)
1744                                 continue;
1745
1746                         /* For a read-modify write there may be blocks that are
1747                          * locked for reading while others are ready to be
1748                          * written so we distinguish these blocks by the
1749                          * R5_Wantprexor bit
1750                          */
1751                         if (dev->towrite &&
1752                             (test_bit(R5_UPTODATE, &dev->flags) ||
1753                             test_bit(R5_Wantcompute, &dev->flags))) {
1754                                 set_bit(R5_Wantprexor, &dev->flags);
1755                                 set_bit(R5_LOCKED, &dev->flags);
1756                                 clear_bit(R5_UPTODATE, &dev->flags);
1757                                 locked++;
1758                         }
1759                 }
1760         }
1761
1762         /* keep the parity disk locked while asynchronous operations
1763          * are in flight
1764          */
1765         set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
1766         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
1767         locked++;
1768
1769         pr_debug("%s: stripe %llu locked: %d pending: %lx\n",
1770                 __FUNCTION__, (unsigned long long)sh->sector,
1771                 locked, sh->ops.pending);
1772
1773         return locked;
1774 }
1775
1776 /*
1777  * Each stripe/dev can have one or more bion attached.
1778  * toread/towrite point to the first in a chain.
1779  * The bi_next chain must be in order.
1780  */
1781 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx, int forwrite)
1782 {
1783         struct bio **bip;
1784         raid5_conf_t *conf = sh->raid_conf;
1785         int firstwrite=0;
1786
1787         pr_debug("adding bh b#%llu to stripe s#%llu\n",
1788                 (unsigned long long)bi->bi_sector,
1789                 (unsigned long long)sh->sector);
1790
1791
1792         spin_lock(&sh->lock);
1793         spin_lock_irq(&conf->device_lock);
1794         if (forwrite) {
1795                 bip = &sh->dev[dd_idx].towrite;
1796                 if (*bip == NULL && sh->dev[dd_idx].written == NULL)
1797                         firstwrite = 1;
1798         } else
1799                 bip = &sh->dev[dd_idx].toread;
1800         while (*bip && (*bip)->bi_sector < bi->bi_sector) {
1801                 if ((*bip)->bi_sector + ((*bip)->bi_size >> 9) > bi->bi_sector)
1802                         goto overlap;
1803                 bip = & (*bip)->bi_next;
1804         }
1805         if (*bip && (*bip)->bi_sector < bi->bi_sector + ((bi->bi_size)>>9))
1806                 goto overlap;
1807
1808         BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
1809         if (*bip)
1810                 bi->bi_next = *bip;
1811         *bip = bi;
1812         bi->bi_phys_segments ++;
1813         spin_unlock_irq(&conf->device_lock);
1814         spin_unlock(&sh->lock);
1815
1816         pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
1817                 (unsigned long long)bi->bi_sector,
1818                 (unsigned long long)sh->sector, dd_idx);
1819
1820         if (conf->mddev->bitmap && firstwrite) {
1821                 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
1822                                   STRIPE_SECTORS, 0);
1823                 sh->bm_seq = conf->seq_flush+1;
1824                 set_bit(STRIPE_BIT_DELAY, &sh->state);
1825         }
1826
1827         if (forwrite) {
1828                 /* check if page is covered */
1829                 sector_t sector = sh->dev[dd_idx].sector;
1830                 for (bi=sh->dev[dd_idx].towrite;
1831                      sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
1832                              bi && bi->bi_sector <= sector;
1833                      bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
1834                         if (bi->bi_sector + (bi->bi_size>>9) >= sector)
1835                                 sector = bi->bi_sector + (bi->bi_size>>9);
1836                 }
1837                 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
1838                         set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags);
1839         }
1840         return 1;
1841
1842  overlap:
1843         set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
1844         spin_unlock_irq(&conf->device_lock);
1845         spin_unlock(&sh->lock);
1846         return 0;
1847 }
1848
1849 static void end_reshape(raid5_conf_t *conf);
1850
1851 static int page_is_zero(struct page *p)
1852 {
1853         char *a = page_address(p);
1854         return ((*(u32*)a) == 0 &&
1855                 memcmp(a, a+4, STRIPE_SIZE-4)==0);
1856 }
1857
1858 static int stripe_to_pdidx(sector_t stripe, raid5_conf_t *conf, int disks)
1859 {
1860         int sectors_per_chunk = conf->chunk_size >> 9;
1861         int pd_idx, dd_idx;
1862         int chunk_offset = sector_div(stripe, sectors_per_chunk);
1863
1864         raid5_compute_sector(stripe * (disks - conf->max_degraded)
1865                              *sectors_per_chunk + chunk_offset,
1866                              disks, disks - conf->max_degraded,
1867                              &dd_idx, &pd_idx, conf);
1868         return pd_idx;
1869 }
1870
1871 static void
1872 handle_requests_to_failed_array(raid5_conf_t *conf, struct stripe_head *sh,
1873                                 struct stripe_head_state *s, int disks,
1874                                 struct bio **return_bi)
1875 {
1876         int i;
1877         for (i = disks; i--; ) {
1878                 struct bio *bi;
1879                 int bitmap_end = 0;
1880
1881                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
1882                         mdk_rdev_t *rdev;
1883                         rcu_read_lock();
1884                         rdev = rcu_dereference(conf->disks[i].rdev);
1885                         if (rdev && test_bit(In_sync, &rdev->flags))
1886                                 /* multiple read failures in one stripe */
1887                                 md_error(conf->mddev, rdev);
1888                         rcu_read_unlock();
1889                 }
1890                 spin_lock_irq(&conf->device_lock);
1891                 /* fail all writes first */
1892                 bi = sh->dev[i].towrite;
1893                 sh->dev[i].towrite = NULL;
1894                 if (bi) {
1895                         s->to_write--;
1896                         bitmap_end = 1;
1897                 }
1898
1899                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
1900                         wake_up(&conf->wait_for_overlap);
1901
1902                 while (bi && bi->bi_sector <
1903                         sh->dev[i].sector + STRIPE_SECTORS) {
1904                         struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
1905                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
1906                         if (--bi->bi_phys_segments == 0) {
1907                                 md_write_end(conf->mddev);
1908                                 bi->bi_next = *return_bi;
1909                                 *return_bi = bi;
1910                         }
1911                         bi = nextbi;
1912                 }
1913                 /* and fail all 'written' */
1914                 bi = sh->dev[i].written;
1915                 sh->dev[i].written = NULL;
1916                 if (bi) bitmap_end = 1;
1917                 while (bi && bi->bi_sector <
1918                        sh->dev[i].sector + STRIPE_SECTORS) {
1919                         struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
1920                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
1921                         if (--bi->bi_phys_segments == 0) {
1922                                 md_write_end(conf->mddev);
1923                                 bi->bi_next = *return_bi;
1924                                 *return_bi = bi;
1925                         }
1926                         bi = bi2;
1927                 }
1928
1929                 /* fail any reads if this device is non-operational and
1930                  * the data has not reached the cache yet.
1931                  */
1932                 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
1933                     (!test_bit(R5_Insync, &sh->dev[i].flags) ||
1934                       test_bit(R5_ReadError, &sh->dev[i].flags))) {
1935                         bi = sh->dev[i].toread;
1936                         sh->dev[i].toread = NULL;
1937                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
1938                                 wake_up(&conf->wait_for_overlap);
1939                         if (bi) s->to_read--;
1940                         while (bi && bi->bi_sector <
1941                                sh->dev[i].sector + STRIPE_SECTORS) {
1942                                 struct bio *nextbi =
1943                                         r5_next_bio(bi, sh->dev[i].sector);
1944                                 clear_bit(BIO_UPTODATE, &bi->bi_flags);
1945                                 if (--bi->bi_phys_segments == 0) {
1946                                         bi->bi_next = *return_bi;
1947                                         *return_bi = bi;
1948                                 }
1949                                 bi = nextbi;
1950                         }
1951                 }
1952                 spin_unlock_irq(&conf->device_lock);
1953                 if (bitmap_end)
1954                         bitmap_endwrite(conf->mddev->bitmap, sh->sector,
1955                                         STRIPE_SECTORS, 0, 0);
1956         }
1957
1958 }
1959
1960 /* __handle_issuing_new_read_requests5 - returns 0 if there are no more disks
1961  * to process
1962  */
1963 static int __handle_issuing_new_read_requests5(struct stripe_head *sh,
1964                         struct stripe_head_state *s, int disk_idx, int disks)
1965 {
1966         struct r5dev *dev = &sh->dev[disk_idx];
1967         struct r5dev *failed_dev = &sh->dev[s->failed_num];
1968
1969         /* don't schedule compute operations or reads on the parity block while
1970          * a check is in flight
1971          */
1972         if ((disk_idx == sh->pd_idx) &&
1973              test_bit(STRIPE_OP_CHECK, &sh->ops.pending))
1974                 return ~0;
1975
1976         /* is the data in this block needed, and can we get it? */
1977         if (!test_bit(R5_LOCKED, &dev->flags) &&
1978             !test_bit(R5_UPTODATE, &dev->flags) && (dev->toread ||
1979             (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
1980              s->syncing || s->expanding || (s->failed &&
1981              (failed_dev->toread || (failed_dev->towrite &&
1982              !test_bit(R5_OVERWRITE, &failed_dev->flags)
1983              ))))) {
1984                 /* 1/ We would like to get this block, possibly by computing it,
1985                  * but we might not be able to.
1986                  *
1987                  * 2/ Since parity check operations potentially make the parity
1988                  * block !uptodate it will need to be refreshed before any
1989                  * compute operations on data disks are scheduled.
1990                  *
1991                  * 3/ We hold off parity block re-reads until check operations
1992                  * have quiesced.
1993                  */
1994                 if ((s->uptodate == disks - 1) &&
1995                     !test_bit(STRIPE_OP_CHECK, &sh->ops.pending)) {
1996                         set_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.pending);
1997                         set_bit(R5_Wantcompute, &dev->flags);
1998                         sh->ops.target = disk_idx;
1999                         s->req_compute = 1;
2000                         sh->ops.count++;
2001                         /* Careful: from this point on 'uptodate' is in the eye
2002                          * of raid5_run_ops which services 'compute' operations
2003                          * before writes. R5_Wantcompute flags a block that will
2004                          * be R5_UPTODATE by the time it is needed for a
2005                          * subsequent operation.
2006                          */
2007                         s->uptodate++;
2008                         return 0; /* uptodate + compute == disks */
2009                 } else if ((s->uptodate < disks - 1) &&
2010                         test_bit(R5_Insync, &dev->flags)) {
2011                         /* Note: we hold off compute operations while checks are
2012                          * in flight, but we still prefer 'compute' over 'read'
2013                          * hence we only read if (uptodate < * disks-1)
2014                          */
2015                         set_bit(R5_LOCKED, &dev->flags);
2016                         set_bit(R5_Wantread, &dev->flags);
2017                         if (!test_and_set_bit(STRIPE_OP_IO, &sh->ops.pending))
2018                                 sh->ops.count++;
2019                         s->locked++;
2020                         pr_debug("Reading block %d (sync=%d)\n", disk_idx,
2021                                 s->syncing);
2022                 }
2023         }
2024
2025         return ~0;
2026 }
2027
2028 static void handle_issuing_new_read_requests5(struct stripe_head *sh,
2029                         struct stripe_head_state *s, int disks)
2030 {
2031         int i;
2032
2033         /* Clear completed compute operations.  Parity recovery
2034          * (STRIPE_OP_MOD_REPAIR_PD) implies a write-back which is handled
2035          * later on in this routine
2036          */
2037         if (test_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.complete) &&
2038                 !test_bit(STRIPE_OP_MOD_REPAIR_PD, &sh->ops.pending)) {
2039                 clear_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.complete);
2040                 clear_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.ack);
2041                 clear_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.pending);
2042         }
2043
2044         /* look for blocks to read/compute, skip this if a compute
2045          * is already in flight, or if the stripe contents are in the
2046          * midst of changing due to a write
2047          */
2048         if (!test_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.pending) &&
2049                 !test_bit(STRIPE_OP_PREXOR, &sh->ops.pending) &&
2050                 !test_bit(STRIPE_OP_POSTXOR, &sh->ops.pending)) {
2051                 for (i = disks; i--; )
2052                         if (__handle_issuing_new_read_requests5(
2053                                 sh, s, i, disks) == 0)
2054                                 break;
2055         }
2056         set_bit(STRIPE_HANDLE, &sh->state);
2057 }
2058
2059 static void handle_issuing_new_read_requests6(struct stripe_head *sh,
2060                         struct stripe_head_state *s, struct r6_state *r6s,
2061                         int disks)
2062 {
2063         int i;
2064         for (i = disks; i--; ) {
2065                 struct r5dev *dev = &sh->dev[i];
2066                 if (!test_bit(R5_LOCKED, &dev->flags) &&
2067                     !test_bit(R5_UPTODATE, &dev->flags) &&
2068                     (dev->toread || (dev->towrite &&
2069                      !test_bit(R5_OVERWRITE, &dev->flags)) ||
2070                      s->syncing || s->expanding ||
2071                      (s->failed >= 1 &&
2072                       (sh->dev[r6s->failed_num[0]].toread ||
2073                        s->to_write)) ||
2074                      (s->failed >= 2 &&
2075                       (sh->dev[r6s->failed_num[1]].toread ||
2076                        s->to_write)))) {
2077                         /* we would like to get this block, possibly
2078                          * by computing it, but we might not be able to
2079                          */
2080                         if (s->uptodate == disks-1) {
2081                                 pr_debug("Computing stripe %llu block %d\n",
2082                                        (unsigned long long)sh->sector, i);
2083                                 compute_block_1(sh, i, 0);
2084                                 s->uptodate++;
2085                         } else if ( s->uptodate == disks-2 && s->failed >= 2 ) {
2086                                 /* Computing 2-failure is *very* expensive; only
2087                                  * do it if failed >= 2
2088                                  */
2089                                 int other;
2090                                 for (other = disks; other--; ) {
2091                                         if (other == i)
2092                                                 continue;
2093                                         if (!test_bit(R5_UPTODATE,
2094                                               &sh->dev[other].flags))
2095                                                 break;
2096                                 }
2097                                 BUG_ON(other < 0);
2098                                 pr_debug("Computing stripe %llu blocks %d,%d\n",
2099                                        (unsigned long long)sh->sector,
2100                                        i, other);
2101                                 compute_block_2(sh, i, other);
2102                                 s->uptodate += 2;
2103                         } else if (test_bit(R5_Insync, &dev->flags)) {
2104                                 set_bit(R5_LOCKED, &dev->flags);
2105                                 set_bit(R5_Wantread, &dev->flags);
2106                                 s->locked++;
2107                                 pr_debug("Reading block %d (sync=%d)\n",
2108                                         i, s->syncing);
2109                         }
2110                 }
2111         }
2112         set_bit(STRIPE_HANDLE, &sh->state);
2113 }
2114
2115
2116 /* handle_completed_write_requests
2117  * any written block on an uptodate or failed drive can be returned.
2118  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
2119  * never LOCKED, so we don't need to test 'failed' directly.
2120  */
2121 static void handle_completed_write_requests(raid5_conf_t *conf,
2122         struct stripe_head *sh, int disks, struct bio **return_bi)
2123 {
2124         int i;
2125         struct r5dev *dev;
2126
2127         for (i = disks; i--; )
2128                 if (sh->dev[i].written) {
2129                         dev = &sh->dev[i];
2130                         if (!test_bit(R5_LOCKED, &dev->flags) &&
2131                                 test_bit(R5_UPTODATE, &dev->flags)) {
2132                                 /* We can return any write requests */
2133                                 struct bio *wbi, *wbi2;
2134                                 int bitmap_end = 0;
2135                                 pr_debug("Return write for disc %d\n", i);
2136                                 spin_lock_irq(&conf->device_lock);
2137                                 wbi = dev->written;
2138                                 dev->written = NULL;
2139                                 while (wbi && wbi->bi_sector <
2140                                         dev->sector + STRIPE_SECTORS) {
2141                                         wbi2 = r5_next_bio(wbi, dev->sector);
2142                                         if (--wbi->bi_phys_segments == 0) {
2143                                                 md_write_end(conf->mddev);
2144                                                 wbi->bi_next = *return_bi;
2145                                                 *return_bi = wbi;
2146                                         }
2147                                         wbi = wbi2;
2148                                 }
2149                                 if (dev->towrite == NULL)
2150                                         bitmap_end = 1;
2151                                 spin_unlock_irq(&conf->device_lock);
2152                                 if (bitmap_end)
2153                                         bitmap_endwrite(conf->mddev->bitmap,
2154                                                         sh->sector,
2155                                                         STRIPE_SECTORS,
2156                                          !test_bit(STRIPE_DEGRADED, &sh->state),
2157                                                         0);
2158                         }
2159                 }
2160 }
2161
2162 static void handle_issuing_new_write_requests5(raid5_conf_t *conf,
2163                 struct stripe_head *sh, struct stripe_head_state *s, int disks)
2164 {
2165         int rmw = 0, rcw = 0, i;
2166         for (i = disks; i--; ) {
2167                 /* would I have to read this buffer for read_modify_write */
2168                 struct r5dev *dev = &sh->dev[i];
2169                 if ((dev->towrite || i == sh->pd_idx) &&
2170                     !test_bit(R5_LOCKED, &dev->flags) &&
2171                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2172                       test_bit(R5_Wantcompute, &dev->flags))) {
2173                         if (test_bit(R5_Insync, &dev->flags))
2174                                 rmw++;
2175                         else
2176                                 rmw += 2*disks;  /* cannot read it */
2177                 }
2178                 /* Would I have to read this buffer for reconstruct_write */
2179                 if (!test_bit(R5_OVERWRITE, &dev->flags) && i != sh->pd_idx &&
2180                     !test_bit(R5_LOCKED, &dev->flags) &&
2181                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2182                     test_bit(R5_Wantcompute, &dev->flags))) {
2183                         if (test_bit(R5_Insync, &dev->flags)) rcw++;
2184                         else
2185                                 rcw += 2*disks;
2186                 }
2187         }
2188         pr_debug("for sector %llu, rmw=%d rcw=%d\n",
2189                 (unsigned long long)sh->sector, rmw, rcw);
2190         set_bit(STRIPE_HANDLE, &sh->state);
2191         if (rmw < rcw && rmw > 0)
2192                 /* prefer read-modify-write, but need to get some data */
2193                 for (i = disks; i--; ) {
2194                         struct r5dev *dev = &sh->dev[i];
2195                         if ((dev->towrite || i == sh->pd_idx) &&
2196                             !test_bit(R5_LOCKED, &dev->flags) &&
2197                             !(test_bit(R5_UPTODATE, &dev->flags) ||
2198                             test_bit(R5_Wantcompute, &dev->flags)) &&
2199                             test_bit(R5_Insync, &dev->flags)) {
2200                                 if (
2201                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2202                                         pr_debug("Read_old block "
2203                                                 "%d for r-m-w\n", i);
2204                                         set_bit(R5_LOCKED, &dev->flags);
2205                                         set_bit(R5_Wantread, &dev->flags);
2206                                         if (!test_and_set_bit(
2207                                                 STRIPE_OP_IO, &sh->ops.pending))
2208                                                 sh->ops.count++;
2209                                         s->locked++;
2210                                 } else {
2211                                         set_bit(STRIPE_DELAYED, &sh->state);
2212                                         set_bit(STRIPE_HANDLE, &sh->state);
2213                                 }
2214                         }
2215                 }
2216         if (rcw <= rmw && rcw > 0)
2217                 /* want reconstruct write, but need to get some data */
2218                 for (i = disks; i--; ) {
2219                         struct r5dev *dev = &sh->dev[i];
2220                         if (!test_bit(R5_OVERWRITE, &dev->flags) &&
2221                             i != sh->pd_idx &&
2222                             !test_bit(R5_LOCKED, &dev->flags) &&
2223                             !(test_bit(R5_UPTODATE, &dev->flags) ||
2224                             test_bit(R5_Wantcompute, &dev->flags)) &&
2225                             test_bit(R5_Insync, &dev->flags)) {
2226                                 if (
2227                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2228                                         pr_debug("Read_old block "
2229                                                 "%d for Reconstruct\n", i);
2230                                         set_bit(R5_LOCKED, &dev->flags);
2231                                         set_bit(R5_Wantread, &dev->flags);
2232                                         if (!test_and_set_bit(
2233                                                 STRIPE_OP_IO, &sh->ops.pending))
2234                                                 sh->ops.count++;
2235                                         s->locked++;
2236                                 } else {
2237                                         set_bit(STRIPE_DELAYED, &sh->state);
2238                                         set_bit(STRIPE_HANDLE, &sh->state);
2239                                 }
2240                         }
2241                 }
2242         /* now if nothing is locked, and if we have enough data,
2243          * we can start a write request
2244          */
2245         /* since handle_stripe can be called at any time we need to handle the
2246          * case where a compute block operation has been submitted and then a
2247          * subsequent call wants to start a write request.  raid5_run_ops only
2248          * handles the case where compute block and postxor are requested
2249          * simultaneously.  If this is not the case then new writes need to be
2250          * held off until the compute completes.
2251          */
2252         if ((s->req_compute ||
2253             !test_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.pending)) &&
2254                 (s->locked == 0 && (rcw == 0 || rmw == 0) &&
2255                 !test_bit(STRIPE_BIT_DELAY, &sh->state)))
2256                 s->locked += handle_write_operations5(sh, rcw == 0, 0);
2257 }
2258
2259 static void handle_issuing_new_write_requests6(raid5_conf_t *conf,
2260                 struct stripe_head *sh, struct stripe_head_state *s,
2261                 struct r6_state *r6s, int disks)
2262 {
2263         int rcw = 0, must_compute = 0, pd_idx = sh->pd_idx, i;
2264         int qd_idx = r6s->qd_idx;
2265         for (i = disks; i--; ) {
2266                 struct r5dev *dev = &sh->dev[i];
2267                 /* Would I have to read this buffer for reconstruct_write */
2268                 if (!test_bit(R5_OVERWRITE, &dev->flags)
2269                     && i != pd_idx && i != qd_idx
2270                     && (!test_bit(R5_LOCKED, &dev->flags)
2271                             ) &&
2272                     !test_bit(R5_UPTODATE, &dev->flags)) {
2273                         if (test_bit(R5_Insync, &dev->flags)) rcw++;
2274                         else {
2275                                 pr_debug("raid6: must_compute: "
2276                                         "disk %d flags=%#lx\n", i, dev->flags);
2277                                 must_compute++;
2278                         }
2279                 }
2280         }
2281         pr_debug("for sector %llu, rcw=%d, must_compute=%d\n",
2282                (unsigned long long)sh->sector, rcw, must_compute);
2283         set_bit(STRIPE_HANDLE, &sh->state);
2284
2285         if (rcw > 0)
2286                 /* want reconstruct write, but need to get some data */
2287                 for (i = disks; i--; ) {
2288                         struct r5dev *dev = &sh->dev[i];
2289                         if (!test_bit(R5_OVERWRITE, &dev->flags)
2290                             && !(s->failed == 0 && (i == pd_idx || i == qd_idx))
2291                             && !test_bit(R5_LOCKED, &dev->flags) &&
2292                             !test_bit(R5_UPTODATE, &dev->flags) &&
2293                             test_bit(R5_Insync, &dev->flags)) {
2294                                 if (
2295                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2296                                         pr_debug("Read_old stripe %llu "
2297                                                 "block %d for Reconstruct\n",
2298                                              (unsigned long long)sh->sector, i);
2299                                         set_bit(R5_LOCKED, &dev->flags);
2300                                         set_bit(R5_Wantread, &dev->flags);
2301                                         s->locked++;
2302                                 } else {
2303                                         pr_debug("Request delayed stripe %llu "
2304                                                 "block %d for Reconstruct\n",
2305                                              (unsigned long long)sh->sector, i);
2306                                         set_bit(STRIPE_DELAYED, &sh->state);
2307                                         set_bit(STRIPE_HANDLE, &sh->state);
2308                                 }
2309                         }
2310                 }
2311         /* now if nothing is locked, and if we have enough data, we can start a
2312          * write request
2313          */
2314         if (s->locked == 0 && rcw == 0 &&
2315             !test_bit(STRIPE_BIT_DELAY, &sh->state)) {
2316                 if (must_compute > 0) {
2317                         /* We have failed blocks and need to compute them */
2318                         switch (s->failed) {
2319                         case 0:
2320                                 BUG();
2321                         case 1:
2322                                 compute_block_1(sh, r6s->failed_num[0], 0);
2323                                 break;
2324                         case 2:
2325                                 compute_block_2(sh, r6s->failed_num[0],
2326                                                 r6s->failed_num[1]);
2327                                 break;
2328                         default: /* This request should have been failed? */
2329                                 BUG();
2330                         }
2331                 }
2332
2333                 pr_debug("Computing parity for stripe %llu\n",
2334                         (unsigned long long)sh->sector);
2335                 compute_parity6(sh, RECONSTRUCT_WRITE);
2336                 /* now every locked buffer is ready to be written */
2337                 for (i = disks; i--; )
2338                         if (test_bit(R5_LOCKED, &sh->dev[i].flags)) {
2339                                 pr_debug("Writing stripe %llu block %d\n",
2340                                        (unsigned long long)sh->sector, i);
2341                                 s->locked++;
2342                                 set_bit(R5_Wantwrite, &sh->dev[i].flags);
2343                         }
2344                 /* after a RECONSTRUCT_WRITE, the stripe MUST be in-sync */
2345                 set_bit(STRIPE_INSYNC, &sh->state);
2346
2347                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2348                         atomic_dec(&conf->preread_active_stripes);
2349                         if (atomic_read(&conf->preread_active_stripes) <
2350                             IO_THRESHOLD)
2351                                 md_wakeup_thread(conf->mddev->thread);
2352                 }
2353         }
2354 }
2355
2356 static void handle_parity_checks5(raid5_conf_t *conf, struct stripe_head *sh,
2357                                 struct stripe_head_state *s, int disks)
2358 {
2359         set_bit(STRIPE_HANDLE, &sh->state);
2360         /* Take one of the following actions:
2361          * 1/ start a check parity operation if (uptodate == disks)
2362          * 2/ finish a check parity operation and act on the result
2363          * 3/ skip to the writeback section if we previously
2364          *    initiated a recovery operation
2365          */
2366         if (s->failed == 0 &&
2367             !test_bit(STRIPE_OP_MOD_REPAIR_PD, &sh->ops.pending)) {
2368                 if (!test_and_set_bit(STRIPE_OP_CHECK, &sh->ops.pending)) {
2369                         BUG_ON(s->uptodate != disks);
2370                         clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
2371                         sh->ops.count++;
2372                         s->uptodate--;
2373                 } else if (
2374                        test_and_clear_bit(STRIPE_OP_CHECK, &sh->ops.complete)) {
2375                         clear_bit(STRIPE_OP_CHECK, &sh->ops.ack);
2376                         clear_bit(STRIPE_OP_CHECK, &sh->ops.pending);
2377
2378                         if (sh->ops.zero_sum_result == 0)
2379                                 /* parity is correct (on disc,
2380                                  * not in buffer any more)
2381                                  */
2382                                 set_bit(STRIPE_INSYNC, &sh->state);
2383                         else {
2384                                 conf->mddev->resync_mismatches +=
2385                                         STRIPE_SECTORS;
2386                                 if (test_bit(
2387                                      MD_RECOVERY_CHECK, &conf->mddev->recovery))
2388                                         /* don't try to repair!! */
2389                                         set_bit(STRIPE_INSYNC, &sh->state);
2390                                 else {
2391                                         set_bit(STRIPE_OP_COMPUTE_BLK,
2392                                                 &sh->ops.pending);
2393                                         set_bit(STRIPE_OP_MOD_REPAIR_PD,
2394                                                 &sh->ops.pending);
2395                                         set_bit(R5_Wantcompute,
2396                                                 &sh->dev[sh->pd_idx].flags);
2397                                         sh->ops.target = sh->pd_idx;
2398                                         sh->ops.count++;
2399                                         s->uptodate++;
2400                                 }
2401                         }
2402                 }
2403         }
2404
2405         /* check if we can clear a parity disk reconstruct */
2406         if (test_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.complete) &&
2407                 test_bit(STRIPE_OP_MOD_REPAIR_PD, &sh->ops.pending)) {
2408
2409                 clear_bit(STRIPE_OP_MOD_REPAIR_PD, &sh->ops.pending);
2410                 clear_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.complete);
2411                 clear_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.ack);
2412                 clear_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.pending);
2413         }
2414
2415         /* Wait for check parity and compute block operations to complete
2416          * before write-back
2417          */
2418         if (!test_bit(STRIPE_INSYNC, &sh->state) &&
2419                 !test_bit(STRIPE_OP_CHECK, &sh->ops.pending) &&
2420                 !test_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.pending)) {
2421                 struct r5dev *dev;
2422                 /* either failed parity check, or recovery is happening */
2423                 if (s->failed == 0)
2424                         s->failed_num = sh->pd_idx;
2425                 dev = &sh->dev[s->failed_num];
2426                 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
2427                 BUG_ON(s->uptodate != disks);
2428
2429                 set_bit(R5_LOCKED, &dev->flags);
2430                 set_bit(R5_Wantwrite, &dev->flags);
2431                 if (!test_and_set_bit(STRIPE_OP_IO, &sh->ops.pending))
2432                         sh->ops.count++;
2433
2434                 clear_bit(STRIPE_DEGRADED, &sh->state);
2435                 s->locked++;
2436                 set_bit(STRIPE_INSYNC, &sh->state);
2437         }
2438 }
2439
2440
2441 static void handle_parity_checks6(raid5_conf_t *conf, struct stripe_head *sh,
2442                                 struct stripe_head_state *s,
2443                                 struct r6_state *r6s, struct page *tmp_page,
2444                                 int disks)
2445 {
2446         int update_p = 0, update_q = 0;
2447         struct r5dev *dev;
2448         int pd_idx = sh->pd_idx;
2449         int qd_idx = r6s->qd_idx;
2450
2451         set_bit(STRIPE_HANDLE, &sh->state);
2452
2453         BUG_ON(s->failed > 2);
2454         BUG_ON(s->uptodate < disks);
2455         /* Want to check and possibly repair P and Q.
2456          * However there could be one 'failed' device, in which
2457          * case we can only check one of them, possibly using the
2458          * other to generate missing data
2459          */
2460
2461         /* If !tmp_page, we cannot do the calculations,
2462          * but as we have set STRIPE_HANDLE, we will soon be called
2463          * by stripe_handle with a tmp_page - just wait until then.
2464          */
2465         if (tmp_page) {
2466                 if (s->failed == r6s->q_failed) {
2467                         /* The only possible failed device holds 'Q', so it
2468                          * makes sense to check P (If anything else were failed,
2469                          * we would have used P to recreate it).
2470                          */
2471                         compute_block_1(sh, pd_idx, 1);
2472                         if (!page_is_zero(sh->dev[pd_idx].page)) {
2473                                 compute_block_1(sh, pd_idx, 0);
2474                                 update_p = 1;
2475                         }
2476                 }
2477                 if (!r6s->q_failed && s->failed < 2) {
2478                         /* q is not failed, and we didn't use it to generate
2479                          * anything, so it makes sense to check it
2480                          */
2481                         memcpy(page_address(tmp_page),
2482                                page_address(sh->dev[qd_idx].page),
2483                                STRIPE_SIZE);
2484                         compute_parity6(sh, UPDATE_PARITY);
2485                         if (memcmp(page_address(tmp_page),
2486                                    page_address(sh->dev[qd_idx].page),
2487                                    STRIPE_SIZE) != 0) {
2488                                 clear_bit(STRIPE_INSYNC, &sh->state);
2489                                 update_q = 1;
2490                         }
2491                 }
2492                 if (update_p || update_q) {
2493                         conf->mddev->resync_mismatches += STRIPE_SECTORS;
2494                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
2495                                 /* don't try to repair!! */
2496                                 update_p = update_q = 0;
2497                 }
2498
2499                 /* now write out any block on a failed drive,
2500                  * or P or Q if they need it
2501                  */
2502
2503                 if (s->failed == 2) {
2504                         dev = &sh->dev[r6s->failed_num[1]];
2505                         s->locked++;
2506                         set_bit(R5_LOCKED, &dev->flags);
2507                         set_bit(R5_Wantwrite, &dev->flags);
2508                 }
2509                 if (s->failed >= 1) {
2510                         dev = &sh->dev[r6s->failed_num[0]];
2511                         s->locked++;
2512                         set_bit(R5_LOCKED, &dev->flags);
2513                         set_bit(R5_Wantwrite, &dev->flags);
2514                 }
2515
2516                 if (update_p) {
2517                         dev = &sh->dev[pd_idx];
2518                         s->locked++;
2519                         set_bit(R5_LOCKED, &dev->flags);
2520                         set_bit(R5_Wantwrite, &dev->flags);
2521                 }
2522                 if (update_q) {
2523                         dev = &sh->dev[qd_idx];
2524                         s->locked++;
2525                         set_bit(R5_LOCKED, &dev->flags);
2526                         set_bit(R5_Wantwrite, &dev->flags);
2527                 }
2528                 clear_bit(STRIPE_DEGRADED, &sh->state);
2529
2530                 set_bit(STRIPE_INSYNC, &sh->state);
2531         }
2532 }
2533
2534 static void handle_stripe_expansion(raid5_conf_t *conf, struct stripe_head *sh,
2535                                 struct r6_state *r6s)
2536 {
2537         int i;
2538
2539         /* We have read all the blocks in this stripe and now we need to
2540          * copy some of them into a target stripe for expand.
2541          */
2542         struct dma_async_tx_descriptor *tx = NULL;
2543         clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
2544         for (i = 0; i < sh->disks; i++)
2545                 if (i != sh->pd_idx && (!r6s || i != r6s->qd_idx)) {
2546                         int dd_idx, pd_idx, j;
2547                         struct stripe_head *sh2;
2548
2549                         sector_t bn = compute_blocknr(sh, i);
2550                         sector_t s = raid5_compute_sector(bn, conf->raid_disks,
2551                                                 conf->raid_disks -
2552                                                 conf->max_degraded, &dd_idx,
2553                                                 &pd_idx, conf);
2554                         sh2 = get_active_stripe(conf, s, conf->raid_disks,
2555                                                 pd_idx, 1);
2556                         if (sh2 == NULL)
2557                                 /* so far only the early blocks of this stripe
2558                                  * have been requested.  When later blocks
2559                                  * get requested, we will try again
2560                                  */
2561                                 continue;
2562                         if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
2563                            test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
2564                                 /* must have already done this block */
2565                                 release_stripe(sh2);
2566                                 continue;
2567                         }
2568
2569                         /* place all the copies on one channel */
2570                         tx = async_memcpy(sh2->dev[dd_idx].page,
2571                                 sh->dev[i].page, 0, 0, STRIPE_SIZE,
2572                                 ASYNC_TX_DEP_ACK, tx, NULL, NULL);
2573
2574                         set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
2575                         set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
2576                         for (j = 0; j < conf->raid_disks; j++)
2577                                 if (j != sh2->pd_idx &&
2578                                     (!r6s || j != raid6_next_disk(sh2->pd_idx,
2579                                                                  sh2->disks)) &&
2580                                     !test_bit(R5_Expanded, &sh2->dev[j].flags))
2581                                         break;
2582                         if (j == conf->raid_disks) {
2583                                 set_bit(STRIPE_EXPAND_READY, &sh2->state);
2584                                 set_bit(STRIPE_HANDLE, &sh2->state);
2585                         }
2586                         release_stripe(sh2);
2587
2588                 }
2589         /* done submitting copies, wait for them to complete */
2590         if (tx) {
2591                 async_tx_ack(tx);
2592                 dma_wait_for_async_tx(tx);
2593         }
2594 }
2595
2596 /*
2597  * handle_stripe - do things to a stripe.
2598  *
2599  * We lock the stripe and then examine the state of various bits
2600  * to see what needs to be done.
2601  * Possible results:
2602  *    return some read request which now have data
2603  *    return some write requests which are safely on disc
2604  *    schedule a read on some buffers
2605  *    schedule a write of some buffers
2606  *    return confirmation of parity correctness
2607  *
2608  * buffers are taken off read_list or write_list, and bh_cache buffers
2609  * get BH_Lock set before the stripe lock is released.
2610  *
2611  */
2612
2613 static void handle_stripe5(struct stripe_head *sh)
2614 {
2615         raid5_conf_t *conf = sh->raid_conf;
2616         int disks = sh->disks, i;
2617         struct bio *return_bi = NULL;
2618         struct stripe_head_state s;
2619         struct r5dev *dev;
2620         unsigned long pending = 0;
2621
2622         memset(&s, 0, sizeof(s));
2623         pr_debug("handling stripe %llu, state=%#lx cnt=%d, pd_idx=%d "
2624                 "ops=%lx:%lx:%lx\n", (unsigned long long)sh->sector, sh->state,
2625                 atomic_read(&sh->count), sh->pd_idx,
2626                 sh->ops.pending, sh->ops.ack, sh->ops.complete);
2627
2628         spin_lock(&sh->lock);
2629         clear_bit(STRIPE_HANDLE, &sh->state);
2630         clear_bit(STRIPE_DELAYED, &sh->state);
2631
2632         s.syncing = test_bit(STRIPE_SYNCING, &sh->state);
2633         s.expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
2634         s.expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
2635         /* Now to look around and see what can be done */
2636
2637         /* clean-up completed biofill operations */
2638         if (test_bit(STRIPE_OP_BIOFILL, &sh->ops.complete)) {
2639                 clear_bit(STRIPE_OP_BIOFILL, &sh->ops.pending);
2640                 clear_bit(STRIPE_OP_BIOFILL, &sh->ops.ack);
2641                 clear_bit(STRIPE_OP_BIOFILL, &sh->ops.complete);
2642         }
2643
2644         rcu_read_lock();
2645         for (i=disks; i--; ) {
2646                 mdk_rdev_t *rdev;
2647                 struct r5dev *dev = &sh->dev[i];
2648                 clear_bit(R5_Insync, &dev->flags);
2649
2650                 pr_debug("check %d: state 0x%lx toread %p read %p write %p "
2651                         "written %p\n", i, dev->flags, dev->toread, dev->read,
2652                         dev->towrite, dev->written);
2653
2654                 /* maybe we can request a biofill operation
2655                  *
2656                  * new wantfill requests are only permitted while
2657                  * STRIPE_OP_BIOFILL is clear
2658                  */
2659                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
2660                         !test_bit(STRIPE_OP_BIOFILL, &sh->ops.pending))
2661                         set_bit(R5_Wantfill, &dev->flags);
2662
2663                 /* now count some things */
2664                 if (test_bit(R5_LOCKED, &dev->flags)) s.locked++;
2665                 if (test_bit(R5_UPTODATE, &dev->flags)) s.uptodate++;
2666                 if (test_bit(R5_Wantcompute, &dev->flags)) s.compute++;
2667
2668                 if (test_bit(R5_Wantfill, &dev->flags))
2669                         s.to_fill++;
2670                 else if (dev->toread)
2671                         s.to_read++;
2672                 if (dev->towrite) {
2673                         s.to_write++;
2674                         if (!test_bit(R5_OVERWRITE, &dev->flags))
2675                                 s.non_overwrite++;
2676                 }
2677                 if (dev->written)
2678                         s.written++;
2679                 rdev = rcu_dereference(conf->disks[i].rdev);
2680                 if (!rdev || !test_bit(In_sync, &rdev->flags)) {
2681                         /* The ReadError flag will just be confusing now */
2682                         clear_bit(R5_ReadError, &dev->flags);
2683                         clear_bit(R5_ReWrite, &dev->flags);
2684                 }
2685                 if (!rdev || !test_bit(In_sync, &rdev->flags)
2686                     || test_bit(R5_ReadError, &dev->flags)) {
2687                         s.failed++;
2688                         s.failed_num = i;
2689                 } else
2690                         set_bit(R5_Insync, &dev->flags);
2691         }
2692         rcu_read_unlock();
2693
2694         if (s.to_fill && !test_and_set_bit(STRIPE_OP_BIOFILL, &sh->ops.pending))
2695                 sh->ops.count++;
2696
2697         pr_debug("locked=%d uptodate=%d to_read=%d"
2698                 " to_write=%d failed=%d failed_num=%d\n",
2699                 s.locked, s.uptodate, s.to_read, s.to_write,
2700                 s.failed, s.failed_num);
2701         /* check if the array has lost two devices and, if so, some requests might
2702          * need to be failed
2703          */
2704         if (s.failed > 1 && s.to_read+s.to_write+s.written)
2705                 handle_requests_to_failed_array(conf, sh, &s, disks,
2706                                                 &return_bi);
2707         if (s.failed > 1 && s.syncing) {
2708                 md_done_sync(conf->mddev, STRIPE_SECTORS,0);
2709                 clear_bit(STRIPE_SYNCING, &sh->state);
2710                 s.syncing = 0;
2711         }
2712
2713         /* might be able to return some write requests if the parity block
2714          * is safe, or on a failed drive
2715          */
2716         dev = &sh->dev[sh->pd_idx];
2717         if ( s.written &&
2718              ((test_bit(R5_Insync, &dev->flags) &&
2719                !test_bit(R5_LOCKED, &dev->flags) &&
2720                test_bit(R5_UPTODATE, &dev->flags)) ||
2721                (s.failed == 1 && s.failed_num == sh->pd_idx)))
2722                 handle_completed_write_requests(conf, sh, disks, &return_bi);
2723
2724         /* Now we might consider reading some blocks, either to check/generate
2725          * parity, or to satisfy requests
2726          * or to load a block that is being partially written.
2727          */
2728         if (s.to_read || s.non_overwrite ||
2729             (s.syncing && (s.uptodate + s.compute < disks)) || s.expanding ||
2730             test_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.pending))
2731                 handle_issuing_new_read_requests5(sh, &s, disks);
2732
2733         /* Now we check to see if any write operations have recently
2734          * completed
2735          */
2736
2737         /* leave prexor set until postxor is done, allows us to distinguish
2738          * a rmw from a rcw during biodrain
2739          */
2740         if (test_bit(STRIPE_OP_PREXOR, &sh->ops.complete) &&
2741                 test_bit(STRIPE_OP_POSTXOR, &sh->ops.complete)) {
2742
2743                 clear_bit(STRIPE_OP_PREXOR, &sh->ops.complete);
2744                 clear_bit(STRIPE_OP_PREXOR, &sh->ops.ack);
2745                 clear_bit(STRIPE_OP_PREXOR, &sh->ops.pending);
2746
2747                 for (i = disks; i--; )
2748                         clear_bit(R5_Wantprexor, &sh->dev[i].flags);
2749         }
2750
2751         /* if only POSTXOR is set then this is an 'expand' postxor */
2752         if (test_bit(STRIPE_OP_BIODRAIN, &sh->ops.complete) &&
2753                 test_bit(STRIPE_OP_POSTXOR, &sh->ops.complete)) {
2754
2755                 clear_bit(STRIPE_OP_BIODRAIN, &sh->ops.complete);
2756                 clear_bit(STRIPE_OP_BIODRAIN, &sh->ops.ack);
2757                 clear_bit(STRIPE_OP_BIODRAIN, &sh->ops.pending);
2758
2759                 clear_bit(STRIPE_OP_POSTXOR, &sh->ops.complete);
2760                 clear_bit(STRIPE_OP_POSTXOR, &sh->ops.ack);
2761                 clear_bit(STRIPE_OP_POSTXOR, &sh->ops.pending);
2762
2763                 /* All the 'written' buffers and the parity block are ready to
2764                  * be written back to disk
2765                  */
2766                 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags));
2767                 for (i = disks; i--; ) {
2768                         dev = &sh->dev[i];
2769                         if (test_bit(R5_LOCKED, &dev->flags) &&
2770                                 (i == sh->pd_idx || dev->written)) {
2771                                 pr_debug("Writing block %d\n", i);
2772                                 set_bit(R5_Wantwrite, &dev->flags);
2773                                 if (!test_and_set_bit(
2774                                     STRIPE_OP_IO, &sh->ops.pending))
2775                                         sh->ops.count++;
2776                                 if (!test_bit(R5_Insync, &dev->flags) ||
2777                                     (i == sh->pd_idx && s.failed == 0))
2778                                         set_bit(STRIPE_INSYNC, &sh->state);
2779                         }
2780                 }
2781                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2782                         atomic_dec(&conf->preread_active_stripes);
2783                         if (atomic_read(&conf->preread_active_stripes) <
2784                                 IO_THRESHOLD)
2785                                 md_wakeup_thread(conf->mddev->thread);
2786                 }
2787         }
2788
2789         /* Now to consider new write requests and what else, if anything
2790          * should be read.  We do not handle new writes when:
2791          * 1/ A 'write' operation (copy+xor) is already in flight.
2792          * 2/ A 'check' operation is in flight, as it may clobber the parity
2793          *    block.
2794          */
2795         if (s.to_write && !test_bit(STRIPE_OP_POSTXOR, &sh->ops.pending) &&
2796                           !test_bit(STRIPE_OP_CHECK, &sh->ops.pending))
2797                 handle_issuing_new_write_requests5(conf, sh, &s, disks);
2798
2799         /* maybe we need to check and possibly fix the parity for this stripe
2800          * Any reads will already have been scheduled, so we just see if enough
2801          * data is available.  The parity check is held off while parity
2802          * dependent operations are in flight.
2803          */
2804         if ((s.syncing && s.locked == 0 &&
2805              !test_bit(STRIPE_OP_COMPUTE_BLK, &sh->ops.pending) &&
2806              !test_bit(STRIPE_INSYNC, &sh->state)) ||
2807               test_bit(STRIPE_OP_CHECK, &sh->ops.pending) ||
2808               test_bit(STRIPE_OP_MOD_REPAIR_PD, &sh->ops.pending))
2809                 handle_parity_checks5(conf, sh, &s, disks);
2810
2811         if (s.syncing && s.locked == 0 && test_bit(STRIPE_INSYNC, &sh->state)) {
2812                 md_done_sync(conf->mddev, STRIPE_SECTORS,1);
2813                 clear_bit(STRIPE_SYNCING, &sh->state);
2814         }
2815
2816         /* If the failed drive is just a ReadError, then we might need to progress
2817          * the repair/check process
2818          */
2819         if (s.failed == 1 && !conf->mddev->ro &&
2820             test_bit(R5_ReadError, &sh->dev[s.failed_num].flags)
2821             && !test_bit(R5_LOCKED, &sh->dev[s.failed_num].flags)
2822             && test_bit(R5_UPTODATE, &sh->dev[s.failed_num].flags)
2823                 ) {
2824                 dev = &sh->dev[s.failed_num];
2825                 if (!test_bit(R5_ReWrite, &dev->flags)) {
2826                         set_bit(R5_Wantwrite, &dev->flags);
2827                         if (!test_and_set_bit(STRIPE_OP_IO, &sh->ops.pending))
2828                                 sh->ops.count++;
2829                         set_bit(R5_ReWrite, &dev->flags);
2830                         set_bit(R5_LOCKED, &dev->flags);
2831                         s.locked++;
2832                 } else {
2833                         /* let's read it back */
2834                         set_bit(R5_Wantread, &dev->flags);
2835                         if (!test_and_set_bit(STRIPE_OP_IO, &sh->ops.pending))
2836                                 sh->ops.count++;
2837                         set_bit(R5_LOCKED, &dev->flags);
2838                         s.locked++;
2839                 }
2840         }
2841
2842         /* Finish postxor operations initiated by the expansion
2843          * process
2844          */
2845         if (test_bit(STRIPE_OP_POSTXOR, &sh->ops.complete) &&
2846                 !test_bit(STRIPE_OP_BIODRAIN, &sh->ops.pending)) {
2847
2848                 clear_bit(STRIPE_EXPANDING, &sh->state);
2849
2850                 clear_bit(STRIPE_OP_POSTXOR, &sh->ops.pending);
2851                 clear_bit(STRIPE_OP_POSTXOR, &sh->ops.ack);
2852                 clear_bit(STRIPE_OP_POSTXOR, &sh->ops.complete);
2853
2854                 for (i = conf->raid_disks; i--; ) {
2855                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
2856                         if (!test_and_set_bit(STRIPE_OP_IO, &sh->ops.pending))
2857                                 sh->ops.count++;
2858                 }
2859         }
2860
2861         if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
2862                 !test_bit(STRIPE_OP_POSTXOR, &sh->ops.pending)) {
2863                 /* Need to write out all blocks after computing parity */
2864                 sh->disks = conf->raid_disks;
2865                 sh->pd_idx = stripe_to_pdidx(sh->sector, conf,
2866                         conf->raid_disks);
2867                 s.locked += handle_write_operations5(sh, 1, 1);
2868         } else if (s.expanded &&
2869                 !test_bit(STRIPE_OP_POSTXOR, &sh->ops.pending)) {
2870                 clear_bit(STRIPE_EXPAND_READY, &sh->state);
2871                 atomic_dec(&conf->reshape_stripes);
2872                 wake_up(&conf->wait_for_overlap);
2873                 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
2874         }
2875
2876         if (s.expanding && s.locked == 0)
2877                 handle_stripe_expansion(conf, sh, NULL);
2878
2879         if (sh->ops.count)
2880                 pending = get_stripe_work(sh);
2881
2882         spin_unlock(&sh->lock);
2883
2884         if (pending)
2885                 raid5_run_ops(sh, pending);
2886
2887         return_io(return_bi);
2888
2889 }
2890
2891 static void handle_stripe6(struct stripe_head *sh, struct page *tmp_page)
2892 {
2893         raid6_conf_t *conf = sh->raid_conf;
2894         int disks = sh->disks;
2895         struct bio *return_bi = NULL;
2896         int i, pd_idx = sh->pd_idx;
2897         struct stripe_head_state s;
2898         struct r6_state r6s;
2899         struct r5dev *dev, *pdev, *qdev;
2900
2901         r6s.qd_idx = raid6_next_disk(pd_idx, disks);
2902         pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
2903                 "pd_idx=%d, qd_idx=%d\n",
2904                (unsigned long long)sh->sector, sh->state,
2905                atomic_read(&sh->count), pd_idx, r6s.qd_idx);
2906         memset(&s, 0, sizeof(s));
2907
2908         spin_lock(&sh->lock);
2909         clear_bit(STRIPE_HANDLE, &sh->state);
2910         clear_bit(STRIPE_DELAYED, &sh->state);
2911
2912         s.syncing = test_bit(STRIPE_SYNCING, &sh->state);
2913         s.expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
2914         s.expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
2915         /* Now to look around and see what can be done */
2916
2917         rcu_read_lock();
2918         for (i=disks; i--; ) {
2919                 mdk_rdev_t *rdev;
2920                 dev = &sh->dev[i];
2921                 clear_bit(R5_Insync, &dev->flags);
2922
2923                 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
2924                         i, dev->flags, dev->toread, dev->towrite, dev->written);
2925                 /* maybe we can reply to a read */
2926                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread) {
2927                         struct bio *rbi, *rbi2;
2928                         pr_debug("Return read for disc %d\n", i);
2929                         spin_lock_irq(&conf->device_lock);
2930                         rbi = dev->toread;
2931                         dev->toread = NULL;
2932                         if (test_and_clear_bit(R5_Overlap, &dev->flags))
2933                                 wake_up(&conf->wait_for_overlap);
2934                         spin_unlock_irq(&conf->device_lock);
2935                         while (rbi && rbi->bi_sector < dev->sector + STRIPE_SECTORS) {
2936                                 copy_data(0, rbi, dev->page, dev->sector);
2937                                 rbi2 = r5_next_bio(rbi, dev->sector);
2938                                 spin_lock_irq(&conf->device_lock);
2939                                 if (--rbi->bi_phys_segments == 0) {
2940                                         rbi->bi_next = return_bi;
2941                                         return_bi = rbi;
2942                                 }
2943                                 spin_unlock_irq(&conf->device_lock);
2944                                 rbi = rbi2;
2945                         }
2946                 }
2947
2948                 /* now count some things */
2949                 if (test_bit(R5_LOCKED, &dev->flags)) s.locked++;
2950                 if (test_bit(R5_UPTODATE, &dev->flags)) s.uptodate++;
2951
2952
2953                 if (dev->toread)
2954                         s.to_read++;
2955                 if (dev->towrite) {
2956                         s.to_write++;
2957                         if (!test_bit(R5_OVERWRITE, &dev->flags))
2958                                 s.non_overwrite++;
2959                 }
2960                 if (dev->written)
2961                         s.written++;
2962                 rdev = rcu_dereference(conf->disks[i].rdev);
2963                 if (!rdev || !test_bit(In_sync, &rdev->flags)) {
2964                         /* The ReadError flag will just be confusing now */
2965                         clear_bit(R5_ReadError, &dev->flags);
2966                         clear_bit(R5_ReWrite, &dev->flags);
2967                 }
2968                 if (!rdev || !test_bit(In_sync, &rdev->flags)
2969                     || test_bit(R5_ReadError, &dev->flags)) {
2970                         if (s.failed < 2)
2971                                 r6s.failed_num[s.failed] = i;
2972                         s.failed++;
2973                 } else
2974                         set_bit(R5_Insync, &dev->flags);
2975         }
2976         rcu_read_unlock();
2977         pr_debug("locked=%d uptodate=%d to_read=%d"
2978                " to_write=%d failed=%d failed_num=%d,%d\n",
2979                s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
2980                r6s.failed_num[0], r6s.failed_num[1]);
2981         /* check if the array has lost >2 devices and, if so, some requests
2982          * might need to be failed
2983          */
2984         if (s.failed > 2 && s.to_read+s.to_write+s.written)
2985                 handle_requests_to_failed_array(conf, sh, &s, disks,
2986                                                 &return_bi);
2987         if (s.failed > 2 && s.syncing) {
2988                 md_done_sync(conf->mddev, STRIPE_SECTORS,0);
2989                 clear_bit(STRIPE_SYNCING, &sh->state);
2990                 s.syncing = 0;
2991         }
2992
2993         /*
2994          * might be able to return some write requests if the parity blocks
2995          * are safe, or on a failed drive
2996          */
2997         pdev = &sh->dev[pd_idx];
2998         r6s.p_failed = (s.failed >= 1 && r6s.failed_num[0] == pd_idx)
2999                 || (s.failed >= 2 && r6s.failed_num[1] == pd_idx);
3000         qdev = &sh->dev[r6s.qd_idx];
3001         r6s.q_failed = (s.failed >= 1 && r6s.failed_num[0] == r6s.qd_idx)
3002                 || (s.failed >= 2 && r6s.failed_num[1] == r6s.qd_idx);
3003
3004         if ( s.written &&
3005              ( r6s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
3006                              && !test_bit(R5_LOCKED, &pdev->flags)
3007                              && test_bit(R5_UPTODATE, &pdev->flags)))) &&
3008              ( r6s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
3009                              && !test_bit(R5_LOCKED, &qdev->flags)
3010                              && test_bit(R5_UPTODATE, &qdev->flags)))))
3011                 handle_completed_write_requests(conf, sh, disks, &return_bi);
3012
3013         /* Now we might consider reading some blocks, either to check/generate
3014          * parity, or to satisfy requests
3015          * or to load a block that is being partially written.
3016          */
3017         if (s.to_read || s.non_overwrite || (s.to_write && s.failed) ||
3018             (s.syncing && (s.uptodate < disks)) || s.expanding)
3019                 handle_issuing_new_read_requests6(sh, &s, &r6s, disks);
3020
3021         /* now to consider writing and what else, if anything should be read */
3022         if (s.to_write)
3023                 handle_issuing_new_write_requests6(conf, sh, &s, &r6s, disks);
3024
3025         /* maybe we need to check and possibly fix the parity for this stripe
3026          * Any reads will already have been scheduled, so we just see if enough
3027          * data is available
3028          */
3029         if (s.syncing && s.locked == 0 && !test_bit(STRIPE_INSYNC, &sh->state))
3030                 handle_parity_checks6(conf, sh, &s, &r6s, tmp_page, disks);
3031
3032         if (s.syncing && s.locked == 0 && test_bit(STRIPE_INSYNC, &sh->state)) {
3033                 md_done_sync(conf->mddev, STRIPE_SECTORS,1);
3034                 clear_bit(STRIPE_SYNCING, &sh->state);
3035         }
3036
3037         /* If the failed drives are just a ReadError, then we might need
3038          * to progress the repair/check process
3039          */
3040         if (s.failed <= 2 && !conf->mddev->ro)
3041                 for (i = 0; i < s.failed; i++) {
3042                         dev = &sh->dev[r6s.failed_num[i]];
3043                         if (test_bit(R5_ReadError, &dev->flags)
3044                             && !test_bit(R5_LOCKED, &dev->flags)
3045                             && test_bit(R5_UPTODATE, &dev->flags)
3046                                 ) {
3047                                 if (!test_bit(R5_ReWrite, &dev->flags)) {
3048                                         set_bit(R5_Wantwrite, &dev->flags);
3049                                         set_bit(R5_ReWrite, &dev->flags);
3050                                         set_bit(R5_LOCKED, &dev->flags);
3051                                 } else {
3052                                         /* let's read it back */
3053                                         set_bit(R5_Wantread, &dev->flags);
3054                                         set_bit(R5_LOCKED, &dev->flags);
3055                                 }
3056                         }
3057                 }
3058
3059         if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state)) {
3060                 /* Need to write out all blocks after computing P&Q */
3061                 sh->disks = conf->raid_disks;
3062                 sh->pd_idx = stripe_to_pdidx(sh->sector, conf,
3063                                              conf->raid_disks);
3064                 compute_parity6(sh, RECONSTRUCT_WRITE);
3065                 for (i = conf->raid_disks ; i-- ;  ) {
3066                         set_bit(R5_LOCKED, &sh->dev[i].flags);
3067                         s.locked++;
3068                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
3069                 }
3070                 clear_bit(STRIPE_EXPANDING, &sh->state);
3071         } else if (s.expanded) {
3072                 clear_bit(STRIPE_EXPAND_READY, &sh->state);
3073                 atomic_dec(&conf->reshape_stripes);
3074                 wake_up(&conf->wait_for_overlap);
3075                 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3076         }
3077
3078         if (s.expanding && s.locked == 0)
3079                 handle_stripe_expansion(conf, sh, &r6s);
3080
3081         spin_unlock(&sh->lock);
3082
3083         return_io(return_bi);
3084
3085         for (i=disks; i-- ;) {
3086                 int rw;
3087                 struct bio *bi;
3088                 mdk_rdev_t *rdev;
3089                 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags))
3090                         rw = WRITE;
3091                 else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
3092                         rw = READ;
3093                 else
3094                         continue;
3095
3096                 bi = &sh->dev[i].req;
3097
3098                 bi->bi_rw = rw;
3099                 if (rw == WRITE)
3100                         bi->bi_end_io = raid5_end_write_request;
3101                 else
3102                         bi->bi_end_io = raid5_end_read_request;
3103
3104                 rcu_read_lock();
3105                 rdev = rcu_dereference(conf->disks[i].rdev);
3106                 if (rdev && test_bit(Faulty, &rdev->flags))
3107                         rdev = NULL;
3108                 if (rdev)
3109                         atomic_inc(&rdev->nr_pending);
3110                 rcu_read_unlock();
3111
3112                 if (rdev) {
3113                         if (s.syncing || s.expanding || s.expanded)
3114                                 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
3115
3116                         bi->bi_bdev = rdev->bdev;
3117                         pr_debug("for %llu schedule op %ld on disc %d\n",
3118                                 (unsigned long long)sh->sector, bi->bi_rw, i);
3119                         atomic_inc(&sh->count);
3120                         bi->bi_sector = sh->sector + rdev->data_offset;
3121                         bi->bi_flags = 1 << BIO_UPTODATE;
3122                         bi->bi_vcnt = 1;
3123                         bi->bi_max_vecs = 1;
3124                         bi->bi_idx = 0;
3125                         bi->bi_io_vec = &sh->dev[i].vec;
3126                         bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
3127                         bi->bi_io_vec[0].bv_offset = 0;
3128                         bi->bi_size = STRIPE_SIZE;
3129                         bi->bi_next = NULL;
3130                         if (rw == WRITE &&
3131                             test_bit(R5_ReWrite, &sh->dev[i].flags))
3132                                 atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
3133                         generic_make_request(bi);
3134                 } else {
3135                         if (rw == WRITE)
3136                                 set_bit(STRIPE_DEGRADED, &sh->state);
3137                         pr_debug("skip op %ld on disc %d for sector %llu\n",
3138                                 bi->bi_rw, i, (unsigned long long)sh->sector);
3139                         clear_bit(R5_LOCKED, &sh->dev[i].flags);
3140                         set_bit(STRIPE_HANDLE, &sh->state);
3141                 }
3142         }
3143 }
3144
3145 static void handle_stripe(struct stripe_head *sh, struct page *tmp_page)
3146 {
3147         if (sh->raid_conf->level == 6)
3148                 handle_stripe6(sh, tmp_page);
3149         else
3150                 handle_stripe5(sh);
3151 }
3152
3153
3154
3155 static void raid5_activate_delayed(raid5_conf_t *conf)
3156 {
3157         if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
3158                 while (!list_empty(&conf->delayed_list)) {
3159                         struct list_head *l = conf->delayed_list.next;
3160                         struct stripe_head *sh;
3161                         sh = list_entry(l, struct stripe_head, lru);
3162                         list_del_init(l);
3163                         clear_bit(STRIPE_DELAYED, &sh->state);
3164                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3165                                 atomic_inc(&conf->preread_active_stripes);
3166                         list_add_tail(&sh->lru, &conf->handle_list);
3167                 }
3168         }
3169 }
3170
3171 static void activate_bit_delay(raid5_conf_t *conf)
3172 {
3173         /* device_lock is held */
3174         struct list_head head;
3175         list_add(&head, &conf->bitmap_list);
3176         list_del_init(&conf->bitmap_list);
3177         while (!list_empty(&head)) {
3178                 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
3179                 list_del_init(&sh->lru);
3180                 atomic_inc(&sh->count);
3181                 __release_stripe(conf, sh);
3182         }
3183 }
3184
3185 static void unplug_slaves(mddev_t *mddev)
3186 {
3187         raid5_conf_t *conf = mddev_to_conf(mddev);
3188         int i;
3189
3190         rcu_read_lock();
3191         for (i=0; i<mddev->raid_disks; i++) {
3192                 mdk_rdev_t *rdev = rcu_dereference(conf->disks[i].rdev);
3193                 if (rdev && !test_bit(Faulty, &rdev->flags) && atomic_read(&rdev->nr_pending)) {
3194                         struct request_queue *r_queue = bdev_get_queue(rdev->bdev);
3195
3196                         atomic_inc(&rdev->nr_pending);
3197                         rcu_read_unlock();
3198
3199                         if (r_queue->unplug_fn)
3200                                 r_queue->unplug_fn(r_queue);
3201
3202                         rdev_dec_pending(rdev, mddev);
3203                         rcu_read_lock();
3204                 }
3205         }
3206         rcu_read_unlock();
3207 }
3208
3209 static void raid5_unplug_device(struct request_queue *q)
3210 {
3211         mddev_t *mddev = q->queuedata;
3212         raid5_conf_t *conf = mddev_to_conf(mddev);
3213         unsigned long flags;
3214
3215         spin_lock_irqsave(&conf->device_lock, flags);
3216
3217         if (blk_remove_plug(q)) {
3218                 conf->seq_flush++;
3219                 raid5_activate_delayed(conf);
3220         }
3221         md_wakeup_thread(mddev->thread);
3222
3223         spin_unlock_irqrestore(&conf->device_lock, flags);
3224
3225         unplug_slaves(mddev);
3226 }
3227
3228 static int raid5_issue_flush(struct request_queue *q, struct gendisk *disk,
3229                              sector_t *error_sector)
3230 {
3231         mddev_t *mddev = q->queuedata;
3232         raid5_conf_t *conf = mddev_to_conf(mddev);
3233         int i, ret = 0;
3234
3235         rcu_read_lock();
3236         for (i=0; i<mddev->raid_disks && ret == 0; i++) {
3237                 mdk_rdev_t *rdev = rcu_dereference(conf->disks[i].rdev);
3238                 if (rdev && !test_bit(Faulty, &rdev->flags)) {
3239                         struct block_device *bdev = rdev->bdev;
3240                         struct request_queue *r_queue = bdev_get_queue(bdev);
3241
3242                         if (!r_queue->issue_flush_fn)
3243                                 ret = -EOPNOTSUPP;
3244                         else {
3245                                 atomic_inc(&rdev->nr_pending);
3246                                 rcu_read_unlock();
3247                                 ret = r_queue->issue_flush_fn(r_queue, bdev->bd_disk,
3248                                                               error_sector);
3249                                 rdev_dec_pending(rdev, mddev);
3250                                 rcu_read_lock();
3251                         }
3252                 }
3253         }
3254         rcu_read_unlock();
3255         return ret;
3256 }
3257
3258 static int raid5_congested(void *data, int bits)
3259 {
3260         mddev_t *mddev = data;
3261         raid5_conf_t *conf = mddev_to_conf(mddev);
3262
3263         /* No difference between reads and writes.  Just check
3264          * how busy the stripe_cache is
3265          */
3266         if (conf->inactive_blocked)
3267                 return 1;
3268         if (conf->quiesce)
3269                 return 1;
3270         if (list_empty_careful(&conf->inactive_list))
3271                 return 1;
3272
3273         return 0;
3274 }
3275
3276 /* We want read requests to align with chunks where possible,
3277  * but write requests don't need to.
3278  */
3279 static int raid5_mergeable_bvec(struct request_queue *q, struct bio *bio, struct bio_vec *biovec)
3280 {
3281         mddev_t *mddev = q->queuedata;
3282         sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
3283         int max;
3284         unsigned int chunk_sectors = mddev->chunk_size >> 9;
3285         unsigned int bio_sectors = bio->bi_size >> 9;
3286
3287         if (bio_data_dir(bio) == WRITE)
3288                 return biovec->bv_len; /* always allow writes to be mergeable */
3289
3290         max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
3291         if (max < 0) max = 0;
3292         if (max <= biovec->bv_len && bio_sectors == 0)
3293                 return biovec->bv_len;
3294         else
3295                 return max;
3296 }
3297
3298
3299 static int in_chunk_boundary(mddev_t *mddev, struct bio *bio)
3300 {
3301         sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
3302         unsigned int chunk_sectors = mddev->chunk_size >> 9;
3303         unsigned int bio_sectors = bio->bi_size >> 9;
3304
3305         return  chunk_sectors >=
3306                 ((sector & (chunk_sectors - 1)) + bio_sectors);
3307 }
3308
3309 /*
3310  *  add bio to the retry LIFO  ( in O(1) ... we are in interrupt )
3311  *  later sampled by raid5d.
3312  */
3313 static void add_bio_to_retry(struct bio *bi,raid5_conf_t *conf)
3314 {
3315         unsigned long flags;
3316
3317         spin_lock_irqsave(&conf->device_lock, flags);
3318
3319         bi->bi_next = conf->retry_read_aligned_list;
3320         conf->retry_read_aligned_list = bi;
3321
3322         spin_unlock_irqrestore(&conf->device_lock, flags);
3323         md_wakeup_thread(conf->mddev->thread);
3324 }
3325
3326
3327 static struct bio *remove_bio_from_retry(raid5_conf_t *conf)
3328 {
3329         struct bio *bi;
3330
3331         bi = conf->retry_read_aligned;
3332         if (bi) {
3333                 conf->retry_read_aligned = NULL;
3334                 return bi;
3335         }
3336         bi = conf->retry_read_aligned_list;
3337         if(bi) {
3338                 conf->retry_read_aligned_list = bi->bi_next;
3339                 bi->bi_next = NULL;
3340                 bi->bi_phys_segments = 1; /* biased count of active stripes */
3341                 bi->bi_hw_segments = 0; /* count of processed stripes */
3342         }
3343
3344         return bi;
3345 }
3346
3347
3348 /*
3349  *  The "raid5_align_endio" should check if the read succeeded and if it
3350  *  did, call bio_endio on the original bio (having bio_put the new bio
3351  *  first).
3352  *  If the read failed..
3353  */
3354 static int raid5_align_endio(struct bio *bi, unsigned int bytes, int error)
3355 {
3356         struct bio* raid_bi  = bi->bi_private;
3357         mddev_t *mddev;
3358         raid5_conf_t *conf;
3359         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
3360         mdk_rdev_t *rdev;
3361
3362         if (bi->bi_size)
3363                 return 1;
3364         bio_put(bi);
3365
3366         mddev = raid_bi->bi_bdev->bd_disk->queue->queuedata;
3367         conf = mddev_to_conf(mddev);
3368         rdev = (void*)raid_bi->bi_next;
3369         raid_bi->bi_next = NULL;
3370
3371         rdev_dec_pending(rdev, conf->mddev);
3372
3373         if (!error && uptodate) {
3374                 bio_endio(raid_bi, bytes, 0);
3375                 if (atomic_dec_and_test(&conf->active_aligned_reads))
3376                         wake_up(&conf->wait_for_stripe);
3377                 return 0;
3378         }
3379
3380
3381         pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
3382
3383         add_bio_to_retry(raid_bi, conf);
3384         return 0;
3385 }
3386
3387 static int bio_fits_rdev(struct bio *bi)
3388 {
3389         struct request_queue *q = bdev_get_queue(bi->bi_bdev);
3390
3391         if ((bi->bi_size>>9) > q->max_sectors)
3392                 return 0;
3393         blk_recount_segments(q, bi);
3394         if (bi->bi_phys_segments > q->max_phys_segments ||
3395             bi->bi_hw_segments > q->max_hw_segments)
3396                 return 0;
3397
3398         if (q->merge_bvec_fn)
3399                 /* it's too hard to apply the merge_bvec_fn at this stage,
3400                  * just just give up
3401                  */
3402                 return 0;
3403
3404         return 1;
3405 }
3406
3407
3408 static int chunk_aligned_read(struct request_queue *q, struct bio * raid_bio)
3409 {
3410         mddev_t *mddev = q->queuedata;
3411         raid5_conf_t *conf = mddev_to_conf(mddev);
3412         const unsigned int raid_disks = conf->raid_disks;
3413         const unsigned int data_disks = raid_disks - conf->max_degraded;
3414         unsigned int dd_idx, pd_idx;
3415         struct bio* align_bi;
3416         mdk_rdev_t *rdev;
3417
3418         if (!in_chunk_boundary(mddev, raid_bio)) {
3419                 pr_debug("chunk_aligned_read : non aligned\n");
3420                 return 0;
3421         }
3422         /*
3423          * use bio_clone to make a copy of the bio
3424          */
3425         align_bi = bio_clone(raid_bio, GFP_NOIO);
3426         if (!align_bi)
3427                 return 0;
3428         /*
3429          *   set bi_end_io to a new function, and set bi_private to the
3430          *     original bio.
3431          */
3432         align_bi->bi_end_io  = raid5_align_endio;
3433         align_bi->bi_private = raid_bio;
3434         /*
3435          *      compute position
3436          */
3437         align_bi->bi_sector =  raid5_compute_sector(raid_bio->bi_sector,
3438                                         raid_disks,
3439                                         data_disks,
3440                                         &dd_idx,
3441                                         &pd_idx,
3442                                         conf);
3443
3444         rcu_read_lock();
3445         rdev = rcu_dereference(conf->disks[dd_idx].rdev);
3446         if (rdev && test_bit(In_sync, &rdev->flags)) {
3447                 atomic_inc(&rdev->nr_pending);
3448                 rcu_read_unlock();
3449                 raid_bio->bi_next = (void*)rdev;
3450                 align_bi->bi_bdev =  rdev->bdev;
3451                 align_bi->bi_flags &= ~(1 << BIO_SEG_VALID);
3452                 align_bi->bi_sector += rdev->data_offset;
3453
3454                 if (!bio_fits_rdev(align_bi)) {
3455                         /* too big in some way */
3456                         bio_put(align_bi);
3457                         rdev_dec_pending(rdev, mddev);
3458                         return 0;
3459                 }
3460
3461                 spin_lock_irq(&conf->device_lock);
3462                 wait_event_lock_irq(conf->wait_for_stripe,
3463                                     conf->quiesce == 0,
3464                                     conf->device_lock, /* nothing */);
3465                 atomic_inc(&conf->active_aligned_reads);
3466                 spin_unlock_irq(&conf->device_lock);
3467
3468                 generic_make_request(align_bi);
3469                 return 1;
3470         } else {
3471                 rcu_read_unlock();
3472                 bio_put(align_bi);
3473                 return 0;
3474         }
3475 }
3476
3477
3478 static int make_request(struct request_queue *q, struct bio * bi)
3479 {
3480         mddev_t *mddev = q->queuedata;
3481         raid5_conf_t *conf = mddev_to_conf(mddev);
3482         unsigned int dd_idx, pd_idx;
3483         sector_t new_sector;
3484         sector_t logical_sector, last_sector;
3485         struct stripe_head *sh;
3486         const int rw = bio_data_dir(bi);
3487         int remaining;
3488
3489         if (unlikely(bio_barrier(bi))) {
3490                 bio_endio(bi, bi->bi_size, -EOPNOTSUPP);
3491                 return 0;
3492         }
3493
3494         md_write_start(mddev, bi);
3495
3496         disk_stat_inc(mddev->gendisk, ios[rw]);
3497         disk_stat_add(mddev->gendisk, sectors[rw], bio_sectors(bi));
3498
3499         if (rw == READ &&
3500              mddev->reshape_position == MaxSector &&
3501              chunk_aligned_read(q,bi))
3502                 return 0;
3503
3504         logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
3505         last_sector = bi->bi_sector + (bi->bi_size>>9);
3506         bi->bi_next = NULL;
3507         bi->bi_phys_segments = 1;       /* over-loaded to count active stripes */
3508
3509         for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
3510                 DEFINE_WAIT(w);
3511                 int disks, data_disks;
3512
3513         retry:
3514                 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
3515                 if (likely(conf->expand_progress == MaxSector))
3516                         disks = conf->raid_disks;
3517                 else {
3518                         /* spinlock is needed as expand_progress may be
3519                          * 64bit on a 32bit platform, and so it might be
3520                          * possible to see a half-updated value
3521                          * Ofcourse expand_progress could change after
3522                          * the lock is dropped, so once we get a reference
3523                          * to the stripe that we think it is, we will have
3524                          * to check again.
3525                          */
3526                         spin_lock_irq(&conf->device_lock);
3527                         disks = conf->raid_disks;
3528                         if (logical_sector >= conf->expand_progress)
3529                                 disks = conf->previous_raid_disks;
3530                         else {
3531                                 if (logical_sector >= conf->expand_lo) {
3532                                         spin_unlock_irq(&conf->device_lock);
3533                                         schedule();
3534                                         goto retry;
3535                                 }
3536                         }
3537                         spin_unlock_irq(&conf->device_lock);
3538                 }
3539                 data_disks = disks - conf->max_degraded;
3540
3541                 new_sector = raid5_compute_sector(logical_sector, disks, data_disks,
3542                                                   &dd_idx, &pd_idx, conf);
3543                 pr_debug("raid5: make_request, sector %llu logical %llu\n",
3544                         (unsigned long long)new_sector, 
3545                         (unsigned long long)logical_sector);
3546
3547                 sh = get_active_stripe(conf, new_sector, disks, pd_idx, (bi->bi_rw&RWA_MASK));
3548                 if (sh) {
3549                         if (unlikely(conf->expand_progress != MaxSector)) {
3550                                 /* expansion might have moved on while waiting for a
3551                                  * stripe, so we must do the range check again.
3552                                  * Expansion could still move past after this
3553                                  * test, but as we are holding a reference to
3554                                  * 'sh', we know that if that happens,
3555                                  *  STRIPE_EXPANDING will get set and the expansion
3556                                  * won't proceed until we finish with the stripe.
3557                                  */
3558                                 int must_retry = 0;
3559                                 spin_lock_irq(&conf->device_lock);
3560                                 if (logical_sector <  conf->expand_progress &&
3561                                     disks == conf->previous_raid_disks)
3562                                         /* mismatch, need to try again */
3563                                         must_retry = 1;
3564                                 spin_unlock_irq(&conf->device_lock);
3565                                 if (must_retry) {
3566                                         release_stripe(sh);
3567                                         goto retry;
3568                                 }
3569                         }
3570                         /* FIXME what if we get a false positive because these
3571                          * are being updated.
3572                          */
3573                         if (logical_sector >= mddev->suspend_lo &&
3574                             logical_sector < mddev->suspend_hi) {
3575                                 release_stripe(sh);
3576                                 schedule();
3577                                 goto retry;
3578                         }
3579
3580                         if (test_bit(STRIPE_EXPANDING, &sh->state) ||
3581                             !add_stripe_bio(sh, bi, dd_idx, (bi->bi_rw&RW_MASK))) {
3582                                 /* Stripe is busy expanding or
3583                                  * add failed due to overlap.  Flush everything
3584                                  * and wait a while
3585                                  */
3586                                 raid5_unplug_device(mddev->queue);
3587                                 release_stripe(sh);
3588                                 schedule();
3589                                 goto retry;
3590                         }
3591                         finish_wait(&conf->wait_for_overlap, &w);
3592                         handle_stripe(sh, NULL);
3593                         release_stripe(sh);
3594                 } else {
3595                         /* cannot get stripe for read-ahead, just give-up */
3596                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
3597                         finish_wait(&conf->wait_for_overlap, &w);
3598                         break;
3599                 }
3600                         
3601         }
3602         spin_lock_irq(&conf->device_lock);
3603         remaining = --bi->bi_phys_segments;
3604         spin_unlock_irq(&conf->device_lock);
3605         if (remaining == 0) {
3606                 int bytes = bi->bi_size;
3607
3608                 if ( rw == WRITE )
3609                         md_write_end(mddev);
3610                 bi->bi_size = 0;
3611                 bi->bi_end_io(bi, bytes,
3612                               test_bit(BIO_UPTODATE, &bi->bi_flags)
3613                                 ? 0 : -EIO);
3614         }
3615         return 0;
3616 }
3617
3618 static sector_t reshape_request(mddev_t *mddev, sector_t sector_nr, int *skipped)
3619 {
3620         /* reshaping is quite different to recovery/resync so it is
3621          * handled quite separately ... here.
3622          *
3623          * On each call to sync_request, we gather one chunk worth of
3624          * destination stripes and flag them as expanding.
3625          * Then we find all the source stripes and request reads.
3626          * As the reads complete, handle_stripe will copy the data
3627          * into the destination stripe and release that stripe.
3628          */
3629         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
3630         struct stripe_head *sh;
3631         int pd_idx;
3632         sector_t first_sector, last_sector;
3633         int raid_disks = conf->previous_raid_disks;
3634         int data_disks = raid_disks - conf->max_degraded;
3635         int new_data_disks = conf->raid_disks - conf->max_degraded;
3636         int i;
3637         int dd_idx;
3638         sector_t writepos, safepos, gap;
3639
3640         if (sector_nr == 0 &&
3641             conf->expand_progress != 0) {
3642                 /* restarting in the middle, skip the initial sectors */
3643                 sector_nr = conf->expand_progress;
3644                 sector_div(sector_nr, new_data_disks);
3645                 *skipped = 1;
3646                 return sector_nr;
3647         }
3648
3649         /* we update the metadata when there is more than 3Meg
3650          * in the block range (that is rather arbitrary, should
3651          * probably be time based) or when the data about to be
3652          * copied would over-write the source of the data at
3653          * the front of the range.
3654          * i.e. one new_stripe forward from expand_progress new_maps
3655          * to after where expand_lo old_maps to
3656          */
3657         writepos = conf->expand_progress +
3658                 conf->chunk_size/512*(new_data_disks);
3659         sector_div(writepos, new_data_disks);
3660         safepos = conf->expand_lo;
3661         sector_div(safepos, data_disks);
3662         gap = conf->expand_progress - conf->expand_lo;
3663
3664         if (writepos >= safepos ||
3665             gap > (new_data_disks)*3000*2 /*3Meg*/) {
3666                 /* Cannot proceed until we've updated the superblock... */
3667                 wait_event(conf->wait_for_overlap,
3668                            atomic_read(&conf->reshape_stripes)==0);
3669                 mddev->reshape_position = conf->expand_progress;
3670                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
3671                 md_wakeup_thread(mddev->thread);
3672                 wait_event(mddev->sb_wait, mddev->flags == 0 ||
3673                            kthread_should_stop());
3674                 spin_lock_irq(&conf->device_lock);
3675                 conf->expand_lo = mddev->reshape_position;
3676                 spin_unlock_irq(&conf->device_lock);
3677                 wake_up(&conf->wait_for_overlap);
3678         }
3679
3680         for (i=0; i < conf->chunk_size/512; i+= STRIPE_SECTORS) {
3681                 int j;
3682                 int skipped = 0;
3683                 pd_idx = stripe_to_pdidx(sector_nr+i, conf, conf->raid_disks);
3684                 sh = get_active_stripe(conf, sector_nr+i,
3685                                        conf->raid_disks, pd_idx, 0);
3686                 set_bit(STRIPE_EXPANDING, &sh->state);
3687                 atomic_inc(&conf->reshape_stripes);
3688                 /* If any of this stripe is beyond the end of the old
3689                  * array, then we need to zero those blocks
3690                  */
3691                 for (j=sh->disks; j--;) {
3692                         sector_t s;
3693                         if (j == sh->pd_idx)
3694                                 continue;
3695                         if (conf->level == 6 &&
3696                             j == raid6_next_disk(sh->pd_idx, sh->disks))
3697                                 continue;
3698                         s = compute_blocknr(sh, j);
3699                         if (s < (mddev->array_size<<1)) {
3700                                 skipped = 1;
3701                                 continue;
3702                         }
3703                         memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
3704                         set_bit(R5_Expanded, &sh->dev[j].flags);
3705                         set_bit(R5_UPTODATE, &sh->dev[j].flags);
3706                 }
3707                 if (!skipped) {
3708                         set_bit(STRIPE_EXPAND_READY, &sh->state);
3709                         set_bit(STRIPE_HANDLE, &sh->state);
3710                 }
3711                 release_stripe(sh);
3712         }
3713         spin_lock_irq(&conf->device_lock);
3714         conf->expand_progress = (sector_nr + i) * new_data_disks;
3715         spin_unlock_irq(&conf->device_lock);
3716         /* Ok, those stripe are ready. We can start scheduling
3717          * reads on the source stripes.
3718          * The source stripes are determined by mapping the first and last
3719          * block on the destination stripes.
3720          */
3721         first_sector =
3722                 raid5_compute_sector(sector_nr*(new_data_disks),
3723                                      raid_disks, data_disks,
3724                                      &dd_idx, &pd_idx, conf);
3725         last_sector =
3726                 raid5_compute_sector((sector_nr+conf->chunk_size/512)
3727                                      *(new_data_disks) -1,
3728                                      raid_disks, data_disks,
3729                                      &dd_idx, &pd_idx, conf);
3730         if (last_sector >= (mddev->size<<1))
3731                 last_sector = (mddev->size<<1)-1;
3732         while (first_sector <= last_sector) {
3733                 pd_idx = stripe_to_pdidx(first_sector, conf,
3734                                          conf->previous_raid_disks);
3735                 sh = get_active_stripe(conf, first_sector,
3736                                        conf->previous_raid_disks, pd_idx, 0);
3737                 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3738                 set_bit(STRIPE_HANDLE, &sh->state);
3739                 release_stripe(sh);
3740                 first_sector += STRIPE_SECTORS;
3741         }
3742         return conf->chunk_size>>9;
3743 }
3744
3745 /* FIXME go_faster isn't used */
3746 static inline sector_t sync_request(mddev_t *mddev, sector_t sector_nr, int *skipped, int go_faster)
3747 {
3748         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
3749         struct stripe_head *sh;
3750         int pd_idx;
3751         int raid_disks = conf->raid_disks;
3752         sector_t max_sector = mddev->size << 1;
3753         int sync_blocks;
3754         int still_degraded = 0;
3755         int i;
3756
3757         if (sector_nr >= max_sector) {
3758                 /* just being told to finish up .. nothing much to do */
3759                 unplug_slaves(mddev);
3760                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
3761                         end_reshape(conf);
3762                         return 0;
3763                 }
3764
3765                 if (mddev->curr_resync < max_sector) /* aborted */
3766                         bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
3767                                         &sync_blocks, 1);
3768                 else /* completed sync */
3769                         conf->fullsync = 0;
3770                 bitmap_close_sync(mddev->bitmap);
3771
3772                 return 0;
3773         }
3774
3775         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
3776                 return reshape_request(mddev, sector_nr, skipped);
3777
3778         /* if there is too many failed drives and we are trying
3779          * to resync, then assert that we are finished, because there is
3780          * nothing we can do.
3781          */
3782         if (mddev->degraded >= conf->max_degraded &&
3783             test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
3784                 sector_t rv = (mddev->size << 1) - sector_nr;
3785                 *skipped = 1;
3786                 return rv;
3787         }
3788         if (!bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
3789             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
3790             !conf->fullsync && sync_blocks >= STRIPE_SECTORS) {
3791                 /* we can skip this block, and probably more */
3792                 sync_blocks /= STRIPE_SECTORS;
3793                 *skipped = 1;
3794                 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
3795         }
3796
3797         pd_idx = stripe_to_pdidx(sector_nr, conf, raid_disks);
3798         sh = get_active_stripe(conf, sector_nr, raid_disks, pd_idx, 1);
3799         if (sh == NULL) {
3800                 sh = get_active_stripe(conf, sector_nr, raid_disks, pd_idx, 0);
3801                 /* make sure we don't swamp the stripe cache if someone else
3802                  * is trying to get access
3803                  */
3804                 schedule_timeout_uninterruptible(1);
3805         }
3806         /* Need to check if array will still be degraded after recovery/resync
3807          * We don't need to check the 'failed' flag as when that gets set,
3808          * recovery aborts.
3809          */
3810         for (i=0; i<mddev->raid_disks; i++)
3811                 if (conf->disks[i].rdev == NULL)
3812                         still_degraded = 1;
3813
3814         bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
3815
3816         spin_lock(&sh->lock);
3817         set_bit(STRIPE_SYNCING, &sh->state);
3818         clear_bit(STRIPE_INSYNC, &sh->state);
3819         spin_unlock(&sh->lock);
3820
3821         handle_stripe(sh, NULL);
3822         release_stripe(sh);
3823
3824         return STRIPE_SECTORS;
3825 }
3826
3827 static int  retry_aligned_read(raid5_conf_t *conf, struct bio *raid_bio)
3828 {
3829         /* We may not be able to submit a whole bio at once as there
3830          * may not be enough stripe_heads available.
3831          * We cannot pre-allocate enough stripe_heads as we may need
3832          * more than exist in the cache (if we allow ever large chunks).
3833          * So we do one stripe head at a time and record in
3834          * ->bi_hw_segments how many have been done.
3835          *
3836          * We *know* that this entire raid_bio is in one chunk, so
3837          * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
3838          */
3839         struct stripe_head *sh;
3840         int dd_idx, pd_idx;
3841         sector_t sector, logical_sector, last_sector;
3842         int scnt = 0;
3843         int remaining;
3844         int handled = 0;
3845
3846         logical_sector = raid_bio->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
3847         sector = raid5_compute_sector(  logical_sector,
3848                                         conf->raid_disks,
3849                                         conf->raid_disks - conf->max_degraded,
3850                                         &dd_idx,
3851                                         &pd_idx,
3852                                         conf);
3853         last_sector = raid_bio->bi_sector + (raid_bio->bi_size>>9);
3854
3855         for (; logical_sector < last_sector;
3856              logical_sector += STRIPE_SECTORS,
3857                      sector += STRIPE_SECTORS,
3858                      scnt++) {
3859
3860                 if (scnt < raid_bio->bi_hw_segments)
3861                         /* already done this stripe */
3862                         continue;
3863
3864                 sh = get_active_stripe(conf, sector, conf->raid_disks, pd_idx, 1);
3865
3866                 if (!sh) {
3867                         /* failed to get a stripe - must wait */
3868                         raid_bio->bi_hw_segments = scnt;
3869                         conf->retry_read_aligned = raid_bio;
3870                         return handled;
3871                 }
3872
3873                 set_bit(R5_ReadError, &sh->dev[dd_idx].flags);
3874                 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0)) {
3875                         release_stripe(sh);
3876                         raid_bio->bi_hw_segments = scnt;
3877                         conf->retry_read_aligned = raid_bio;
3878                         return handled;
3879                 }
3880
3881                 handle_stripe(sh, NULL);
3882                 release_stripe(sh);
3883                 handled++;
3884         }
3885         spin_lock_irq(&conf->device_lock);
3886         remaining = --raid_bio->bi_phys_segments;
3887         spin_unlock_irq(&conf->device_lock);
3888         if (remaining == 0) {
3889                 int bytes = raid_bio->bi_size;
3890
3891                 raid_bio->bi_size = 0;
3892                 raid_bio->bi_end_io(raid_bio, bytes,
3893                               test_bit(BIO_UPTODATE, &raid_bio->bi_flags)
3894                                 ? 0 : -EIO);
3895         }
3896         if (atomic_dec_and_test(&conf->active_aligned_reads))
3897                 wake_up(&conf->wait_for_stripe);
3898         return handled;
3899 }
3900
3901
3902
3903 /*
3904  * This is our raid5 kernel thread.
3905  *
3906  * We scan the hash table for stripes which can be handled now.
3907  * During the scan, completed stripes are saved for us by the interrupt
3908  * handler, so that they will not have to wait for our next wakeup.
3909  */
3910 static void raid5d (mddev_t *mddev)
3911 {
3912         struct stripe_head *sh;
3913         raid5_conf_t *conf = mddev_to_conf(mddev);
3914         int handled;
3915
3916         pr_debug("+++ raid5d active\n");
3917
3918         md_check_recovery(mddev);
3919
3920         handled = 0;
3921         spin_lock_irq(&conf->device_lock);
3922         while (1) {
3923                 struct list_head *first;
3924                 struct bio *bio;
3925
3926                 if (conf->seq_flush != conf->seq_write) {
3927                         int seq = conf->seq_flush;
3928                         spin_unlock_irq(&conf->device_lock);
3929                         bitmap_unplug(mddev->bitmap);
3930                         spin_lock_irq(&conf->device_lock);
3931                         conf->seq_write = seq;
3932                         activate_bit_delay(conf);
3933                 }
3934
3935                 if (list_empty(&conf->handle_list) &&
3936                     atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD &&
3937                     !blk_queue_plugged(mddev->queue) &&
3938                     !list_empty(&conf->delayed_list))
3939                         raid5_activate_delayed(conf);
3940
3941                 while ((bio = remove_bio_from_retry(conf))) {
3942                         int ok;
3943                         spin_unlock_irq(&conf->device_lock);
3944                         ok = retry_aligned_read(conf, bio);
3945                         spin_lock_irq(&conf->device_lock);
3946                         if (!ok)
3947                                 break;
3948                         handled++;
3949                 }
3950
3951                 if (list_empty(&conf->handle_list)) {
3952                         async_tx_issue_pending_all();
3953                         break;
3954                 }
3955
3956                 first = conf->handle_list.next;
3957                 sh = list_entry(first, struct stripe_head, lru);
3958
3959                 list_del_init(first);
3960                 atomic_inc(&sh->count);
3961                 BUG_ON(atomic_read(&sh->count)!= 1);
3962                 spin_unlock_irq(&conf->device_lock);
3963                 
3964                 handled++;
3965                 handle_stripe(sh, conf->spare_page);
3966                 release_stripe(sh);
3967
3968                 spin_lock_irq(&conf->device_lock);
3969         }
3970         pr_debug("%d stripes handled\n", handled);
3971
3972         spin_unlock_irq(&conf->device_lock);
3973
3974         unplug_slaves(mddev);
3975
3976         pr_debug("--- raid5d inactive\n");
3977 }
3978
3979 static ssize_t
3980 raid5_show_stripe_cache_size(mddev_t *mddev, char *page)
3981 {
3982         raid5_conf_t *conf = mddev_to_conf(mddev);
3983         if (conf)
3984                 return sprintf(page, "%d\n", conf->max_nr_stripes);
3985         else
3986                 return 0;
3987 }
3988
3989 static ssize_t
3990 raid5_store_stripe_cache_size(mddev_t *mddev, const char *page, size_t len)
3991 {
3992         raid5_conf_t *conf = mddev_to_conf(mddev);
3993         char *end;
3994         int new;
3995         if (len >= PAGE_SIZE)
3996                 return -EINVAL;
3997         if (!conf)
3998                 return -ENODEV;
3999
4000         new = simple_strtoul(page, &end, 10);
4001         if (!*page || (*end && *end != '\n') )
4002                 return -EINVAL;
4003         if (new <= 16 || new > 32768)
4004                 return -EINVAL;
4005         while (new < conf->max_nr_stripes) {
4006                 if (drop_one_stripe(conf))
4007                         conf->max_nr_stripes--;
4008                 else
4009                         break;
4010         }
4011         md_allow_write(mddev);
4012         while (new > conf->max_nr_stripes) {
4013                 if (grow_one_stripe(conf))
4014                         conf->max_nr_stripes++;
4015                 else break;
4016         }
4017         return len;
4018 }
4019
4020 static struct md_sysfs_entry
4021 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
4022                                 raid5_show_stripe_cache_size,
4023                                 raid5_store_stripe_cache_size);
4024
4025 static ssize_t
4026 stripe_cache_active_show(mddev_t *mddev, char *page)
4027 {
4028         raid5_conf_t *conf = mddev_to_conf(mddev);
4029         if (conf)
4030                 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
4031         else
4032                 return 0;
4033 }
4034
4035 static struct md_sysfs_entry
4036 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
4037
4038 static struct attribute *raid5_attrs[] =  {
4039         &raid5_stripecache_size.attr,
4040         &raid5_stripecache_active.attr,
4041         NULL,
4042 };
4043 static struct attribute_group raid5_attrs_group = {
4044         .name = NULL,
4045         .attrs = raid5_attrs,
4046 };
4047
4048 static int run(mddev_t *mddev)
4049 {
4050         raid5_conf_t *conf;
4051         int raid_disk, memory;
4052         mdk_rdev_t *rdev;
4053         struct disk_info *disk;
4054         struct list_head *tmp;
4055         int working_disks = 0;
4056
4057         if (mddev->level != 5 && mddev->level != 4 && mddev->level != 6) {
4058                 printk(KERN_ERR "raid5: %s: raid level not set to 4/5/6 (%d)\n",
4059                        mdname(mddev), mddev->level);
4060                 return -EIO;
4061         }
4062
4063         if (mddev->reshape_position != MaxSector) {
4064                 /* Check that we can continue the reshape.
4065                  * Currently only disks can change, it must
4066                  * increase, and we must be past the point where
4067                  * a stripe over-writes itself
4068                  */
4069                 sector_t here_new, here_old;
4070                 int old_disks;
4071                 int max_degraded = (mddev->level == 5 ? 1 : 2);
4072
4073                 if (mddev->new_level != mddev->level ||
4074                     mddev->new_layout != mddev->layout ||
4075                     mddev->new_chunk != mddev->chunk_size) {
4076                         printk(KERN_ERR "raid5: %s: unsupported reshape "
4077                                "required - aborting.\n",
4078                                mdname(mddev));
4079                         return -EINVAL;
4080                 }
4081                 if (mddev->delta_disks <= 0) {
4082                         printk(KERN_ERR "raid5: %s: unsupported reshape "
4083                                "(reduce disks) required - aborting.\n",
4084                                mdname(mddev));
4085                         return -EINVAL;
4086                 }
4087                 old_disks = mddev->raid_disks - mddev->delta_disks;
4088                 /* reshape_position must be on a new-stripe boundary, and one
4089                  * further up in new geometry must map after here in old
4090                  * geometry.
4091                  */
4092                 here_new = mddev->reshape_position;
4093                 if (sector_div(here_new, (mddev->chunk_size>>9)*
4094                                (mddev->raid_disks - max_degraded))) {
4095                         printk(KERN_ERR "raid5: reshape_position not "
4096                                "on a stripe boundary\n");
4097                         return -EINVAL;
4098                 }
4099                 /* here_new is the stripe we will write to */
4100                 here_old = mddev->reshape_position;
4101                 sector_div(here_old, (mddev->chunk_size>>9)*
4102                            (old_disks-max_degraded));
4103                 /* here_old is the first stripe that we might need to read
4104                  * from */
4105                 if (here_new >= here_old) {
4106                         /* Reading from the same stripe as writing to - bad */
4107                         printk(KERN_ERR "raid5: reshape_position too early for "
4108                                "auto-recovery - aborting.\n");
4109                         return -EINVAL;
4110                 }
4111                 printk(KERN_INFO "raid5: reshape will continue\n");
4112                 /* OK, we should be able to continue; */
4113         }
4114
4115
4116         mddev->private = kzalloc(sizeof (raid5_conf_t), GFP_KERNEL);
4117         if ((conf = mddev->private) == NULL)
4118                 goto abort;
4119         if (mddev->reshape_position == MaxSector) {
4120                 conf->previous_raid_disks = conf->raid_disks = mddev->raid_disks;
4121         } else {
4122                 conf->raid_disks = mddev->raid_disks;
4123                 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
4124         }
4125
4126         conf->disks = kzalloc(conf->raid_disks * sizeof(struct disk_info),
4127                               GFP_KERNEL);
4128         if (!conf->disks)
4129                 goto abort;
4130
4131         conf->mddev = mddev;
4132
4133         if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
4134                 goto abort;
4135
4136         if (mddev->level == 6) {
4137                 conf->spare_page = alloc_page(GFP_KERNEL);
4138                 if (!conf->spare_page)
4139                         goto abort;
4140         }
4141         spin_lock_init(&conf->device_lock);
4142         init_waitqueue_head(&conf->wait_for_stripe);
4143         init_waitqueue_head(&conf->wait_for_overlap);
4144         INIT_LIST_HEAD(&conf->handle_list);
4145         INIT_LIST_HEAD(&conf->delayed_list);
4146         INIT_LIST_HEAD(&conf->bitmap_list);
4147         INIT_LIST_HEAD(&conf->inactive_list);
4148         atomic_set(&conf->active_stripes, 0);
4149         atomic_set(&conf->preread_active_stripes, 0);
4150         atomic_set(&conf->active_aligned_reads, 0);
4151
4152         pr_debug("raid5: run(%s) called.\n", mdname(mddev));
4153
4154         ITERATE_RDEV(mddev,rdev,tmp) {
4155                 raid_disk = rdev->raid_disk;
4156                 if (raid_disk >= conf->raid_disks
4157                     || raid_disk < 0)
4158                         continue;
4159                 disk = conf->disks + raid_disk;
4160
4161                 disk->rdev = rdev;
4162
4163                 if (test_bit(In_sync, &rdev->flags)) {
4164                         char b[BDEVNAME_SIZE];
4165                         printk(KERN_INFO "raid5: device %s operational as raid"
4166                                 " disk %d\n", bdevname(rdev->bdev,b),
4167                                 raid_disk);
4168                         working_disks++;
4169                 }
4170         }
4171
4172         /*
4173          * 0 for a fully functional array, 1 or 2 for a degraded array.
4174          */
4175         mddev->degraded = conf->raid_disks - working_disks;
4176         conf->mddev = mddev;
4177         conf->chunk_size = mddev->chunk_size;
4178         conf->level = mddev->level;
4179         if (conf->level == 6)
4180                 conf->max_degraded = 2;
4181         else
4182                 conf->max_degraded = 1;
4183         conf->algorithm = mddev->layout;
4184         conf->max_nr_stripes = NR_STRIPES;
4185         conf->expand_progress = mddev->reshape_position;
4186
4187         /* device size must be a multiple of chunk size */
4188         mddev->size &= ~(mddev->chunk_size/1024 -1);
4189         mddev->resync_max_sectors = mddev->size << 1;
4190
4191         if (conf->level == 6 && conf->raid_disks < 4) {
4192                 printk(KERN_ERR "raid6: not enough configured devices for %s (%d, minimum 4)\n",
4193                        mdname(mddev), conf->raid_disks);
4194                 goto abort;
4195         }
4196         if (!conf->chunk_size || conf->chunk_size % 4) {
4197                 printk(KERN_ERR "raid5: invalid chunk size %d for %s\n",
4198                         conf->chunk_size, mdname(mddev));
4199                 goto abort;
4200         }
4201         if (conf->algorithm > ALGORITHM_RIGHT_SYMMETRIC) {
4202                 printk(KERN_ERR 
4203                         "raid5: unsupported parity algorithm %d for %s\n",
4204                         conf->algorithm, mdname(mddev));
4205                 goto abort;
4206         }
4207         if (mddev->degraded > conf->max_degraded) {
4208                 printk(KERN_ERR "raid5: not enough operational devices for %s"
4209                         " (%d/%d failed)\n",
4210                         mdname(mddev), mddev->degraded, conf->raid_disks);
4211                 goto abort;
4212         }
4213
4214         if (mddev->degraded > 0 &&
4215             mddev->recovery_cp != MaxSector) {
4216                 if (mddev->ok_start_degraded)
4217                         printk(KERN_WARNING
4218                                "raid5: starting dirty degraded array: %s"
4219                                "- data corruption possible.\n",
4220                                mdname(mddev));
4221                 else {
4222                         printk(KERN_ERR
4223                                "raid5: cannot start dirty degraded array for %s\n",
4224                                mdname(mddev));
4225                         goto abort;
4226                 }
4227         }
4228
4229         {
4230                 mddev->thread = md_register_thread(raid5d, mddev, "%s_raid5");
4231                 if (!mddev->thread) {
4232                         printk(KERN_ERR 
4233                                 "raid5: couldn't allocate thread for %s\n",
4234                                 mdname(mddev));
4235                         goto abort;
4236                 }
4237         }
4238         memory = conf->max_nr_stripes * (sizeof(struct stripe_head) +
4239                  conf->raid_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
4240         if (grow_stripes(conf, conf->max_nr_stripes)) {
4241                 printk(KERN_ERR 
4242                         "raid5: couldn't allocate %dkB for buffers\n", memory);
4243                 shrink_stripes(conf);
4244                 md_unregister_thread(mddev->thread);
4245                 goto abort;
4246         } else
4247                 printk(KERN_INFO "raid5: allocated %dkB for %s\n",
4248                         memory, mdname(mddev));
4249
4250         if (mddev->degraded == 0)
4251                 printk("raid5: raid level %d set %s active with %d out of %d"
4252                         " devices, algorithm %d\n", conf->level, mdname(mddev), 
4253                         mddev->raid_disks-mddev->degraded, mddev->raid_disks,
4254                         conf->algorithm);
4255         else
4256                 printk(KERN_ALERT "raid5: raid level %d set %s active with %d"
4257                         " out of %d devices, algorithm %d\n", conf->level,
4258                         mdname(mddev), mddev->raid_disks - mddev->degraded,
4259                         mddev->raid_disks, conf->algorithm);
4260
4261         print_raid5_conf(conf);
4262
4263         if (conf->expand_progress != MaxSector) {
4264                 printk("...ok start reshape thread\n");
4265                 conf->expand_lo = conf->expand_progress;
4266                 atomic_set(&conf->reshape_stripes, 0);
4267                 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4268                 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4269                 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
4270                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
4271                 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
4272                                                         "%s_reshape");
4273         }
4274
4275         /* read-ahead size must cover two whole stripes, which is
4276          * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
4277          */
4278         {
4279                 int data_disks = conf->previous_raid_disks - conf->max_degraded;
4280                 int stripe = data_disks *
4281                         (mddev->chunk_size / PAGE_SIZE);
4282                 if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
4283                         mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
4284         }
4285
4286         /* Ok, everything is just fine now */
4287         if (sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
4288                 printk(KERN_WARNING
4289                        "raid5: failed to create sysfs attributes for %s\n",
4290                        mdname(mddev));
4291
4292         mddev->queue->unplug_fn = raid5_unplug_device;
4293         mddev->queue->issue_flush_fn = raid5_issue_flush;
4294         mddev->queue->backing_dev_info.congested_data = mddev;
4295         mddev->queue->backing_dev_info.congested_fn = raid5_congested;
4296
4297         mddev->array_size =  mddev->size * (conf->previous_raid_disks -
4298                                             conf->max_degraded);
4299
4300         blk_queue_merge_bvec(mddev->queue, raid5_mergeable_bvec);
4301
4302         return 0;
4303 abort:
4304         if (conf) {
4305                 print_raid5_conf(conf);
4306                 safe_put_page(conf->spare_page);
4307                 kfree(conf->disks);
4308                 kfree(conf->stripe_hashtbl);
4309                 kfree(conf);
4310         }
4311         mddev->private = NULL;
4312         printk(KERN_ALERT "raid5: failed to run raid set %s\n", mdname(mddev));
4313         return -EIO;
4314 }
4315
4316
4317
4318 static int stop(mddev_t *mddev)
4319 {
4320         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
4321
4322         md_unregister_thread(mddev->thread);
4323         mddev->thread = NULL;
4324         shrink_stripes(conf);
4325         kfree(conf->stripe_hashtbl);
4326         mddev->queue->backing_dev_info.congested_fn = NULL;
4327         blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
4328         sysfs_remove_group(&mddev->kobj, &raid5_attrs_group);
4329         kfree(conf->disks);
4330         kfree(conf);
4331         mddev->private = NULL;
4332         return 0;
4333 }
4334
4335 #ifdef DEBUG
4336 static void print_sh (struct seq_file *seq, struct stripe_head *sh)
4337 {
4338         int i;
4339
4340         seq_printf(seq, "sh %llu, pd_idx %d, state %ld.\n",
4341                    (unsigned long long)sh->sector, sh->pd_idx, sh->state);
4342         seq_printf(seq, "sh %llu,  count %d.\n",
4343                    (unsigned long long)sh->sector, atomic_read(&sh->count));
4344         seq_printf(seq, "sh %llu, ", (unsigned long long)sh->sector);
4345         for (i = 0; i < sh->disks; i++) {
4346                 seq_printf(seq, "(cache%d: %p %ld) ",
4347                            i, sh->dev[i].page, sh->dev[i].flags);
4348         }
4349         seq_printf(seq, "\n");
4350 }
4351
4352 static void printall (struct seq_file *seq, raid5_conf_t *conf)
4353 {
4354         struct stripe_head *sh;
4355         struct hlist_node *hn;
4356         int i;
4357
4358         spin_lock_irq(&conf->device_lock);
4359         for (i = 0; i < NR_HASH; i++) {
4360                 hlist_for_each_entry(sh, hn, &conf->stripe_hashtbl[i], hash) {
4361                         if (sh->raid_conf != conf)
4362                                 continue;
4363                         print_sh(seq, sh);
4364                 }
4365         }
4366         spin_unlock_irq(&conf->device_lock);
4367 }
4368 #endif
4369
4370 static void status (struct seq_file *seq, mddev_t *mddev)
4371 {
4372         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
4373         int i;
4374
4375         seq_printf (seq, " level %d, %dk chunk, algorithm %d", mddev->level, mddev->chunk_size >> 10, mddev->layout);
4376         seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
4377         for (i = 0; i < conf->raid_disks; i++)
4378                 seq_printf (seq, "%s",
4379                                conf->disks[i].rdev &&
4380                                test_bit(In_sync, &conf->disks[i].rdev->flags) ? "U" : "_");
4381         seq_printf (seq, "]");
4382 #ifdef DEBUG
4383         seq_printf (seq, "\n");
4384         printall(seq, conf);
4385 #endif
4386 }
4387
4388 static void print_raid5_conf (raid5_conf_t *conf)
4389 {
4390         int i;
4391         struct disk_info *tmp;
4392
4393         printk("RAID5 conf printout:\n");
4394         if (!conf) {
4395                 printk("(conf==NULL)\n");
4396                 return;
4397         }
4398         printk(" --- rd:%d wd:%d\n", conf->raid_disks,
4399                  conf->raid_disks - conf->mddev->degraded);
4400
4401         for (i = 0; i < conf->raid_disks; i++) {
4402                 char b[BDEVNAME_SIZE];
4403                 tmp = conf->disks + i;
4404                 if (tmp->rdev)
4405                 printk(" disk %d, o:%d, dev:%s\n",
4406                         i, !test_bit(Faulty, &tmp->rdev->flags),
4407                         bdevname(tmp->rdev->bdev,b));
4408         }
4409 }
4410
4411 static int raid5_spare_active(mddev_t *mddev)
4412 {
4413         int i;
4414         raid5_conf_t *conf = mddev->private;
4415         struct disk_info *tmp;
4416
4417         for (i = 0; i < conf->raid_disks; i++) {
4418                 tmp = conf->disks + i;
4419                 if (tmp->rdev
4420                     && !test_bit(Faulty, &tmp->rdev->flags)
4421                     && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
4422                         unsigned long flags;
4423                         spin_lock_irqsave(&conf->device_lock, flags);
4424                         mddev->degraded--;
4425                         spin_unlock_irqrestore(&conf->device_lock, flags);
4426                 }
4427         }
4428         print_raid5_conf(conf);
4429         return 0;
4430 }
4431
4432 static int raid5_remove_disk(mddev_t *mddev, int number)
4433 {
4434         raid5_conf_t *conf = mddev->private;
4435         int err = 0;
4436         mdk_rdev_t *rdev;
4437         struct disk_info *p = conf->disks + number;
4438
4439         print_raid5_conf(conf);
4440         rdev = p->rdev;
4441         if (rdev) {
4442                 if (test_bit(In_sync, &rdev->flags) ||
4443                     atomic_read(&rdev->nr_pending)) {
4444                         err = -EBUSY;
4445                         goto abort;
4446                 }
4447                 p->rdev = NULL;
4448                 synchronize_rcu();
4449                 if (atomic_read(&rdev->nr_pending)) {
4450                         /* lost the race, try later */
4451                         err = -EBUSY;
4452                         p->rdev = rdev;
4453                 }
4454         }
4455 abort:
4456
4457         print_raid5_conf(conf);
4458         return err;
4459 }
4460
4461 static int raid5_add_disk(mddev_t *mddev, mdk_rdev_t *rdev)
4462 {
4463         raid5_conf_t *conf = mddev->private;
4464         int found = 0;
4465         int disk;
4466         struct disk_info *p;
4467
4468         if (mddev->degraded > conf->max_degraded)
4469                 /* no point adding a device */
4470                 return 0;
4471
4472         /*
4473          * find the disk ... but prefer rdev->saved_raid_disk
4474          * if possible.
4475          */
4476         if (rdev->saved_raid_disk >= 0 &&
4477             conf->disks[rdev->saved_raid_disk].rdev == NULL)
4478                 disk = rdev->saved_raid_disk;
4479         else
4480                 disk = 0;
4481         for ( ; disk < conf->raid_disks; disk++)
4482                 if ((p=conf->disks + disk)->rdev == NULL) {
4483                         clear_bit(In_sync, &rdev->flags);
4484                         rdev->raid_disk = disk;
4485                         found = 1;
4486                         if (rdev->saved_raid_disk != disk)
4487                                 conf->fullsync = 1;
4488                         rcu_assign_pointer(p->rdev, rdev);
4489                         break;
4490                 }
4491         print_raid5_conf(conf);
4492         return found;
4493 }
4494
4495 static int raid5_resize(mddev_t *mddev, sector_t sectors)
4496 {
4497         /* no resync is happening, and there is enough space
4498          * on all devices, so we can resize.
4499          * We need to make sure resync covers any new space.
4500          * If the array is shrinking we should possibly wait until
4501          * any io in the removed space completes, but it hardly seems
4502          * worth it.
4503          */
4504         raid5_conf_t *conf = mddev_to_conf(mddev);
4505
4506         sectors &= ~((sector_t)mddev->chunk_size/512 - 1);
4507         mddev->array_size = (sectors * (mddev->raid_disks-conf->max_degraded))>>1;
4508         set_capacity(mddev->gendisk, mddev->array_size << 1);
4509         mddev->changed = 1;
4510         if (sectors/2  > mddev->size && mddev->recovery_cp == MaxSector) {
4511                 mddev->recovery_cp = mddev->size << 1;
4512                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4513         }
4514         mddev->size = sectors /2;
4515         mddev->resync_max_sectors = sectors;
4516         return 0;
4517 }
4518
4519 #ifdef CONFIG_MD_RAID5_RESHAPE
4520 static int raid5_check_reshape(mddev_t *mddev)
4521 {
4522         raid5_conf_t *conf = mddev_to_conf(mddev);
4523         int err;
4524
4525         if (mddev->delta_disks < 0 ||
4526             mddev->new_level != mddev->level)
4527                 return -EINVAL; /* Cannot shrink array or change level yet */
4528         if (mddev->delta_disks == 0)
4529                 return 0; /* nothing to do */
4530
4531         /* Can only proceed if there are plenty of stripe_heads.
4532          * We need a minimum of one full stripe,, and for sensible progress
4533          * it is best to have about 4 times that.
4534          * If we require 4 times, then the default 256 4K stripe_heads will
4535          * allow for chunk sizes up to 256K, which is probably OK.
4536          * If the chunk size is greater, user-space should request more
4537          * stripe_heads first.
4538          */
4539         if ((mddev->chunk_size / STRIPE_SIZE) * 4 > conf->max_nr_stripes ||
4540             (mddev->new_chunk / STRIPE_SIZE) * 4 > conf->max_nr_stripes) {
4541                 printk(KERN_WARNING "raid5: reshape: not enough stripes.  Needed %lu\n",
4542                        (mddev->chunk_size / STRIPE_SIZE)*4);
4543                 return -ENOSPC;
4544         }
4545
4546         err = resize_stripes(conf, conf->raid_disks + mddev->delta_disks);
4547         if (err)
4548                 return err;
4549
4550         if (mddev->degraded > conf->max_degraded)
4551                 return -EINVAL;
4552         /* looks like we might be able to manage this */
4553         return 0;
4554 }
4555
4556 static int raid5_start_reshape(mddev_t *mddev)
4557 {
4558         raid5_conf_t *conf = mddev_to_conf(mddev);
4559         mdk_rdev_t *rdev;
4560         struct list_head *rtmp;
4561         int spares = 0;
4562         int added_devices = 0;
4563         unsigned long flags;
4564
4565         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4566                 return -EBUSY;
4567
4568         ITERATE_RDEV(mddev, rdev, rtmp)
4569                 if (rdev->raid_disk < 0 &&
4570                     !test_bit(Faulty, &rdev->flags))
4571                         spares++;
4572
4573         if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
4574                 /* Not enough devices even to make a degraded array
4575                  * of that size
4576                  */
4577                 return -EINVAL;
4578
4579         atomic_set(&conf->reshape_stripes, 0);
4580         spin_lock_irq(&conf->device_lock);
4581         conf->previous_raid_disks = conf->raid_disks;
4582         conf->raid_disks += mddev->delta_disks;
4583         conf->expand_progress = 0;
4584         conf->expand_lo = 0;
4585         spin_unlock_irq(&conf->device_lock);
4586
4587         /* Add some new drives, as many as will fit.
4588          * We know there are enough to make the newly sized array work.
4589          */
4590         ITERATE_RDEV(mddev, rdev, rtmp)
4591                 if (rdev->raid_disk < 0 &&
4592                     !test_bit(Faulty, &rdev->flags)) {
4593                         if (raid5_add_disk(mddev, rdev)) {
4594                                 char nm[20];
4595                                 set_bit(In_sync, &rdev->flags);
4596                                 added_devices++;
4597                                 rdev->recovery_offset = 0;
4598                                 sprintf(nm, "rd%d", rdev->raid_disk);
4599                                 if (sysfs_create_link(&mddev->kobj,
4600                                                       &rdev->kobj, nm))
4601                                         printk(KERN_WARNING
4602                                                "raid5: failed to create "
4603                                                " link %s for %s\n",
4604                                                nm, mdname(mddev));
4605                         } else
4606                                 break;
4607                 }
4608
4609         spin_lock_irqsave(&conf->device_lock, flags);
4610         mddev->degraded = (conf->raid_disks - conf->previous_raid_disks) - added_devices;
4611         spin_unlock_irqrestore(&conf->device_lock, flags);
4612         mddev->raid_disks = conf->raid_disks;
4613         mddev->reshape_position = 0;
4614         set_bit(MD_CHANGE_DEVS, &mddev->flags);
4615
4616         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4617         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4618         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
4619         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
4620         mddev->sync_thread = md_register_thread(md_do_sync, mddev,
4621                                                 "%s_reshape");
4622         if (!mddev->sync_thread) {
4623                 mddev->recovery = 0;
4624                 spin_lock_irq(&conf->device_lock);
4625                 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
4626                 conf->expand_progress = MaxSector;
4627                 spin_unlock_irq(&conf->device_lock);
4628                 return -EAGAIN;
4629         }
4630         md_wakeup_thread(mddev->sync_thread);
4631         md_new_event(mddev);
4632         return 0;
4633 }
4634 #endif
4635
4636 static void end_reshape(raid5_conf_t *conf)
4637 {
4638         struct block_device *bdev;
4639
4640         if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
4641                 conf->mddev->array_size = conf->mddev->size *
4642                         (conf->raid_disks - conf->max_degraded);
4643                 set_capacity(conf->mddev->gendisk, conf->mddev->array_size << 1);
4644                 conf->mddev->changed = 1;
4645
4646                 bdev = bdget_disk(conf->mddev->gendisk, 0);
4647                 if (bdev) {
4648                         mutex_lock(&bdev->bd_inode->i_mutex);
4649                         i_size_write(bdev->bd_inode, (loff_t)conf->mddev->array_size << 10);
4650                         mutex_unlock(&bdev->bd_inode->i_mutex);
4651                         bdput(bdev);
4652                 }
4653                 spin_lock_irq(&conf->device_lock);
4654                 conf->expand_progress = MaxSector;
4655                 spin_unlock_irq(&conf->device_lock);
4656                 conf->mddev->reshape_position = MaxSector;
4657
4658                 /* read-ahead size must cover two whole stripes, which is
4659                  * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
4660                  */
4661                 {
4662                         int data_disks = conf->previous_raid_disks - conf->max_degraded;
4663                         int stripe = data_disks *
4664                                 (conf->mddev->chunk_size / PAGE_SIZE);
4665                         if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
4666                                 conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
4667                 }
4668         }
4669 }
4670
4671 static void raid5_quiesce(mddev_t *mddev, int state)
4672 {
4673         raid5_conf_t *conf = mddev_to_conf(mddev);
4674
4675         switch(state) {
4676         case 2: /* resume for a suspend */
4677                 wake_up(&conf->wait_for_overlap);
4678                 break;
4679
4680         case 1: /* stop all writes */
4681                 spin_lock_irq(&conf->device_lock);
4682                 conf->quiesce = 1;
4683                 wait_event_lock_irq(conf->wait_for_stripe,
4684                                     atomic_read(&conf->active_stripes) == 0 &&
4685                                     atomic_read(&conf->active_aligned_reads) == 0,
4686                                     conf->device_lock, /* nothing */);
4687                 spin_unlock_irq(&conf->device_lock);
4688                 break;
4689
4690         case 0: /* re-enable writes */
4691                 spin_lock_irq(&conf->device_lock);
4692                 conf->quiesce = 0;
4693                 wake_up(&conf->wait_for_stripe);
4694                 wake_up(&conf->wait_for_overlap);
4695                 spin_unlock_irq(&conf->device_lock);
4696                 break;
4697         }
4698 }
4699
4700 static struct mdk_personality raid6_personality =
4701 {
4702         .name           = "raid6",
4703         .level          = 6,
4704         .owner          = THIS_MODULE,
4705         .make_request   = make_request,
4706         .run            = run,
4707         .stop           = stop,
4708         .status         = status,
4709         .error_handler  = error,
4710         .hot_add_disk   = raid5_add_disk,
4711         .hot_remove_disk= raid5_remove_disk,
4712         .spare_active   = raid5_spare_active,
4713         .sync_request   = sync_request,
4714         .resize         = raid5_resize,
4715 #ifdef CONFIG_MD_RAID5_RESHAPE
4716         .check_reshape  = raid5_check_reshape,
4717         .start_reshape  = raid5_start_reshape,
4718 #endif
4719         .quiesce        = raid5_quiesce,
4720 };
4721 static struct mdk_personality raid5_personality =
4722 {
4723         .name           = "raid5",
4724         .level          = 5,
4725         .owner          = THIS_MODULE,
4726         .make_request   = make_request,
4727         .run            = run,
4728         .stop           = stop,
4729         .status         = status,
4730         .error_handler  = error,
4731         .hot_add_disk   = raid5_add_disk,
4732         .hot_remove_disk= raid5_remove_disk,
4733         .spare_active   = raid5_spare_active,
4734         .sync_request   = sync_request,
4735         .resize         = raid5_resize,
4736 #ifdef CONFIG_MD_RAID5_RESHAPE
4737         .check_reshape  = raid5_check_reshape,
4738         .start_reshape  = raid5_start_reshape,
4739 #endif
4740         .quiesce        = raid5_quiesce,
4741 };
4742
4743 static struct mdk_personality raid4_personality =
4744 {
4745         .name           = "raid4",
4746         .level          = 4,
4747         .owner          = THIS_MODULE,
4748         .make_request   = make_request,
4749         .run            = run,
4750         .stop           = stop,
4751         .status         = status,
4752         .error_handler  = error,
4753         .hot_add_disk   = raid5_add_disk,
4754         .hot_remove_disk= raid5_remove_disk,
4755         .spare_active   = raid5_spare_active,
4756         .sync_request   = sync_request,
4757         .resize         = raid5_resize,
4758 #ifdef CONFIG_MD_RAID5_RESHAPE
4759         .check_reshape  = raid5_check_reshape,
4760         .start_reshape  = raid5_start_reshape,
4761 #endif
4762         .quiesce        = raid5_quiesce,
4763 };
4764
4765 static int __init raid5_init(void)
4766 {
4767         int e;
4768
4769         e = raid6_select_algo();
4770         if ( e )
4771                 return e;
4772         register_md_personality(&raid6_personality);
4773         register_md_personality(&raid5_personality);
4774         register_md_personality(&raid4_personality);
4775         return 0;
4776 }
4777
4778 static void raid5_exit(void)
4779 {
4780         unregister_md_personality(&raid6_personality);
4781         unregister_md_personality(&raid5_personality);
4782         unregister_md_personality(&raid4_personality);
4783 }
4784
4785 module_init(raid5_init);
4786 module_exit(raid5_exit);
4787 MODULE_LICENSE("GPL");
4788 MODULE_ALIAS("md-personality-4"); /* RAID5 */
4789 MODULE_ALIAS("md-raid5");
4790 MODULE_ALIAS("md-raid4");
4791 MODULE_ALIAS("md-level-5");
4792 MODULE_ALIAS("md-level-4");
4793 MODULE_ALIAS("md-personality-8"); /* RAID6 */
4794 MODULE_ALIAS("md-raid6");
4795 MODULE_ALIAS("md-level-6");
4796
4797 /* This used to be two separate modules, they were: */
4798 MODULE_ALIAS("raid5");
4799 MODULE_ALIAS("raid6");