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