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