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