xref: /linux/drivers/md/raid5.c (revision c75c5ab575af7db707689cdbb5a5c458e9a034bb)
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->seq_write is the number of the last batch successfully written.
31  * conf->seq_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 seq_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/module.h>
51 #include <linux/async.h>
52 #include <linux/seq_file.h>
53 #include <linux/cpu.h>
54 #include <linux/slab.h>
55 #include <linux/ratelimit.h>
56 #include <trace/events/block.h>
57 
58 #include "md.h"
59 #include "raid5.h"
60 #include "raid0.h"
61 #include "bitmap.h"
62 
63 /*
64  * Stripe cache
65  */
66 
67 #define NR_STRIPES		256
68 #define STRIPE_SIZE		PAGE_SIZE
69 #define STRIPE_SHIFT		(PAGE_SHIFT - 9)
70 #define STRIPE_SECTORS		(STRIPE_SIZE>>9)
71 #define	IO_THRESHOLD		1
72 #define BYPASS_THRESHOLD	1
73 #define NR_HASH			(PAGE_SIZE / sizeof(struct hlist_head))
74 #define HASH_MASK		(NR_HASH - 1)
75 
76 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
77 {
78 	int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
79 	return &conf->stripe_hashtbl[hash];
80 }
81 
82 /* bio's attached to a stripe+device for I/O are linked together in bi_sector
83  * order without overlap.  There may be several bio's per stripe+device, and
84  * a bio could span several devices.
85  * When walking this list for a particular stripe+device, we must never proceed
86  * beyond a bio that extends past this device, as the next bio might no longer
87  * be valid.
88  * This function is used to determine the 'next' bio in the list, given the sector
89  * of the current stripe+device
90  */
91 static inline struct bio *r5_next_bio(struct bio *bio, sector_t sector)
92 {
93 	int sectors = bio->bi_size >> 9;
94 	if (bio->bi_sector + sectors < sector + STRIPE_SECTORS)
95 		return bio->bi_next;
96 	else
97 		return NULL;
98 }
99 
100 /*
101  * We maintain a biased count of active stripes in the bottom 16 bits of
102  * bi_phys_segments, and a count of processed stripes in the upper 16 bits
103  */
104 static inline int raid5_bi_processed_stripes(struct bio *bio)
105 {
106 	atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
107 	return (atomic_read(segments) >> 16) & 0xffff;
108 }
109 
110 static inline int raid5_dec_bi_active_stripes(struct bio *bio)
111 {
112 	atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
113 	return atomic_sub_return(1, segments) & 0xffff;
114 }
115 
116 static inline void raid5_inc_bi_active_stripes(struct bio *bio)
117 {
118 	atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
119 	atomic_inc(segments);
120 }
121 
122 static inline void raid5_set_bi_processed_stripes(struct bio *bio,
123 	unsigned int cnt)
124 {
125 	atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
126 	int old, new;
127 
128 	do {
129 		old = atomic_read(segments);
130 		new = (old & 0xffff) | (cnt << 16);
131 	} while (atomic_cmpxchg(segments, old, new) != old);
132 }
133 
134 static inline void raid5_set_bi_stripes(struct bio *bio, unsigned int cnt)
135 {
136 	atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
137 	atomic_set(segments, cnt);
138 }
139 
140 /* Find first data disk in a raid6 stripe */
141 static inline int raid6_d0(struct stripe_head *sh)
142 {
143 	if (sh->ddf_layout)
144 		/* ddf always start from first device */
145 		return 0;
146 	/* md starts just after Q block */
147 	if (sh->qd_idx == sh->disks - 1)
148 		return 0;
149 	else
150 		return sh->qd_idx + 1;
151 }
152 static inline int raid6_next_disk(int disk, int raid_disks)
153 {
154 	disk++;
155 	return (disk < raid_disks) ? disk : 0;
156 }
157 
158 /* When walking through the disks in a raid5, starting at raid6_d0,
159  * We need to map each disk to a 'slot', where the data disks are slot
160  * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
161  * is raid_disks-1.  This help does that mapping.
162  */
163 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
164 			     int *count, int syndrome_disks)
165 {
166 	int slot = *count;
167 
168 	if (sh->ddf_layout)
169 		(*count)++;
170 	if (idx == sh->pd_idx)
171 		return syndrome_disks;
172 	if (idx == sh->qd_idx)
173 		return syndrome_disks + 1;
174 	if (!sh->ddf_layout)
175 		(*count)++;
176 	return slot;
177 }
178 
179 static void return_io(struct bio *return_bi)
180 {
181 	struct bio *bi = return_bi;
182 	while (bi) {
183 
184 		return_bi = bi->bi_next;
185 		bi->bi_next = NULL;
186 		bi->bi_size = 0;
187 		trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
188 					 bi, 0);
189 		bio_endio(bi, 0);
190 		bi = return_bi;
191 	}
192 }
193 
194 static void print_raid5_conf (struct r5conf *conf);
195 
196 static int stripe_operations_active(struct stripe_head *sh)
197 {
198 	return sh->check_state || sh->reconstruct_state ||
199 	       test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
200 	       test_bit(STRIPE_COMPUTE_RUN, &sh->state);
201 }
202 
203 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh)
204 {
205 	BUG_ON(!list_empty(&sh->lru));
206 	BUG_ON(atomic_read(&conf->active_stripes)==0);
207 	if (test_bit(STRIPE_HANDLE, &sh->state)) {
208 		if (test_bit(STRIPE_DELAYED, &sh->state) &&
209 		    !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
210 			list_add_tail(&sh->lru, &conf->delayed_list);
211 		else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
212 			   sh->bm_seq - conf->seq_write > 0)
213 			list_add_tail(&sh->lru, &conf->bitmap_list);
214 		else {
215 			clear_bit(STRIPE_DELAYED, &sh->state);
216 			clear_bit(STRIPE_BIT_DELAY, &sh->state);
217 			list_add_tail(&sh->lru, &conf->handle_list);
218 		}
219 		md_wakeup_thread(conf->mddev->thread);
220 	} else {
221 		BUG_ON(stripe_operations_active(sh));
222 		if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
223 			if (atomic_dec_return(&conf->preread_active_stripes)
224 			    < IO_THRESHOLD)
225 				md_wakeup_thread(conf->mddev->thread);
226 		atomic_dec(&conf->active_stripes);
227 		if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
228 			list_add_tail(&sh->lru, &conf->inactive_list);
229 			wake_up(&conf->wait_for_stripe);
230 			if (conf->retry_read_aligned)
231 				md_wakeup_thread(conf->mddev->thread);
232 		}
233 	}
234 }
235 
236 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh)
237 {
238 	if (atomic_dec_and_test(&sh->count))
239 		do_release_stripe(conf, sh);
240 }
241 
242 static void release_stripe(struct stripe_head *sh)
243 {
244 	struct r5conf *conf = sh->raid_conf;
245 	unsigned long flags;
246 
247 	local_irq_save(flags);
248 	if (atomic_dec_and_lock(&sh->count, &conf->device_lock)) {
249 		do_release_stripe(conf, sh);
250 		spin_unlock(&conf->device_lock);
251 	}
252 	local_irq_restore(flags);
253 }
254 
255 static inline void remove_hash(struct stripe_head *sh)
256 {
257 	pr_debug("remove_hash(), stripe %llu\n",
258 		(unsigned long long)sh->sector);
259 
260 	hlist_del_init(&sh->hash);
261 }
262 
263 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
264 {
265 	struct hlist_head *hp = stripe_hash(conf, sh->sector);
266 
267 	pr_debug("insert_hash(), stripe %llu\n",
268 		(unsigned long long)sh->sector);
269 
270 	hlist_add_head(&sh->hash, hp);
271 }
272 
273 
274 /* find an idle stripe, make sure it is unhashed, and return it. */
275 static struct stripe_head *get_free_stripe(struct r5conf *conf)
276 {
277 	struct stripe_head *sh = NULL;
278 	struct list_head *first;
279 
280 	if (list_empty(&conf->inactive_list))
281 		goto out;
282 	first = conf->inactive_list.next;
283 	sh = list_entry(first, struct stripe_head, lru);
284 	list_del_init(first);
285 	remove_hash(sh);
286 	atomic_inc(&conf->active_stripes);
287 out:
288 	return sh;
289 }
290 
291 static void shrink_buffers(struct stripe_head *sh)
292 {
293 	struct page *p;
294 	int i;
295 	int num = sh->raid_conf->pool_size;
296 
297 	for (i = 0; i < num ; i++) {
298 		p = sh->dev[i].page;
299 		if (!p)
300 			continue;
301 		sh->dev[i].page = NULL;
302 		put_page(p);
303 	}
304 }
305 
306 static int grow_buffers(struct stripe_head *sh)
307 {
308 	int i;
309 	int num = sh->raid_conf->pool_size;
310 
311 	for (i = 0; i < num; i++) {
312 		struct page *page;
313 
314 		if (!(page = alloc_page(GFP_KERNEL))) {
315 			return 1;
316 		}
317 		sh->dev[i].page = page;
318 	}
319 	return 0;
320 }
321 
322 static void raid5_build_block(struct stripe_head *sh, int i, int previous);
323 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
324 			    struct stripe_head *sh);
325 
326 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
327 {
328 	struct r5conf *conf = sh->raid_conf;
329 	int i;
330 
331 	BUG_ON(atomic_read(&sh->count) != 0);
332 	BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
333 	BUG_ON(stripe_operations_active(sh));
334 
335 	pr_debug("init_stripe called, stripe %llu\n",
336 		(unsigned long long)sh->sector);
337 
338 	remove_hash(sh);
339 
340 	sh->generation = conf->generation - previous;
341 	sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
342 	sh->sector = sector;
343 	stripe_set_idx(sector, conf, previous, sh);
344 	sh->state = 0;
345 
346 
347 	for (i = sh->disks; i--; ) {
348 		struct r5dev *dev = &sh->dev[i];
349 
350 		if (dev->toread || dev->read || dev->towrite || dev->written ||
351 		    test_bit(R5_LOCKED, &dev->flags)) {
352 			printk(KERN_ERR "sector=%llx i=%d %p %p %p %p %d\n",
353 			       (unsigned long long)sh->sector, i, dev->toread,
354 			       dev->read, dev->towrite, dev->written,
355 			       test_bit(R5_LOCKED, &dev->flags));
356 			WARN_ON(1);
357 		}
358 		dev->flags = 0;
359 		raid5_build_block(sh, i, previous);
360 	}
361 	insert_hash(conf, sh);
362 }
363 
364 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
365 					 short generation)
366 {
367 	struct stripe_head *sh;
368 
369 	pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
370 	hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
371 		if (sh->sector == sector && sh->generation == generation)
372 			return sh;
373 	pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
374 	return NULL;
375 }
376 
377 /*
378  * Need to check if array has failed when deciding whether to:
379  *  - start an array
380  *  - remove non-faulty devices
381  *  - add a spare
382  *  - allow a reshape
383  * This determination is simple when no reshape is happening.
384  * However if there is a reshape, we need to carefully check
385  * both the before and after sections.
386  * This is because some failed devices may only affect one
387  * of the two sections, and some non-in_sync devices may
388  * be insync in the section most affected by failed devices.
389  */
390 static int calc_degraded(struct r5conf *conf)
391 {
392 	int degraded, degraded2;
393 	int i;
394 
395 	rcu_read_lock();
396 	degraded = 0;
397 	for (i = 0; i < conf->previous_raid_disks; i++) {
398 		struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
399 		if (rdev && test_bit(Faulty, &rdev->flags))
400 			rdev = rcu_dereference(conf->disks[i].replacement);
401 		if (!rdev || test_bit(Faulty, &rdev->flags))
402 			degraded++;
403 		else if (test_bit(In_sync, &rdev->flags))
404 			;
405 		else
406 			/* not in-sync or faulty.
407 			 * If the reshape increases the number of devices,
408 			 * this is being recovered by the reshape, so
409 			 * this 'previous' section is not in_sync.
410 			 * If the number of devices is being reduced however,
411 			 * the device can only be part of the array if
412 			 * we are reverting a reshape, so this section will
413 			 * be in-sync.
414 			 */
415 			if (conf->raid_disks >= conf->previous_raid_disks)
416 				degraded++;
417 	}
418 	rcu_read_unlock();
419 	if (conf->raid_disks == conf->previous_raid_disks)
420 		return degraded;
421 	rcu_read_lock();
422 	degraded2 = 0;
423 	for (i = 0; i < conf->raid_disks; i++) {
424 		struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
425 		if (rdev && test_bit(Faulty, &rdev->flags))
426 			rdev = rcu_dereference(conf->disks[i].replacement);
427 		if (!rdev || test_bit(Faulty, &rdev->flags))
428 			degraded2++;
429 		else if (test_bit(In_sync, &rdev->flags))
430 			;
431 		else
432 			/* not in-sync or faulty.
433 			 * If reshape increases the number of devices, this
434 			 * section has already been recovered, else it
435 			 * almost certainly hasn't.
436 			 */
437 			if (conf->raid_disks <= conf->previous_raid_disks)
438 				degraded2++;
439 	}
440 	rcu_read_unlock();
441 	if (degraded2 > degraded)
442 		return degraded2;
443 	return degraded;
444 }
445 
446 static int has_failed(struct r5conf *conf)
447 {
448 	int degraded;
449 
450 	if (conf->mddev->reshape_position == MaxSector)
451 		return conf->mddev->degraded > conf->max_degraded;
452 
453 	degraded = calc_degraded(conf);
454 	if (degraded > conf->max_degraded)
455 		return 1;
456 	return 0;
457 }
458 
459 static struct stripe_head *
460 get_active_stripe(struct r5conf *conf, sector_t sector,
461 		  int previous, int noblock, int noquiesce)
462 {
463 	struct stripe_head *sh;
464 
465 	pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
466 
467 	spin_lock_irq(&conf->device_lock);
468 
469 	do {
470 		wait_event_lock_irq(conf->wait_for_stripe,
471 				    conf->quiesce == 0 || noquiesce,
472 				    conf->device_lock);
473 		sh = __find_stripe(conf, sector, conf->generation - previous);
474 		if (!sh) {
475 			if (!conf->inactive_blocked)
476 				sh = get_free_stripe(conf);
477 			if (noblock && sh == NULL)
478 				break;
479 			if (!sh) {
480 				conf->inactive_blocked = 1;
481 				wait_event_lock_irq(conf->wait_for_stripe,
482 						    !list_empty(&conf->inactive_list) &&
483 						    (atomic_read(&conf->active_stripes)
484 						     < (conf->max_nr_stripes *3/4)
485 						     || !conf->inactive_blocked),
486 						    conf->device_lock);
487 				conf->inactive_blocked = 0;
488 			} else
489 				init_stripe(sh, sector, previous);
490 		} else {
491 			if (atomic_read(&sh->count)) {
492 				BUG_ON(!list_empty(&sh->lru)
493 				    && !test_bit(STRIPE_EXPANDING, &sh->state)
494 				    && !test_bit(STRIPE_ON_UNPLUG_LIST, &sh->state));
495 			} else {
496 				if (!test_bit(STRIPE_HANDLE, &sh->state))
497 					atomic_inc(&conf->active_stripes);
498 				if (list_empty(&sh->lru) &&
499 				    !test_bit(STRIPE_EXPANDING, &sh->state))
500 					BUG();
501 				list_del_init(&sh->lru);
502 			}
503 		}
504 	} while (sh == NULL);
505 
506 	if (sh)
507 		atomic_inc(&sh->count);
508 
509 	spin_unlock_irq(&conf->device_lock);
510 	return sh;
511 }
512 
513 /* Determine if 'data_offset' or 'new_data_offset' should be used
514  * in this stripe_head.
515  */
516 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
517 {
518 	sector_t progress = conf->reshape_progress;
519 	/* Need a memory barrier to make sure we see the value
520 	 * of conf->generation, or ->data_offset that was set before
521 	 * reshape_progress was updated.
522 	 */
523 	smp_rmb();
524 	if (progress == MaxSector)
525 		return 0;
526 	if (sh->generation == conf->generation - 1)
527 		return 0;
528 	/* We are in a reshape, and this is a new-generation stripe,
529 	 * so use new_data_offset.
530 	 */
531 	return 1;
532 }
533 
534 static void
535 raid5_end_read_request(struct bio *bi, int error);
536 static void
537 raid5_end_write_request(struct bio *bi, int error);
538 
539 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
540 {
541 	struct r5conf *conf = sh->raid_conf;
542 	int i, disks = sh->disks;
543 
544 	might_sleep();
545 
546 	for (i = disks; i--; ) {
547 		int rw;
548 		int replace_only = 0;
549 		struct bio *bi, *rbi;
550 		struct md_rdev *rdev, *rrdev = NULL;
551 		if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
552 			if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
553 				rw = WRITE_FUA;
554 			else
555 				rw = WRITE;
556 			if (test_bit(R5_Discard, &sh->dev[i].flags))
557 				rw |= REQ_DISCARD;
558 		} else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
559 			rw = READ;
560 		else if (test_and_clear_bit(R5_WantReplace,
561 					    &sh->dev[i].flags)) {
562 			rw = WRITE;
563 			replace_only = 1;
564 		} else
565 			continue;
566 		if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
567 			rw |= REQ_SYNC;
568 
569 		bi = &sh->dev[i].req;
570 		rbi = &sh->dev[i].rreq; /* For writing to replacement */
571 
572 		bi->bi_rw = rw;
573 		rbi->bi_rw = rw;
574 		if (rw & WRITE) {
575 			bi->bi_end_io = raid5_end_write_request;
576 			rbi->bi_end_io = raid5_end_write_request;
577 		} else
578 			bi->bi_end_io = raid5_end_read_request;
579 
580 		rcu_read_lock();
581 		rrdev = rcu_dereference(conf->disks[i].replacement);
582 		smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
583 		rdev = rcu_dereference(conf->disks[i].rdev);
584 		if (!rdev) {
585 			rdev = rrdev;
586 			rrdev = NULL;
587 		}
588 		if (rw & WRITE) {
589 			if (replace_only)
590 				rdev = NULL;
591 			if (rdev == rrdev)
592 				/* We raced and saw duplicates */
593 				rrdev = NULL;
594 		} else {
595 			if (test_bit(R5_ReadRepl, &sh->dev[i].flags) && rrdev)
596 				rdev = rrdev;
597 			rrdev = NULL;
598 		}
599 
600 		if (rdev && test_bit(Faulty, &rdev->flags))
601 			rdev = NULL;
602 		if (rdev)
603 			atomic_inc(&rdev->nr_pending);
604 		if (rrdev && test_bit(Faulty, &rrdev->flags))
605 			rrdev = NULL;
606 		if (rrdev)
607 			atomic_inc(&rrdev->nr_pending);
608 		rcu_read_unlock();
609 
610 		/* We have already checked bad blocks for reads.  Now
611 		 * need to check for writes.  We never accept write errors
612 		 * on the replacement, so we don't to check rrdev.
613 		 */
614 		while ((rw & WRITE) && rdev &&
615 		       test_bit(WriteErrorSeen, &rdev->flags)) {
616 			sector_t first_bad;
617 			int bad_sectors;
618 			int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
619 					      &first_bad, &bad_sectors);
620 			if (!bad)
621 				break;
622 
623 			if (bad < 0) {
624 				set_bit(BlockedBadBlocks, &rdev->flags);
625 				if (!conf->mddev->external &&
626 				    conf->mddev->flags) {
627 					/* It is very unlikely, but we might
628 					 * still need to write out the
629 					 * bad block log - better give it
630 					 * a chance*/
631 					md_check_recovery(conf->mddev);
632 				}
633 				/*
634 				 * Because md_wait_for_blocked_rdev
635 				 * will dec nr_pending, we must
636 				 * increment it first.
637 				 */
638 				atomic_inc(&rdev->nr_pending);
639 				md_wait_for_blocked_rdev(rdev, conf->mddev);
640 			} else {
641 				/* Acknowledged bad block - skip the write */
642 				rdev_dec_pending(rdev, conf->mddev);
643 				rdev = NULL;
644 			}
645 		}
646 
647 		if (rdev) {
648 			if (s->syncing || s->expanding || s->expanded
649 			    || s->replacing)
650 				md_sync_acct(rdev->bdev, STRIPE_SECTORS);
651 
652 			set_bit(STRIPE_IO_STARTED, &sh->state);
653 
654 			bi->bi_bdev = rdev->bdev;
655 			pr_debug("%s: for %llu schedule op %ld on disc %d\n",
656 				__func__, (unsigned long long)sh->sector,
657 				bi->bi_rw, i);
658 			atomic_inc(&sh->count);
659 			if (use_new_offset(conf, sh))
660 				bi->bi_sector = (sh->sector
661 						 + rdev->new_data_offset);
662 			else
663 				bi->bi_sector = (sh->sector
664 						 + rdev->data_offset);
665 			if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
666 				bi->bi_rw |= REQ_FLUSH;
667 
668 			bi->bi_flags = 1 << BIO_UPTODATE;
669 			bi->bi_idx = 0;
670 			bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
671 			bi->bi_io_vec[0].bv_offset = 0;
672 			bi->bi_size = STRIPE_SIZE;
673 			bi->bi_next = NULL;
674 			if (rrdev)
675 				set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
676 
677 			if (conf->mddev->gendisk)
678 				trace_block_bio_remap(bdev_get_queue(bi->bi_bdev),
679 						      bi, disk_devt(conf->mddev->gendisk),
680 						      sh->dev[i].sector);
681 			generic_make_request(bi);
682 		}
683 		if (rrdev) {
684 			if (s->syncing || s->expanding || s->expanded
685 			    || s->replacing)
686 				md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
687 
688 			set_bit(STRIPE_IO_STARTED, &sh->state);
689 
690 			rbi->bi_bdev = rrdev->bdev;
691 			pr_debug("%s: for %llu schedule op %ld on "
692 				 "replacement disc %d\n",
693 				__func__, (unsigned long long)sh->sector,
694 				rbi->bi_rw, i);
695 			atomic_inc(&sh->count);
696 			if (use_new_offset(conf, sh))
697 				rbi->bi_sector = (sh->sector
698 						  + rrdev->new_data_offset);
699 			else
700 				rbi->bi_sector = (sh->sector
701 						  + rrdev->data_offset);
702 			rbi->bi_flags = 1 << BIO_UPTODATE;
703 			rbi->bi_idx = 0;
704 			rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
705 			rbi->bi_io_vec[0].bv_offset = 0;
706 			rbi->bi_size = STRIPE_SIZE;
707 			rbi->bi_next = NULL;
708 			if (conf->mddev->gendisk)
709 				trace_block_bio_remap(bdev_get_queue(rbi->bi_bdev),
710 						      rbi, disk_devt(conf->mddev->gendisk),
711 						      sh->dev[i].sector);
712 			generic_make_request(rbi);
713 		}
714 		if (!rdev && !rrdev) {
715 			if (rw & WRITE)
716 				set_bit(STRIPE_DEGRADED, &sh->state);
717 			pr_debug("skip op %ld on disc %d for sector %llu\n",
718 				bi->bi_rw, i, (unsigned long long)sh->sector);
719 			clear_bit(R5_LOCKED, &sh->dev[i].flags);
720 			set_bit(STRIPE_HANDLE, &sh->state);
721 		}
722 	}
723 }
724 
725 static struct dma_async_tx_descriptor *
726 async_copy_data(int frombio, struct bio *bio, struct page *page,
727 	sector_t sector, struct dma_async_tx_descriptor *tx)
728 {
729 	struct bio_vec *bvl;
730 	struct page *bio_page;
731 	int i;
732 	int page_offset;
733 	struct async_submit_ctl submit;
734 	enum async_tx_flags flags = 0;
735 
736 	if (bio->bi_sector >= sector)
737 		page_offset = (signed)(bio->bi_sector - sector) * 512;
738 	else
739 		page_offset = (signed)(sector - bio->bi_sector) * -512;
740 
741 	if (frombio)
742 		flags |= ASYNC_TX_FENCE;
743 	init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
744 
745 	bio_for_each_segment(bvl, bio, i) {
746 		int len = bvl->bv_len;
747 		int clen;
748 		int b_offset = 0;
749 
750 		if (page_offset < 0) {
751 			b_offset = -page_offset;
752 			page_offset += b_offset;
753 			len -= b_offset;
754 		}
755 
756 		if (len > 0 && page_offset + len > STRIPE_SIZE)
757 			clen = STRIPE_SIZE - page_offset;
758 		else
759 			clen = len;
760 
761 		if (clen > 0) {
762 			b_offset += bvl->bv_offset;
763 			bio_page = bvl->bv_page;
764 			if (frombio)
765 				tx = async_memcpy(page, bio_page, page_offset,
766 						  b_offset, clen, &submit);
767 			else
768 				tx = async_memcpy(bio_page, page, b_offset,
769 						  page_offset, clen, &submit);
770 		}
771 		/* chain the operations */
772 		submit.depend_tx = tx;
773 
774 		if (clen < len) /* hit end of page */
775 			break;
776 		page_offset +=  len;
777 	}
778 
779 	return tx;
780 }
781 
782 static void ops_complete_biofill(void *stripe_head_ref)
783 {
784 	struct stripe_head *sh = stripe_head_ref;
785 	struct bio *return_bi = NULL;
786 	int i;
787 
788 	pr_debug("%s: stripe %llu\n", __func__,
789 		(unsigned long long)sh->sector);
790 
791 	/* clear completed biofills */
792 	for (i = sh->disks; i--; ) {
793 		struct r5dev *dev = &sh->dev[i];
794 
795 		/* acknowledge completion of a biofill operation */
796 		/* and check if we need to reply to a read request,
797 		 * new R5_Wantfill requests are held off until
798 		 * !STRIPE_BIOFILL_RUN
799 		 */
800 		if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
801 			struct bio *rbi, *rbi2;
802 
803 			BUG_ON(!dev->read);
804 			rbi = dev->read;
805 			dev->read = NULL;
806 			while (rbi && rbi->bi_sector <
807 				dev->sector + STRIPE_SECTORS) {
808 				rbi2 = r5_next_bio(rbi, dev->sector);
809 				if (!raid5_dec_bi_active_stripes(rbi)) {
810 					rbi->bi_next = return_bi;
811 					return_bi = rbi;
812 				}
813 				rbi = rbi2;
814 			}
815 		}
816 	}
817 	clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
818 
819 	return_io(return_bi);
820 
821 	set_bit(STRIPE_HANDLE, &sh->state);
822 	release_stripe(sh);
823 }
824 
825 static void ops_run_biofill(struct stripe_head *sh)
826 {
827 	struct dma_async_tx_descriptor *tx = NULL;
828 	struct async_submit_ctl submit;
829 	int i;
830 
831 	pr_debug("%s: stripe %llu\n", __func__,
832 		(unsigned long long)sh->sector);
833 
834 	for (i = sh->disks; i--; ) {
835 		struct r5dev *dev = &sh->dev[i];
836 		if (test_bit(R5_Wantfill, &dev->flags)) {
837 			struct bio *rbi;
838 			spin_lock_irq(&sh->stripe_lock);
839 			dev->read = rbi = dev->toread;
840 			dev->toread = NULL;
841 			spin_unlock_irq(&sh->stripe_lock);
842 			while (rbi && rbi->bi_sector <
843 				dev->sector + STRIPE_SECTORS) {
844 				tx = async_copy_data(0, rbi, dev->page,
845 					dev->sector, tx);
846 				rbi = r5_next_bio(rbi, dev->sector);
847 			}
848 		}
849 	}
850 
851 	atomic_inc(&sh->count);
852 	init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
853 	async_trigger_callback(&submit);
854 }
855 
856 static void mark_target_uptodate(struct stripe_head *sh, int target)
857 {
858 	struct r5dev *tgt;
859 
860 	if (target < 0)
861 		return;
862 
863 	tgt = &sh->dev[target];
864 	set_bit(R5_UPTODATE, &tgt->flags);
865 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
866 	clear_bit(R5_Wantcompute, &tgt->flags);
867 }
868 
869 static void ops_complete_compute(void *stripe_head_ref)
870 {
871 	struct stripe_head *sh = stripe_head_ref;
872 
873 	pr_debug("%s: stripe %llu\n", __func__,
874 		(unsigned long long)sh->sector);
875 
876 	/* mark the computed target(s) as uptodate */
877 	mark_target_uptodate(sh, sh->ops.target);
878 	mark_target_uptodate(sh, sh->ops.target2);
879 
880 	clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
881 	if (sh->check_state == check_state_compute_run)
882 		sh->check_state = check_state_compute_result;
883 	set_bit(STRIPE_HANDLE, &sh->state);
884 	release_stripe(sh);
885 }
886 
887 /* return a pointer to the address conversion region of the scribble buffer */
888 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
889 				 struct raid5_percpu *percpu)
890 {
891 	return percpu->scribble + sizeof(struct page *) * (sh->disks + 2);
892 }
893 
894 static struct dma_async_tx_descriptor *
895 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
896 {
897 	int disks = sh->disks;
898 	struct page **xor_srcs = percpu->scribble;
899 	int target = sh->ops.target;
900 	struct r5dev *tgt = &sh->dev[target];
901 	struct page *xor_dest = tgt->page;
902 	int count = 0;
903 	struct dma_async_tx_descriptor *tx;
904 	struct async_submit_ctl submit;
905 	int i;
906 
907 	pr_debug("%s: stripe %llu block: %d\n",
908 		__func__, (unsigned long long)sh->sector, target);
909 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
910 
911 	for (i = disks; i--; )
912 		if (i != target)
913 			xor_srcs[count++] = sh->dev[i].page;
914 
915 	atomic_inc(&sh->count);
916 
917 	init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
918 			  ops_complete_compute, sh, to_addr_conv(sh, percpu));
919 	if (unlikely(count == 1))
920 		tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
921 	else
922 		tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
923 
924 	return tx;
925 }
926 
927 /* set_syndrome_sources - populate source buffers for gen_syndrome
928  * @srcs - (struct page *) array of size sh->disks
929  * @sh - stripe_head to parse
930  *
931  * Populates srcs in proper layout order for the stripe and returns the
932  * 'count' of sources to be used in a call to async_gen_syndrome.  The P
933  * destination buffer is recorded in srcs[count] and the Q destination
934  * is recorded in srcs[count+1]].
935  */
936 static int set_syndrome_sources(struct page **srcs, struct stripe_head *sh)
937 {
938 	int disks = sh->disks;
939 	int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
940 	int d0_idx = raid6_d0(sh);
941 	int count;
942 	int i;
943 
944 	for (i = 0; i < disks; i++)
945 		srcs[i] = NULL;
946 
947 	count = 0;
948 	i = d0_idx;
949 	do {
950 		int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
951 
952 		srcs[slot] = sh->dev[i].page;
953 		i = raid6_next_disk(i, disks);
954 	} while (i != d0_idx);
955 
956 	return syndrome_disks;
957 }
958 
959 static struct dma_async_tx_descriptor *
960 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
961 {
962 	int disks = sh->disks;
963 	struct page **blocks = percpu->scribble;
964 	int target;
965 	int qd_idx = sh->qd_idx;
966 	struct dma_async_tx_descriptor *tx;
967 	struct async_submit_ctl submit;
968 	struct r5dev *tgt;
969 	struct page *dest;
970 	int i;
971 	int count;
972 
973 	if (sh->ops.target < 0)
974 		target = sh->ops.target2;
975 	else if (sh->ops.target2 < 0)
976 		target = sh->ops.target;
977 	else
978 		/* we should only have one valid target */
979 		BUG();
980 	BUG_ON(target < 0);
981 	pr_debug("%s: stripe %llu block: %d\n",
982 		__func__, (unsigned long long)sh->sector, target);
983 
984 	tgt = &sh->dev[target];
985 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
986 	dest = tgt->page;
987 
988 	atomic_inc(&sh->count);
989 
990 	if (target == qd_idx) {
991 		count = set_syndrome_sources(blocks, sh);
992 		blocks[count] = NULL; /* regenerating p is not necessary */
993 		BUG_ON(blocks[count+1] != dest); /* q should already be set */
994 		init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
995 				  ops_complete_compute, sh,
996 				  to_addr_conv(sh, percpu));
997 		tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
998 	} else {
999 		/* Compute any data- or p-drive using XOR */
1000 		count = 0;
1001 		for (i = disks; i-- ; ) {
1002 			if (i == target || i == qd_idx)
1003 				continue;
1004 			blocks[count++] = sh->dev[i].page;
1005 		}
1006 
1007 		init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1008 				  NULL, ops_complete_compute, sh,
1009 				  to_addr_conv(sh, percpu));
1010 		tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1011 	}
1012 
1013 	return tx;
1014 }
1015 
1016 static struct dma_async_tx_descriptor *
1017 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1018 {
1019 	int i, count, disks = sh->disks;
1020 	int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1021 	int d0_idx = raid6_d0(sh);
1022 	int faila = -1, failb = -1;
1023 	int target = sh->ops.target;
1024 	int target2 = sh->ops.target2;
1025 	struct r5dev *tgt = &sh->dev[target];
1026 	struct r5dev *tgt2 = &sh->dev[target2];
1027 	struct dma_async_tx_descriptor *tx;
1028 	struct page **blocks = percpu->scribble;
1029 	struct async_submit_ctl submit;
1030 
1031 	pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1032 		 __func__, (unsigned long long)sh->sector, target, target2);
1033 	BUG_ON(target < 0 || target2 < 0);
1034 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1035 	BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1036 
1037 	/* we need to open-code set_syndrome_sources to handle the
1038 	 * slot number conversion for 'faila' and 'failb'
1039 	 */
1040 	for (i = 0; i < disks ; i++)
1041 		blocks[i] = NULL;
1042 	count = 0;
1043 	i = d0_idx;
1044 	do {
1045 		int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1046 
1047 		blocks[slot] = sh->dev[i].page;
1048 
1049 		if (i == target)
1050 			faila = slot;
1051 		if (i == target2)
1052 			failb = slot;
1053 		i = raid6_next_disk(i, disks);
1054 	} while (i != d0_idx);
1055 
1056 	BUG_ON(faila == failb);
1057 	if (failb < faila)
1058 		swap(faila, failb);
1059 	pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1060 		 __func__, (unsigned long long)sh->sector, faila, failb);
1061 
1062 	atomic_inc(&sh->count);
1063 
1064 	if (failb == syndrome_disks+1) {
1065 		/* Q disk is one of the missing disks */
1066 		if (faila == syndrome_disks) {
1067 			/* Missing P+Q, just recompute */
1068 			init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1069 					  ops_complete_compute, sh,
1070 					  to_addr_conv(sh, percpu));
1071 			return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1072 						  STRIPE_SIZE, &submit);
1073 		} else {
1074 			struct page *dest;
1075 			int data_target;
1076 			int qd_idx = sh->qd_idx;
1077 
1078 			/* Missing D+Q: recompute D from P, then recompute Q */
1079 			if (target == qd_idx)
1080 				data_target = target2;
1081 			else
1082 				data_target = target;
1083 
1084 			count = 0;
1085 			for (i = disks; i-- ; ) {
1086 				if (i == data_target || i == qd_idx)
1087 					continue;
1088 				blocks[count++] = sh->dev[i].page;
1089 			}
1090 			dest = sh->dev[data_target].page;
1091 			init_async_submit(&submit,
1092 					  ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1093 					  NULL, NULL, NULL,
1094 					  to_addr_conv(sh, percpu));
1095 			tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1096 				       &submit);
1097 
1098 			count = set_syndrome_sources(blocks, sh);
1099 			init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1100 					  ops_complete_compute, sh,
1101 					  to_addr_conv(sh, percpu));
1102 			return async_gen_syndrome(blocks, 0, count+2,
1103 						  STRIPE_SIZE, &submit);
1104 		}
1105 	} else {
1106 		init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1107 				  ops_complete_compute, sh,
1108 				  to_addr_conv(sh, percpu));
1109 		if (failb == syndrome_disks) {
1110 			/* We're missing D+P. */
1111 			return async_raid6_datap_recov(syndrome_disks+2,
1112 						       STRIPE_SIZE, faila,
1113 						       blocks, &submit);
1114 		} else {
1115 			/* We're missing D+D. */
1116 			return async_raid6_2data_recov(syndrome_disks+2,
1117 						       STRIPE_SIZE, faila, failb,
1118 						       blocks, &submit);
1119 		}
1120 	}
1121 }
1122 
1123 
1124 static void ops_complete_prexor(void *stripe_head_ref)
1125 {
1126 	struct stripe_head *sh = stripe_head_ref;
1127 
1128 	pr_debug("%s: stripe %llu\n", __func__,
1129 		(unsigned long long)sh->sector);
1130 }
1131 
1132 static struct dma_async_tx_descriptor *
1133 ops_run_prexor(struct stripe_head *sh, struct raid5_percpu *percpu,
1134 	       struct dma_async_tx_descriptor *tx)
1135 {
1136 	int disks = sh->disks;
1137 	struct page **xor_srcs = percpu->scribble;
1138 	int count = 0, pd_idx = sh->pd_idx, i;
1139 	struct async_submit_ctl submit;
1140 
1141 	/* existing parity data subtracted */
1142 	struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1143 
1144 	pr_debug("%s: stripe %llu\n", __func__,
1145 		(unsigned long long)sh->sector);
1146 
1147 	for (i = disks; i--; ) {
1148 		struct r5dev *dev = &sh->dev[i];
1149 		/* Only process blocks that are known to be uptodate */
1150 		if (test_bit(R5_Wantdrain, &dev->flags))
1151 			xor_srcs[count++] = dev->page;
1152 	}
1153 
1154 	init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1155 			  ops_complete_prexor, sh, to_addr_conv(sh, percpu));
1156 	tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1157 
1158 	return tx;
1159 }
1160 
1161 static struct dma_async_tx_descriptor *
1162 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1163 {
1164 	int disks = sh->disks;
1165 	int i;
1166 
1167 	pr_debug("%s: stripe %llu\n", __func__,
1168 		(unsigned long long)sh->sector);
1169 
1170 	for (i = disks; i--; ) {
1171 		struct r5dev *dev = &sh->dev[i];
1172 		struct bio *chosen;
1173 
1174 		if (test_and_clear_bit(R5_Wantdrain, &dev->flags)) {
1175 			struct bio *wbi;
1176 
1177 			spin_lock_irq(&sh->stripe_lock);
1178 			chosen = dev->towrite;
1179 			dev->towrite = NULL;
1180 			BUG_ON(dev->written);
1181 			wbi = dev->written = chosen;
1182 			spin_unlock_irq(&sh->stripe_lock);
1183 
1184 			while (wbi && wbi->bi_sector <
1185 				dev->sector + STRIPE_SECTORS) {
1186 				if (wbi->bi_rw & REQ_FUA)
1187 					set_bit(R5_WantFUA, &dev->flags);
1188 				if (wbi->bi_rw & REQ_SYNC)
1189 					set_bit(R5_SyncIO, &dev->flags);
1190 				if (wbi->bi_rw & REQ_DISCARD)
1191 					set_bit(R5_Discard, &dev->flags);
1192 				else
1193 					tx = async_copy_data(1, wbi, dev->page,
1194 						dev->sector, tx);
1195 				wbi = r5_next_bio(wbi, dev->sector);
1196 			}
1197 		}
1198 	}
1199 
1200 	return tx;
1201 }
1202 
1203 static void ops_complete_reconstruct(void *stripe_head_ref)
1204 {
1205 	struct stripe_head *sh = stripe_head_ref;
1206 	int disks = sh->disks;
1207 	int pd_idx = sh->pd_idx;
1208 	int qd_idx = sh->qd_idx;
1209 	int i;
1210 	bool fua = false, sync = false, discard = false;
1211 
1212 	pr_debug("%s: stripe %llu\n", __func__,
1213 		(unsigned long long)sh->sector);
1214 
1215 	for (i = disks; i--; ) {
1216 		fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1217 		sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1218 		discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1219 	}
1220 
1221 	for (i = disks; i--; ) {
1222 		struct r5dev *dev = &sh->dev[i];
1223 
1224 		if (dev->written || i == pd_idx || i == qd_idx) {
1225 			if (!discard)
1226 				set_bit(R5_UPTODATE, &dev->flags);
1227 			if (fua)
1228 				set_bit(R5_WantFUA, &dev->flags);
1229 			if (sync)
1230 				set_bit(R5_SyncIO, &dev->flags);
1231 		}
1232 	}
1233 
1234 	if (sh->reconstruct_state == reconstruct_state_drain_run)
1235 		sh->reconstruct_state = reconstruct_state_drain_result;
1236 	else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1237 		sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1238 	else {
1239 		BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1240 		sh->reconstruct_state = reconstruct_state_result;
1241 	}
1242 
1243 	set_bit(STRIPE_HANDLE, &sh->state);
1244 	release_stripe(sh);
1245 }
1246 
1247 static void
1248 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1249 		     struct dma_async_tx_descriptor *tx)
1250 {
1251 	int disks = sh->disks;
1252 	struct page **xor_srcs = percpu->scribble;
1253 	struct async_submit_ctl submit;
1254 	int count = 0, pd_idx = sh->pd_idx, i;
1255 	struct page *xor_dest;
1256 	int prexor = 0;
1257 	unsigned long flags;
1258 
1259 	pr_debug("%s: stripe %llu\n", __func__,
1260 		(unsigned long long)sh->sector);
1261 
1262 	for (i = 0; i < sh->disks; i++) {
1263 		if (pd_idx == i)
1264 			continue;
1265 		if (!test_bit(R5_Discard, &sh->dev[i].flags))
1266 			break;
1267 	}
1268 	if (i >= sh->disks) {
1269 		atomic_inc(&sh->count);
1270 		set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1271 		ops_complete_reconstruct(sh);
1272 		return;
1273 	}
1274 	/* check if prexor is active which means only process blocks
1275 	 * that are part of a read-modify-write (written)
1276 	 */
1277 	if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1278 		prexor = 1;
1279 		xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1280 		for (i = disks; i--; ) {
1281 			struct r5dev *dev = &sh->dev[i];
1282 			if (dev->written)
1283 				xor_srcs[count++] = dev->page;
1284 		}
1285 	} else {
1286 		xor_dest = sh->dev[pd_idx].page;
1287 		for (i = disks; i--; ) {
1288 			struct r5dev *dev = &sh->dev[i];
1289 			if (i != pd_idx)
1290 				xor_srcs[count++] = dev->page;
1291 		}
1292 	}
1293 
1294 	/* 1/ if we prexor'd then the dest is reused as a source
1295 	 * 2/ if we did not prexor then we are redoing the parity
1296 	 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1297 	 * for the synchronous xor case
1298 	 */
1299 	flags = ASYNC_TX_ACK |
1300 		(prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1301 
1302 	atomic_inc(&sh->count);
1303 
1304 	init_async_submit(&submit, flags, tx, ops_complete_reconstruct, sh,
1305 			  to_addr_conv(sh, percpu));
1306 	if (unlikely(count == 1))
1307 		tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1308 	else
1309 		tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1310 }
1311 
1312 static void
1313 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1314 		     struct dma_async_tx_descriptor *tx)
1315 {
1316 	struct async_submit_ctl submit;
1317 	struct page **blocks = percpu->scribble;
1318 	int count, i;
1319 
1320 	pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1321 
1322 	for (i = 0; i < sh->disks; i++) {
1323 		if (sh->pd_idx == i || sh->qd_idx == i)
1324 			continue;
1325 		if (!test_bit(R5_Discard, &sh->dev[i].flags))
1326 			break;
1327 	}
1328 	if (i >= sh->disks) {
1329 		atomic_inc(&sh->count);
1330 		set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1331 		set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1332 		ops_complete_reconstruct(sh);
1333 		return;
1334 	}
1335 
1336 	count = set_syndrome_sources(blocks, sh);
1337 
1338 	atomic_inc(&sh->count);
1339 
1340 	init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_reconstruct,
1341 			  sh, to_addr_conv(sh, percpu));
1342 	async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE,  &submit);
1343 }
1344 
1345 static void ops_complete_check(void *stripe_head_ref)
1346 {
1347 	struct stripe_head *sh = stripe_head_ref;
1348 
1349 	pr_debug("%s: stripe %llu\n", __func__,
1350 		(unsigned long long)sh->sector);
1351 
1352 	sh->check_state = check_state_check_result;
1353 	set_bit(STRIPE_HANDLE, &sh->state);
1354 	release_stripe(sh);
1355 }
1356 
1357 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1358 {
1359 	int disks = sh->disks;
1360 	int pd_idx = sh->pd_idx;
1361 	int qd_idx = sh->qd_idx;
1362 	struct page *xor_dest;
1363 	struct page **xor_srcs = percpu->scribble;
1364 	struct dma_async_tx_descriptor *tx;
1365 	struct async_submit_ctl submit;
1366 	int count;
1367 	int i;
1368 
1369 	pr_debug("%s: stripe %llu\n", __func__,
1370 		(unsigned long long)sh->sector);
1371 
1372 	count = 0;
1373 	xor_dest = sh->dev[pd_idx].page;
1374 	xor_srcs[count++] = xor_dest;
1375 	for (i = disks; i--; ) {
1376 		if (i == pd_idx || i == qd_idx)
1377 			continue;
1378 		xor_srcs[count++] = sh->dev[i].page;
1379 	}
1380 
1381 	init_async_submit(&submit, 0, NULL, NULL, NULL,
1382 			  to_addr_conv(sh, percpu));
1383 	tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
1384 			   &sh->ops.zero_sum_result, &submit);
1385 
1386 	atomic_inc(&sh->count);
1387 	init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
1388 	tx = async_trigger_callback(&submit);
1389 }
1390 
1391 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
1392 {
1393 	struct page **srcs = percpu->scribble;
1394 	struct async_submit_ctl submit;
1395 	int count;
1396 
1397 	pr_debug("%s: stripe %llu checkp: %d\n", __func__,
1398 		(unsigned long long)sh->sector, checkp);
1399 
1400 	count = set_syndrome_sources(srcs, sh);
1401 	if (!checkp)
1402 		srcs[count] = NULL;
1403 
1404 	atomic_inc(&sh->count);
1405 	init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
1406 			  sh, to_addr_conv(sh, percpu));
1407 	async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
1408 			   &sh->ops.zero_sum_result, percpu->spare_page, &submit);
1409 }
1410 
1411 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1412 {
1413 	int overlap_clear = 0, i, disks = sh->disks;
1414 	struct dma_async_tx_descriptor *tx = NULL;
1415 	struct r5conf *conf = sh->raid_conf;
1416 	int level = conf->level;
1417 	struct raid5_percpu *percpu;
1418 	unsigned long cpu;
1419 
1420 	cpu = get_cpu();
1421 	percpu = per_cpu_ptr(conf->percpu, cpu);
1422 	if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
1423 		ops_run_biofill(sh);
1424 		overlap_clear++;
1425 	}
1426 
1427 	if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
1428 		if (level < 6)
1429 			tx = ops_run_compute5(sh, percpu);
1430 		else {
1431 			if (sh->ops.target2 < 0 || sh->ops.target < 0)
1432 				tx = ops_run_compute6_1(sh, percpu);
1433 			else
1434 				tx = ops_run_compute6_2(sh, percpu);
1435 		}
1436 		/* terminate the chain if reconstruct is not set to be run */
1437 		if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
1438 			async_tx_ack(tx);
1439 	}
1440 
1441 	if (test_bit(STRIPE_OP_PREXOR, &ops_request))
1442 		tx = ops_run_prexor(sh, percpu, tx);
1443 
1444 	if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
1445 		tx = ops_run_biodrain(sh, tx);
1446 		overlap_clear++;
1447 	}
1448 
1449 	if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
1450 		if (level < 6)
1451 			ops_run_reconstruct5(sh, percpu, tx);
1452 		else
1453 			ops_run_reconstruct6(sh, percpu, tx);
1454 	}
1455 
1456 	if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
1457 		if (sh->check_state == check_state_run)
1458 			ops_run_check_p(sh, percpu);
1459 		else if (sh->check_state == check_state_run_q)
1460 			ops_run_check_pq(sh, percpu, 0);
1461 		else if (sh->check_state == check_state_run_pq)
1462 			ops_run_check_pq(sh, percpu, 1);
1463 		else
1464 			BUG();
1465 	}
1466 
1467 	if (overlap_clear)
1468 		for (i = disks; i--; ) {
1469 			struct r5dev *dev = &sh->dev[i];
1470 			if (test_and_clear_bit(R5_Overlap, &dev->flags))
1471 				wake_up(&sh->raid_conf->wait_for_overlap);
1472 		}
1473 	put_cpu();
1474 }
1475 
1476 static int grow_one_stripe(struct r5conf *conf)
1477 {
1478 	struct stripe_head *sh;
1479 	sh = kmem_cache_zalloc(conf->slab_cache, GFP_KERNEL);
1480 	if (!sh)
1481 		return 0;
1482 
1483 	sh->raid_conf = conf;
1484 
1485 	spin_lock_init(&sh->stripe_lock);
1486 
1487 	if (grow_buffers(sh)) {
1488 		shrink_buffers(sh);
1489 		kmem_cache_free(conf->slab_cache, sh);
1490 		return 0;
1491 	}
1492 	/* we just created an active stripe so... */
1493 	atomic_set(&sh->count, 1);
1494 	atomic_inc(&conf->active_stripes);
1495 	INIT_LIST_HEAD(&sh->lru);
1496 	release_stripe(sh);
1497 	return 1;
1498 }
1499 
1500 static int grow_stripes(struct r5conf *conf, int num)
1501 {
1502 	struct kmem_cache *sc;
1503 	int devs = max(conf->raid_disks, conf->previous_raid_disks);
1504 
1505 	if (conf->mddev->gendisk)
1506 		sprintf(conf->cache_name[0],
1507 			"raid%d-%s", conf->level, mdname(conf->mddev));
1508 	else
1509 		sprintf(conf->cache_name[0],
1510 			"raid%d-%p", conf->level, conf->mddev);
1511 	sprintf(conf->cache_name[1], "%s-alt", conf->cache_name[0]);
1512 
1513 	conf->active_name = 0;
1514 	sc = kmem_cache_create(conf->cache_name[conf->active_name],
1515 			       sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
1516 			       0, 0, NULL);
1517 	if (!sc)
1518 		return 1;
1519 	conf->slab_cache = sc;
1520 	conf->pool_size = devs;
1521 	while (num--)
1522 		if (!grow_one_stripe(conf))
1523 			return 1;
1524 	return 0;
1525 }
1526 
1527 /**
1528  * scribble_len - return the required size of the scribble region
1529  * @num - total number of disks in the array
1530  *
1531  * The size must be enough to contain:
1532  * 1/ a struct page pointer for each device in the array +2
1533  * 2/ room to convert each entry in (1) to its corresponding dma
1534  *    (dma_map_page()) or page (page_address()) address.
1535  *
1536  * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
1537  * calculate over all devices (not just the data blocks), using zeros in place
1538  * of the P and Q blocks.
1539  */
1540 static size_t scribble_len(int num)
1541 {
1542 	size_t len;
1543 
1544 	len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
1545 
1546 	return len;
1547 }
1548 
1549 static int resize_stripes(struct r5conf *conf, int newsize)
1550 {
1551 	/* Make all the stripes able to hold 'newsize' devices.
1552 	 * New slots in each stripe get 'page' set to a new page.
1553 	 *
1554 	 * This happens in stages:
1555 	 * 1/ create a new kmem_cache and allocate the required number of
1556 	 *    stripe_heads.
1557 	 * 2/ gather all the old stripe_heads and transfer the pages across
1558 	 *    to the new stripe_heads.  This will have the side effect of
1559 	 *    freezing the array as once all stripe_heads have been collected,
1560 	 *    no IO will be possible.  Old stripe heads are freed once their
1561 	 *    pages have been transferred over, and the old kmem_cache is
1562 	 *    freed when all stripes are done.
1563 	 * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
1564 	 *    we simple return a failre status - no need to clean anything up.
1565 	 * 4/ allocate new pages for the new slots in the new stripe_heads.
1566 	 *    If this fails, we don't bother trying the shrink the
1567 	 *    stripe_heads down again, we just leave them as they are.
1568 	 *    As each stripe_head is processed the new one is released into
1569 	 *    active service.
1570 	 *
1571 	 * Once step2 is started, we cannot afford to wait for a write,
1572 	 * so we use GFP_NOIO allocations.
1573 	 */
1574 	struct stripe_head *osh, *nsh;
1575 	LIST_HEAD(newstripes);
1576 	struct disk_info *ndisks;
1577 	unsigned long cpu;
1578 	int err;
1579 	struct kmem_cache *sc;
1580 	int i;
1581 
1582 	if (newsize <= conf->pool_size)
1583 		return 0; /* never bother to shrink */
1584 
1585 	err = md_allow_write(conf->mddev);
1586 	if (err)
1587 		return err;
1588 
1589 	/* Step 1 */
1590 	sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
1591 			       sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
1592 			       0, 0, NULL);
1593 	if (!sc)
1594 		return -ENOMEM;
1595 
1596 	for (i = conf->max_nr_stripes; i; i--) {
1597 		nsh = kmem_cache_zalloc(sc, GFP_KERNEL);
1598 		if (!nsh)
1599 			break;
1600 
1601 		nsh->raid_conf = conf;
1602 		spin_lock_init(&nsh->stripe_lock);
1603 
1604 		list_add(&nsh->lru, &newstripes);
1605 	}
1606 	if (i) {
1607 		/* didn't get enough, give up */
1608 		while (!list_empty(&newstripes)) {
1609 			nsh = list_entry(newstripes.next, struct stripe_head, lru);
1610 			list_del(&nsh->lru);
1611 			kmem_cache_free(sc, nsh);
1612 		}
1613 		kmem_cache_destroy(sc);
1614 		return -ENOMEM;
1615 	}
1616 	/* Step 2 - Must use GFP_NOIO now.
1617 	 * OK, we have enough stripes, start collecting inactive
1618 	 * stripes and copying them over
1619 	 */
1620 	list_for_each_entry(nsh, &newstripes, lru) {
1621 		spin_lock_irq(&conf->device_lock);
1622 		wait_event_lock_irq(conf->wait_for_stripe,
1623 				    !list_empty(&conf->inactive_list),
1624 				    conf->device_lock);
1625 		osh = get_free_stripe(conf);
1626 		spin_unlock_irq(&conf->device_lock);
1627 		atomic_set(&nsh->count, 1);
1628 		for(i=0; i<conf->pool_size; i++)
1629 			nsh->dev[i].page = osh->dev[i].page;
1630 		for( ; i<newsize; i++)
1631 			nsh->dev[i].page = NULL;
1632 		kmem_cache_free(conf->slab_cache, osh);
1633 	}
1634 	kmem_cache_destroy(conf->slab_cache);
1635 
1636 	/* Step 3.
1637 	 * At this point, we are holding all the stripes so the array
1638 	 * is completely stalled, so now is a good time to resize
1639 	 * conf->disks and the scribble region
1640 	 */
1641 	ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
1642 	if (ndisks) {
1643 		for (i=0; i<conf->raid_disks; i++)
1644 			ndisks[i] = conf->disks[i];
1645 		kfree(conf->disks);
1646 		conf->disks = ndisks;
1647 	} else
1648 		err = -ENOMEM;
1649 
1650 	get_online_cpus();
1651 	conf->scribble_len = scribble_len(newsize);
1652 	for_each_present_cpu(cpu) {
1653 		struct raid5_percpu *percpu;
1654 		void *scribble;
1655 
1656 		percpu = per_cpu_ptr(conf->percpu, cpu);
1657 		scribble = kmalloc(conf->scribble_len, GFP_NOIO);
1658 
1659 		if (scribble) {
1660 			kfree(percpu->scribble);
1661 			percpu->scribble = scribble;
1662 		} else {
1663 			err = -ENOMEM;
1664 			break;
1665 		}
1666 	}
1667 	put_online_cpus();
1668 
1669 	/* Step 4, return new stripes to service */
1670 	while(!list_empty(&newstripes)) {
1671 		nsh = list_entry(newstripes.next, struct stripe_head, lru);
1672 		list_del_init(&nsh->lru);
1673 
1674 		for (i=conf->raid_disks; i < newsize; i++)
1675 			if (nsh->dev[i].page == NULL) {
1676 				struct page *p = alloc_page(GFP_NOIO);
1677 				nsh->dev[i].page = p;
1678 				if (!p)
1679 					err = -ENOMEM;
1680 			}
1681 		release_stripe(nsh);
1682 	}
1683 	/* critical section pass, GFP_NOIO no longer needed */
1684 
1685 	conf->slab_cache = sc;
1686 	conf->active_name = 1-conf->active_name;
1687 	conf->pool_size = newsize;
1688 	return err;
1689 }
1690 
1691 static int drop_one_stripe(struct r5conf *conf)
1692 {
1693 	struct stripe_head *sh;
1694 
1695 	spin_lock_irq(&conf->device_lock);
1696 	sh = get_free_stripe(conf);
1697 	spin_unlock_irq(&conf->device_lock);
1698 	if (!sh)
1699 		return 0;
1700 	BUG_ON(atomic_read(&sh->count));
1701 	shrink_buffers(sh);
1702 	kmem_cache_free(conf->slab_cache, sh);
1703 	atomic_dec(&conf->active_stripes);
1704 	return 1;
1705 }
1706 
1707 static void shrink_stripes(struct r5conf *conf)
1708 {
1709 	while (drop_one_stripe(conf))
1710 		;
1711 
1712 	if (conf->slab_cache)
1713 		kmem_cache_destroy(conf->slab_cache);
1714 	conf->slab_cache = NULL;
1715 }
1716 
1717 static void raid5_end_read_request(struct bio * bi, int error)
1718 {
1719 	struct stripe_head *sh = bi->bi_private;
1720 	struct r5conf *conf = sh->raid_conf;
1721 	int disks = sh->disks, i;
1722 	int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1723 	char b[BDEVNAME_SIZE];
1724 	struct md_rdev *rdev = NULL;
1725 	sector_t s;
1726 
1727 	for (i=0 ; i<disks; i++)
1728 		if (bi == &sh->dev[i].req)
1729 			break;
1730 
1731 	pr_debug("end_read_request %llu/%d, count: %d, uptodate %d.\n",
1732 		(unsigned long long)sh->sector, i, atomic_read(&sh->count),
1733 		uptodate);
1734 	if (i == disks) {
1735 		BUG();
1736 		return;
1737 	}
1738 	if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
1739 		/* If replacement finished while this request was outstanding,
1740 		 * 'replacement' might be NULL already.
1741 		 * In that case it moved down to 'rdev'.
1742 		 * rdev is not removed until all requests are finished.
1743 		 */
1744 		rdev = conf->disks[i].replacement;
1745 	if (!rdev)
1746 		rdev = conf->disks[i].rdev;
1747 
1748 	if (use_new_offset(conf, sh))
1749 		s = sh->sector + rdev->new_data_offset;
1750 	else
1751 		s = sh->sector + rdev->data_offset;
1752 	if (uptodate) {
1753 		set_bit(R5_UPTODATE, &sh->dev[i].flags);
1754 		if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
1755 			/* Note that this cannot happen on a
1756 			 * replacement device.  We just fail those on
1757 			 * any error
1758 			 */
1759 			printk_ratelimited(
1760 				KERN_INFO
1761 				"md/raid:%s: read error corrected"
1762 				" (%lu sectors at %llu on %s)\n",
1763 				mdname(conf->mddev), STRIPE_SECTORS,
1764 				(unsigned long long)s,
1765 				bdevname(rdev->bdev, b));
1766 			atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
1767 			clear_bit(R5_ReadError, &sh->dev[i].flags);
1768 			clear_bit(R5_ReWrite, &sh->dev[i].flags);
1769 		} else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
1770 			clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
1771 
1772 		if (atomic_read(&rdev->read_errors))
1773 			atomic_set(&rdev->read_errors, 0);
1774 	} else {
1775 		const char *bdn = bdevname(rdev->bdev, b);
1776 		int retry = 0;
1777 		int set_bad = 0;
1778 
1779 		clear_bit(R5_UPTODATE, &sh->dev[i].flags);
1780 		atomic_inc(&rdev->read_errors);
1781 		if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
1782 			printk_ratelimited(
1783 				KERN_WARNING
1784 				"md/raid:%s: read error on replacement device "
1785 				"(sector %llu on %s).\n",
1786 				mdname(conf->mddev),
1787 				(unsigned long long)s,
1788 				bdn);
1789 		else if (conf->mddev->degraded >= conf->max_degraded) {
1790 			set_bad = 1;
1791 			printk_ratelimited(
1792 				KERN_WARNING
1793 				"md/raid:%s: read error not correctable "
1794 				"(sector %llu on %s).\n",
1795 				mdname(conf->mddev),
1796 				(unsigned long long)s,
1797 				bdn);
1798 		} else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
1799 			/* Oh, no!!! */
1800 			set_bad = 1;
1801 			printk_ratelimited(
1802 				KERN_WARNING
1803 				"md/raid:%s: read error NOT corrected!! "
1804 				"(sector %llu on %s).\n",
1805 				mdname(conf->mddev),
1806 				(unsigned long long)s,
1807 				bdn);
1808 		} else if (atomic_read(&rdev->read_errors)
1809 			 > conf->max_nr_stripes)
1810 			printk(KERN_WARNING
1811 			       "md/raid:%s: Too many read errors, failing device %s.\n",
1812 			       mdname(conf->mddev), bdn);
1813 		else
1814 			retry = 1;
1815 		if (retry)
1816 			if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
1817 				set_bit(R5_ReadError, &sh->dev[i].flags);
1818 				clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
1819 			} else
1820 				set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
1821 		else {
1822 			clear_bit(R5_ReadError, &sh->dev[i].flags);
1823 			clear_bit(R5_ReWrite, &sh->dev[i].flags);
1824 			if (!(set_bad
1825 			      && test_bit(In_sync, &rdev->flags)
1826 			      && rdev_set_badblocks(
1827 				      rdev, sh->sector, STRIPE_SECTORS, 0)))
1828 				md_error(conf->mddev, rdev);
1829 		}
1830 	}
1831 	rdev_dec_pending(rdev, conf->mddev);
1832 	clear_bit(R5_LOCKED, &sh->dev[i].flags);
1833 	set_bit(STRIPE_HANDLE, &sh->state);
1834 	release_stripe(sh);
1835 }
1836 
1837 static void raid5_end_write_request(struct bio *bi, int error)
1838 {
1839 	struct stripe_head *sh = bi->bi_private;
1840 	struct r5conf *conf = sh->raid_conf;
1841 	int disks = sh->disks, i;
1842 	struct md_rdev *uninitialized_var(rdev);
1843 	int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1844 	sector_t first_bad;
1845 	int bad_sectors;
1846 	int replacement = 0;
1847 
1848 	for (i = 0 ; i < disks; i++) {
1849 		if (bi == &sh->dev[i].req) {
1850 			rdev = conf->disks[i].rdev;
1851 			break;
1852 		}
1853 		if (bi == &sh->dev[i].rreq) {
1854 			rdev = conf->disks[i].replacement;
1855 			if (rdev)
1856 				replacement = 1;
1857 			else
1858 				/* rdev was removed and 'replacement'
1859 				 * replaced it.  rdev is not removed
1860 				 * until all requests are finished.
1861 				 */
1862 				rdev = conf->disks[i].rdev;
1863 			break;
1864 		}
1865 	}
1866 	pr_debug("end_write_request %llu/%d, count %d, uptodate: %d.\n",
1867 		(unsigned long long)sh->sector, i, atomic_read(&sh->count),
1868 		uptodate);
1869 	if (i == disks) {
1870 		BUG();
1871 		return;
1872 	}
1873 
1874 	if (replacement) {
1875 		if (!uptodate)
1876 			md_error(conf->mddev, rdev);
1877 		else if (is_badblock(rdev, sh->sector,
1878 				     STRIPE_SECTORS,
1879 				     &first_bad, &bad_sectors))
1880 			set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
1881 	} else {
1882 		if (!uptodate) {
1883 			set_bit(WriteErrorSeen, &rdev->flags);
1884 			set_bit(R5_WriteError, &sh->dev[i].flags);
1885 			if (!test_and_set_bit(WantReplacement, &rdev->flags))
1886 				set_bit(MD_RECOVERY_NEEDED,
1887 					&rdev->mddev->recovery);
1888 		} else if (is_badblock(rdev, sh->sector,
1889 				       STRIPE_SECTORS,
1890 				       &first_bad, &bad_sectors))
1891 			set_bit(R5_MadeGood, &sh->dev[i].flags);
1892 	}
1893 	rdev_dec_pending(rdev, conf->mddev);
1894 
1895 	if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
1896 		clear_bit(R5_LOCKED, &sh->dev[i].flags);
1897 	set_bit(STRIPE_HANDLE, &sh->state);
1898 	release_stripe(sh);
1899 }
1900 
1901 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous);
1902 
1903 static void raid5_build_block(struct stripe_head *sh, int i, int previous)
1904 {
1905 	struct r5dev *dev = &sh->dev[i];
1906 
1907 	bio_init(&dev->req);
1908 	dev->req.bi_io_vec = &dev->vec;
1909 	dev->req.bi_vcnt++;
1910 	dev->req.bi_max_vecs++;
1911 	dev->req.bi_private = sh;
1912 	dev->vec.bv_page = dev->page;
1913 
1914 	bio_init(&dev->rreq);
1915 	dev->rreq.bi_io_vec = &dev->rvec;
1916 	dev->rreq.bi_vcnt++;
1917 	dev->rreq.bi_max_vecs++;
1918 	dev->rreq.bi_private = sh;
1919 	dev->rvec.bv_page = dev->page;
1920 
1921 	dev->flags = 0;
1922 	dev->sector = compute_blocknr(sh, i, previous);
1923 }
1924 
1925 static void error(struct mddev *mddev, struct md_rdev *rdev)
1926 {
1927 	char b[BDEVNAME_SIZE];
1928 	struct r5conf *conf = mddev->private;
1929 	unsigned long flags;
1930 	pr_debug("raid456: error called\n");
1931 
1932 	spin_lock_irqsave(&conf->device_lock, flags);
1933 	clear_bit(In_sync, &rdev->flags);
1934 	mddev->degraded = calc_degraded(conf);
1935 	spin_unlock_irqrestore(&conf->device_lock, flags);
1936 	set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1937 
1938 	set_bit(Blocked, &rdev->flags);
1939 	set_bit(Faulty, &rdev->flags);
1940 	set_bit(MD_CHANGE_DEVS, &mddev->flags);
1941 	printk(KERN_ALERT
1942 	       "md/raid:%s: Disk failure on %s, disabling device.\n"
1943 	       "md/raid:%s: Operation continuing on %d devices.\n",
1944 	       mdname(mddev),
1945 	       bdevname(rdev->bdev, b),
1946 	       mdname(mddev),
1947 	       conf->raid_disks - mddev->degraded);
1948 }
1949 
1950 /*
1951  * Input: a 'big' sector number,
1952  * Output: index of the data and parity disk, and the sector # in them.
1953  */
1954 static sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
1955 				     int previous, int *dd_idx,
1956 				     struct stripe_head *sh)
1957 {
1958 	sector_t stripe, stripe2;
1959 	sector_t chunk_number;
1960 	unsigned int chunk_offset;
1961 	int pd_idx, qd_idx;
1962 	int ddf_layout = 0;
1963 	sector_t new_sector;
1964 	int algorithm = previous ? conf->prev_algo
1965 				 : conf->algorithm;
1966 	int sectors_per_chunk = previous ? conf->prev_chunk_sectors
1967 					 : conf->chunk_sectors;
1968 	int raid_disks = previous ? conf->previous_raid_disks
1969 				  : conf->raid_disks;
1970 	int data_disks = raid_disks - conf->max_degraded;
1971 
1972 	/* First compute the information on this sector */
1973 
1974 	/*
1975 	 * Compute the chunk number and the sector offset inside the chunk
1976 	 */
1977 	chunk_offset = sector_div(r_sector, sectors_per_chunk);
1978 	chunk_number = r_sector;
1979 
1980 	/*
1981 	 * Compute the stripe number
1982 	 */
1983 	stripe = chunk_number;
1984 	*dd_idx = sector_div(stripe, data_disks);
1985 	stripe2 = stripe;
1986 	/*
1987 	 * Select the parity disk based on the user selected algorithm.
1988 	 */
1989 	pd_idx = qd_idx = -1;
1990 	switch(conf->level) {
1991 	case 4:
1992 		pd_idx = data_disks;
1993 		break;
1994 	case 5:
1995 		switch (algorithm) {
1996 		case ALGORITHM_LEFT_ASYMMETRIC:
1997 			pd_idx = data_disks - sector_div(stripe2, raid_disks);
1998 			if (*dd_idx >= pd_idx)
1999 				(*dd_idx)++;
2000 			break;
2001 		case ALGORITHM_RIGHT_ASYMMETRIC:
2002 			pd_idx = sector_div(stripe2, raid_disks);
2003 			if (*dd_idx >= pd_idx)
2004 				(*dd_idx)++;
2005 			break;
2006 		case ALGORITHM_LEFT_SYMMETRIC:
2007 			pd_idx = data_disks - sector_div(stripe2, raid_disks);
2008 			*dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2009 			break;
2010 		case ALGORITHM_RIGHT_SYMMETRIC:
2011 			pd_idx = sector_div(stripe2, raid_disks);
2012 			*dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2013 			break;
2014 		case ALGORITHM_PARITY_0:
2015 			pd_idx = 0;
2016 			(*dd_idx)++;
2017 			break;
2018 		case ALGORITHM_PARITY_N:
2019 			pd_idx = data_disks;
2020 			break;
2021 		default:
2022 			BUG();
2023 		}
2024 		break;
2025 	case 6:
2026 
2027 		switch (algorithm) {
2028 		case ALGORITHM_LEFT_ASYMMETRIC:
2029 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2030 			qd_idx = pd_idx + 1;
2031 			if (pd_idx == raid_disks-1) {
2032 				(*dd_idx)++;	/* Q D D D P */
2033 				qd_idx = 0;
2034 			} else if (*dd_idx >= pd_idx)
2035 				(*dd_idx) += 2; /* D D P Q D */
2036 			break;
2037 		case ALGORITHM_RIGHT_ASYMMETRIC:
2038 			pd_idx = sector_div(stripe2, raid_disks);
2039 			qd_idx = pd_idx + 1;
2040 			if (pd_idx == raid_disks-1) {
2041 				(*dd_idx)++;	/* Q D D D P */
2042 				qd_idx = 0;
2043 			} else if (*dd_idx >= pd_idx)
2044 				(*dd_idx) += 2; /* D D P Q D */
2045 			break;
2046 		case ALGORITHM_LEFT_SYMMETRIC:
2047 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2048 			qd_idx = (pd_idx + 1) % raid_disks;
2049 			*dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2050 			break;
2051 		case ALGORITHM_RIGHT_SYMMETRIC:
2052 			pd_idx = sector_div(stripe2, raid_disks);
2053 			qd_idx = (pd_idx + 1) % raid_disks;
2054 			*dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2055 			break;
2056 
2057 		case ALGORITHM_PARITY_0:
2058 			pd_idx = 0;
2059 			qd_idx = 1;
2060 			(*dd_idx) += 2;
2061 			break;
2062 		case ALGORITHM_PARITY_N:
2063 			pd_idx = data_disks;
2064 			qd_idx = data_disks + 1;
2065 			break;
2066 
2067 		case ALGORITHM_ROTATING_ZERO_RESTART:
2068 			/* Exactly the same as RIGHT_ASYMMETRIC, but or
2069 			 * of blocks for computing Q is different.
2070 			 */
2071 			pd_idx = sector_div(stripe2, raid_disks);
2072 			qd_idx = pd_idx + 1;
2073 			if (pd_idx == raid_disks-1) {
2074 				(*dd_idx)++;	/* Q D D D P */
2075 				qd_idx = 0;
2076 			} else if (*dd_idx >= pd_idx)
2077 				(*dd_idx) += 2; /* D D P Q D */
2078 			ddf_layout = 1;
2079 			break;
2080 
2081 		case ALGORITHM_ROTATING_N_RESTART:
2082 			/* Same a left_asymmetric, by first stripe is
2083 			 * D D D P Q  rather than
2084 			 * Q D D D P
2085 			 */
2086 			stripe2 += 1;
2087 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2088 			qd_idx = pd_idx + 1;
2089 			if (pd_idx == raid_disks-1) {
2090 				(*dd_idx)++;	/* Q D D D P */
2091 				qd_idx = 0;
2092 			} else if (*dd_idx >= pd_idx)
2093 				(*dd_idx) += 2; /* D D P Q D */
2094 			ddf_layout = 1;
2095 			break;
2096 
2097 		case ALGORITHM_ROTATING_N_CONTINUE:
2098 			/* Same as left_symmetric but Q is before P */
2099 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2100 			qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2101 			*dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2102 			ddf_layout = 1;
2103 			break;
2104 
2105 		case ALGORITHM_LEFT_ASYMMETRIC_6:
2106 			/* RAID5 left_asymmetric, with Q on last device */
2107 			pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2108 			if (*dd_idx >= pd_idx)
2109 				(*dd_idx)++;
2110 			qd_idx = raid_disks - 1;
2111 			break;
2112 
2113 		case ALGORITHM_RIGHT_ASYMMETRIC_6:
2114 			pd_idx = sector_div(stripe2, raid_disks-1);
2115 			if (*dd_idx >= pd_idx)
2116 				(*dd_idx)++;
2117 			qd_idx = raid_disks - 1;
2118 			break;
2119 
2120 		case ALGORITHM_LEFT_SYMMETRIC_6:
2121 			pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2122 			*dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2123 			qd_idx = raid_disks - 1;
2124 			break;
2125 
2126 		case ALGORITHM_RIGHT_SYMMETRIC_6:
2127 			pd_idx = sector_div(stripe2, raid_disks-1);
2128 			*dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2129 			qd_idx = raid_disks - 1;
2130 			break;
2131 
2132 		case ALGORITHM_PARITY_0_6:
2133 			pd_idx = 0;
2134 			(*dd_idx)++;
2135 			qd_idx = raid_disks - 1;
2136 			break;
2137 
2138 		default:
2139 			BUG();
2140 		}
2141 		break;
2142 	}
2143 
2144 	if (sh) {
2145 		sh->pd_idx = pd_idx;
2146 		sh->qd_idx = qd_idx;
2147 		sh->ddf_layout = ddf_layout;
2148 	}
2149 	/*
2150 	 * Finally, compute the new sector number
2151 	 */
2152 	new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2153 	return new_sector;
2154 }
2155 
2156 
2157 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous)
2158 {
2159 	struct r5conf *conf = sh->raid_conf;
2160 	int raid_disks = sh->disks;
2161 	int data_disks = raid_disks - conf->max_degraded;
2162 	sector_t new_sector = sh->sector, check;
2163 	int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2164 					 : conf->chunk_sectors;
2165 	int algorithm = previous ? conf->prev_algo
2166 				 : conf->algorithm;
2167 	sector_t stripe;
2168 	int chunk_offset;
2169 	sector_t chunk_number;
2170 	int dummy1, dd_idx = i;
2171 	sector_t r_sector;
2172 	struct stripe_head sh2;
2173 
2174 
2175 	chunk_offset = sector_div(new_sector, sectors_per_chunk);
2176 	stripe = new_sector;
2177 
2178 	if (i == sh->pd_idx)
2179 		return 0;
2180 	switch(conf->level) {
2181 	case 4: break;
2182 	case 5:
2183 		switch (algorithm) {
2184 		case ALGORITHM_LEFT_ASYMMETRIC:
2185 		case ALGORITHM_RIGHT_ASYMMETRIC:
2186 			if (i > sh->pd_idx)
2187 				i--;
2188 			break;
2189 		case ALGORITHM_LEFT_SYMMETRIC:
2190 		case ALGORITHM_RIGHT_SYMMETRIC:
2191 			if (i < sh->pd_idx)
2192 				i += raid_disks;
2193 			i -= (sh->pd_idx + 1);
2194 			break;
2195 		case ALGORITHM_PARITY_0:
2196 			i -= 1;
2197 			break;
2198 		case ALGORITHM_PARITY_N:
2199 			break;
2200 		default:
2201 			BUG();
2202 		}
2203 		break;
2204 	case 6:
2205 		if (i == sh->qd_idx)
2206 			return 0; /* It is the Q disk */
2207 		switch (algorithm) {
2208 		case ALGORITHM_LEFT_ASYMMETRIC:
2209 		case ALGORITHM_RIGHT_ASYMMETRIC:
2210 		case ALGORITHM_ROTATING_ZERO_RESTART:
2211 		case ALGORITHM_ROTATING_N_RESTART:
2212 			if (sh->pd_idx == raid_disks-1)
2213 				i--;	/* Q D D D P */
2214 			else if (i > sh->pd_idx)
2215 				i -= 2; /* D D P Q D */
2216 			break;
2217 		case ALGORITHM_LEFT_SYMMETRIC:
2218 		case ALGORITHM_RIGHT_SYMMETRIC:
2219 			if (sh->pd_idx == raid_disks-1)
2220 				i--; /* Q D D D P */
2221 			else {
2222 				/* D D P Q D */
2223 				if (i < sh->pd_idx)
2224 					i += raid_disks;
2225 				i -= (sh->pd_idx + 2);
2226 			}
2227 			break;
2228 		case ALGORITHM_PARITY_0:
2229 			i -= 2;
2230 			break;
2231 		case ALGORITHM_PARITY_N:
2232 			break;
2233 		case ALGORITHM_ROTATING_N_CONTINUE:
2234 			/* Like left_symmetric, but P is before Q */
2235 			if (sh->pd_idx == 0)
2236 				i--;	/* P D D D Q */
2237 			else {
2238 				/* D D Q P D */
2239 				if (i < sh->pd_idx)
2240 					i += raid_disks;
2241 				i -= (sh->pd_idx + 1);
2242 			}
2243 			break;
2244 		case ALGORITHM_LEFT_ASYMMETRIC_6:
2245 		case ALGORITHM_RIGHT_ASYMMETRIC_6:
2246 			if (i > sh->pd_idx)
2247 				i--;
2248 			break;
2249 		case ALGORITHM_LEFT_SYMMETRIC_6:
2250 		case ALGORITHM_RIGHT_SYMMETRIC_6:
2251 			if (i < sh->pd_idx)
2252 				i += data_disks + 1;
2253 			i -= (sh->pd_idx + 1);
2254 			break;
2255 		case ALGORITHM_PARITY_0_6:
2256 			i -= 1;
2257 			break;
2258 		default:
2259 			BUG();
2260 		}
2261 		break;
2262 	}
2263 
2264 	chunk_number = stripe * data_disks + i;
2265 	r_sector = chunk_number * sectors_per_chunk + chunk_offset;
2266 
2267 	check = raid5_compute_sector(conf, r_sector,
2268 				     previous, &dummy1, &sh2);
2269 	if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
2270 		|| sh2.qd_idx != sh->qd_idx) {
2271 		printk(KERN_ERR "md/raid:%s: compute_blocknr: map not correct\n",
2272 		       mdname(conf->mddev));
2273 		return 0;
2274 	}
2275 	return r_sector;
2276 }
2277 
2278 
2279 static void
2280 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
2281 			 int rcw, int expand)
2282 {
2283 	int i, pd_idx = sh->pd_idx, disks = sh->disks;
2284 	struct r5conf *conf = sh->raid_conf;
2285 	int level = conf->level;
2286 
2287 	if (rcw) {
2288 
2289 		for (i = disks; i--; ) {
2290 			struct r5dev *dev = &sh->dev[i];
2291 
2292 			if (dev->towrite) {
2293 				set_bit(R5_LOCKED, &dev->flags);
2294 				set_bit(R5_Wantdrain, &dev->flags);
2295 				if (!expand)
2296 					clear_bit(R5_UPTODATE, &dev->flags);
2297 				s->locked++;
2298 			}
2299 		}
2300 		/* if we are not expanding this is a proper write request, and
2301 		 * there will be bios with new data to be drained into the
2302 		 * stripe cache
2303 		 */
2304 		if (!expand) {
2305 			if (!s->locked)
2306 				/* False alarm, nothing to do */
2307 				return;
2308 			sh->reconstruct_state = reconstruct_state_drain_run;
2309 			set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2310 		} else
2311 			sh->reconstruct_state = reconstruct_state_run;
2312 
2313 		set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2314 
2315 		if (s->locked + conf->max_degraded == disks)
2316 			if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
2317 				atomic_inc(&conf->pending_full_writes);
2318 	} else {
2319 		BUG_ON(level == 6);
2320 		BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
2321 			test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
2322 
2323 		for (i = disks; i--; ) {
2324 			struct r5dev *dev = &sh->dev[i];
2325 			if (i == pd_idx)
2326 				continue;
2327 
2328 			if (dev->towrite &&
2329 			    (test_bit(R5_UPTODATE, &dev->flags) ||
2330 			     test_bit(R5_Wantcompute, &dev->flags))) {
2331 				set_bit(R5_Wantdrain, &dev->flags);
2332 				set_bit(R5_LOCKED, &dev->flags);
2333 				clear_bit(R5_UPTODATE, &dev->flags);
2334 				s->locked++;
2335 			}
2336 		}
2337 		if (!s->locked)
2338 			/* False alarm - nothing to do */
2339 			return;
2340 		sh->reconstruct_state = reconstruct_state_prexor_drain_run;
2341 		set_bit(STRIPE_OP_PREXOR, &s->ops_request);
2342 		set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2343 		set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2344 	}
2345 
2346 	/* keep the parity disk(s) locked while asynchronous operations
2347 	 * are in flight
2348 	 */
2349 	set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
2350 	clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2351 	s->locked++;
2352 
2353 	if (level == 6) {
2354 		int qd_idx = sh->qd_idx;
2355 		struct r5dev *dev = &sh->dev[qd_idx];
2356 
2357 		set_bit(R5_LOCKED, &dev->flags);
2358 		clear_bit(R5_UPTODATE, &dev->flags);
2359 		s->locked++;
2360 	}
2361 
2362 	pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2363 		__func__, (unsigned long long)sh->sector,
2364 		s->locked, s->ops_request);
2365 }
2366 
2367 /*
2368  * Each stripe/dev can have one or more bion attached.
2369  * toread/towrite point to the first in a chain.
2370  * The bi_next chain must be in order.
2371  */
2372 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx, int forwrite)
2373 {
2374 	struct bio **bip;
2375 	struct r5conf *conf = sh->raid_conf;
2376 	int firstwrite=0;
2377 
2378 	pr_debug("adding bi b#%llu to stripe s#%llu\n",
2379 		(unsigned long long)bi->bi_sector,
2380 		(unsigned long long)sh->sector);
2381 
2382 	/*
2383 	 * If several bio share a stripe. The bio bi_phys_segments acts as a
2384 	 * reference count to avoid race. The reference count should already be
2385 	 * increased before this function is called (for example, in
2386 	 * make_request()), so other bio sharing this stripe will not free the
2387 	 * stripe. If a stripe is owned by one stripe, the stripe lock will
2388 	 * protect it.
2389 	 */
2390 	spin_lock_irq(&sh->stripe_lock);
2391 	if (forwrite) {
2392 		bip = &sh->dev[dd_idx].towrite;
2393 		if (*bip == NULL)
2394 			firstwrite = 1;
2395 	} else
2396 		bip = &sh->dev[dd_idx].toread;
2397 	while (*bip && (*bip)->bi_sector < bi->bi_sector) {
2398 		if ((*bip)->bi_sector + ((*bip)->bi_size >> 9) > bi->bi_sector)
2399 			goto overlap;
2400 		bip = & (*bip)->bi_next;
2401 	}
2402 	if (*bip && (*bip)->bi_sector < bi->bi_sector + ((bi->bi_size)>>9))
2403 		goto overlap;
2404 
2405 	BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
2406 	if (*bip)
2407 		bi->bi_next = *bip;
2408 	*bip = bi;
2409 	raid5_inc_bi_active_stripes(bi);
2410 
2411 	if (forwrite) {
2412 		/* check if page is covered */
2413 		sector_t sector = sh->dev[dd_idx].sector;
2414 		for (bi=sh->dev[dd_idx].towrite;
2415 		     sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
2416 			     bi && bi->bi_sector <= sector;
2417 		     bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
2418 			if (bi->bi_sector + (bi->bi_size>>9) >= sector)
2419 				sector = bi->bi_sector + (bi->bi_size>>9);
2420 		}
2421 		if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
2422 			set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags);
2423 	}
2424 
2425 	pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
2426 		(unsigned long long)(*bip)->bi_sector,
2427 		(unsigned long long)sh->sector, dd_idx);
2428 	spin_unlock_irq(&sh->stripe_lock);
2429 
2430 	if (conf->mddev->bitmap && firstwrite) {
2431 		bitmap_startwrite(conf->mddev->bitmap, sh->sector,
2432 				  STRIPE_SECTORS, 0);
2433 		sh->bm_seq = conf->seq_flush+1;
2434 		set_bit(STRIPE_BIT_DELAY, &sh->state);
2435 	}
2436 	return 1;
2437 
2438  overlap:
2439 	set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
2440 	spin_unlock_irq(&sh->stripe_lock);
2441 	return 0;
2442 }
2443 
2444 static void end_reshape(struct r5conf *conf);
2445 
2446 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
2447 			    struct stripe_head *sh)
2448 {
2449 	int sectors_per_chunk =
2450 		previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
2451 	int dd_idx;
2452 	int chunk_offset = sector_div(stripe, sectors_per_chunk);
2453 	int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
2454 
2455 	raid5_compute_sector(conf,
2456 			     stripe * (disks - conf->max_degraded)
2457 			     *sectors_per_chunk + chunk_offset,
2458 			     previous,
2459 			     &dd_idx, sh);
2460 }
2461 
2462 static void
2463 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
2464 				struct stripe_head_state *s, int disks,
2465 				struct bio **return_bi)
2466 {
2467 	int i;
2468 	for (i = disks; i--; ) {
2469 		struct bio *bi;
2470 		int bitmap_end = 0;
2471 
2472 		if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2473 			struct md_rdev *rdev;
2474 			rcu_read_lock();
2475 			rdev = rcu_dereference(conf->disks[i].rdev);
2476 			if (rdev && test_bit(In_sync, &rdev->flags))
2477 				atomic_inc(&rdev->nr_pending);
2478 			else
2479 				rdev = NULL;
2480 			rcu_read_unlock();
2481 			if (rdev) {
2482 				if (!rdev_set_badblocks(
2483 					    rdev,
2484 					    sh->sector,
2485 					    STRIPE_SECTORS, 0))
2486 					md_error(conf->mddev, rdev);
2487 				rdev_dec_pending(rdev, conf->mddev);
2488 			}
2489 		}
2490 		spin_lock_irq(&sh->stripe_lock);
2491 		/* fail all writes first */
2492 		bi = sh->dev[i].towrite;
2493 		sh->dev[i].towrite = NULL;
2494 		spin_unlock_irq(&sh->stripe_lock);
2495 		if (bi)
2496 			bitmap_end = 1;
2497 
2498 		if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2499 			wake_up(&conf->wait_for_overlap);
2500 
2501 		while (bi && bi->bi_sector <
2502 			sh->dev[i].sector + STRIPE_SECTORS) {
2503 			struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
2504 			clear_bit(BIO_UPTODATE, &bi->bi_flags);
2505 			if (!raid5_dec_bi_active_stripes(bi)) {
2506 				md_write_end(conf->mddev);
2507 				bi->bi_next = *return_bi;
2508 				*return_bi = bi;
2509 			}
2510 			bi = nextbi;
2511 		}
2512 		if (bitmap_end)
2513 			bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2514 				STRIPE_SECTORS, 0, 0);
2515 		bitmap_end = 0;
2516 		/* and fail all 'written' */
2517 		bi = sh->dev[i].written;
2518 		sh->dev[i].written = NULL;
2519 		if (bi) bitmap_end = 1;
2520 		while (bi && bi->bi_sector <
2521 		       sh->dev[i].sector + STRIPE_SECTORS) {
2522 			struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
2523 			clear_bit(BIO_UPTODATE, &bi->bi_flags);
2524 			if (!raid5_dec_bi_active_stripes(bi)) {
2525 				md_write_end(conf->mddev);
2526 				bi->bi_next = *return_bi;
2527 				*return_bi = bi;
2528 			}
2529 			bi = bi2;
2530 		}
2531 
2532 		/* fail any reads if this device is non-operational and
2533 		 * the data has not reached the cache yet.
2534 		 */
2535 		if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
2536 		    (!test_bit(R5_Insync, &sh->dev[i].flags) ||
2537 		      test_bit(R5_ReadError, &sh->dev[i].flags))) {
2538 			spin_lock_irq(&sh->stripe_lock);
2539 			bi = sh->dev[i].toread;
2540 			sh->dev[i].toread = NULL;
2541 			spin_unlock_irq(&sh->stripe_lock);
2542 			if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2543 				wake_up(&conf->wait_for_overlap);
2544 			while (bi && bi->bi_sector <
2545 			       sh->dev[i].sector + STRIPE_SECTORS) {
2546 				struct bio *nextbi =
2547 					r5_next_bio(bi, sh->dev[i].sector);
2548 				clear_bit(BIO_UPTODATE, &bi->bi_flags);
2549 				if (!raid5_dec_bi_active_stripes(bi)) {
2550 					bi->bi_next = *return_bi;
2551 					*return_bi = bi;
2552 				}
2553 				bi = nextbi;
2554 			}
2555 		}
2556 		if (bitmap_end)
2557 			bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2558 					STRIPE_SECTORS, 0, 0);
2559 		/* If we were in the middle of a write the parity block might
2560 		 * still be locked - so just clear all R5_LOCKED flags
2561 		 */
2562 		clear_bit(R5_LOCKED, &sh->dev[i].flags);
2563 	}
2564 
2565 	if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2566 		if (atomic_dec_and_test(&conf->pending_full_writes))
2567 			md_wakeup_thread(conf->mddev->thread);
2568 }
2569 
2570 static void
2571 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
2572 		   struct stripe_head_state *s)
2573 {
2574 	int abort = 0;
2575 	int i;
2576 
2577 	clear_bit(STRIPE_SYNCING, &sh->state);
2578 	if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
2579 		wake_up(&conf->wait_for_overlap);
2580 	s->syncing = 0;
2581 	s->replacing = 0;
2582 	/* There is nothing more to do for sync/check/repair.
2583 	 * Don't even need to abort as that is handled elsewhere
2584 	 * if needed, and not always wanted e.g. if there is a known
2585 	 * bad block here.
2586 	 * For recover/replace we need to record a bad block on all
2587 	 * non-sync devices, or abort the recovery
2588 	 */
2589 	if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
2590 		/* During recovery devices cannot be removed, so
2591 		 * locking and refcounting of rdevs is not needed
2592 		 */
2593 		for (i = 0; i < conf->raid_disks; i++) {
2594 			struct md_rdev *rdev = conf->disks[i].rdev;
2595 			if (rdev
2596 			    && !test_bit(Faulty, &rdev->flags)
2597 			    && !test_bit(In_sync, &rdev->flags)
2598 			    && !rdev_set_badblocks(rdev, sh->sector,
2599 						   STRIPE_SECTORS, 0))
2600 				abort = 1;
2601 			rdev = conf->disks[i].replacement;
2602 			if (rdev
2603 			    && !test_bit(Faulty, &rdev->flags)
2604 			    && !test_bit(In_sync, &rdev->flags)
2605 			    && !rdev_set_badblocks(rdev, sh->sector,
2606 						   STRIPE_SECTORS, 0))
2607 				abort = 1;
2608 		}
2609 		if (abort)
2610 			conf->recovery_disabled =
2611 				conf->mddev->recovery_disabled;
2612 	}
2613 	md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
2614 }
2615 
2616 static int want_replace(struct stripe_head *sh, int disk_idx)
2617 {
2618 	struct md_rdev *rdev;
2619 	int rv = 0;
2620 	/* Doing recovery so rcu locking not required */
2621 	rdev = sh->raid_conf->disks[disk_idx].replacement;
2622 	if (rdev
2623 	    && !test_bit(Faulty, &rdev->flags)
2624 	    && !test_bit(In_sync, &rdev->flags)
2625 	    && (rdev->recovery_offset <= sh->sector
2626 		|| rdev->mddev->recovery_cp <= sh->sector))
2627 		rv = 1;
2628 
2629 	return rv;
2630 }
2631 
2632 /* fetch_block - checks the given member device to see if its data needs
2633  * to be read or computed to satisfy a request.
2634  *
2635  * Returns 1 when no more member devices need to be checked, otherwise returns
2636  * 0 to tell the loop in handle_stripe_fill to continue
2637  */
2638 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
2639 		       int disk_idx, int disks)
2640 {
2641 	struct r5dev *dev = &sh->dev[disk_idx];
2642 	struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
2643 				  &sh->dev[s->failed_num[1]] };
2644 
2645 	/* is the data in this block needed, and can we get it? */
2646 	if (!test_bit(R5_LOCKED, &dev->flags) &&
2647 	    !test_bit(R5_UPTODATE, &dev->flags) &&
2648 	    (dev->toread ||
2649 	     (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
2650 	     s->syncing || s->expanding ||
2651 	     (s->replacing && want_replace(sh, disk_idx)) ||
2652 	     (s->failed >= 1 && fdev[0]->toread) ||
2653 	     (s->failed >= 2 && fdev[1]->toread) ||
2654 	     (sh->raid_conf->level <= 5 && s->failed && fdev[0]->towrite &&
2655 	      !test_bit(R5_OVERWRITE, &fdev[0]->flags)) ||
2656 	     (sh->raid_conf->level == 6 && s->failed && s->to_write))) {
2657 		/* we would like to get this block, possibly by computing it,
2658 		 * otherwise read it if the backing disk is insync
2659 		 */
2660 		BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
2661 		BUG_ON(test_bit(R5_Wantread, &dev->flags));
2662 		if ((s->uptodate == disks - 1) &&
2663 		    (s->failed && (disk_idx == s->failed_num[0] ||
2664 				   disk_idx == s->failed_num[1]))) {
2665 			/* have disk failed, and we're requested to fetch it;
2666 			 * do compute it
2667 			 */
2668 			pr_debug("Computing stripe %llu block %d\n",
2669 			       (unsigned long long)sh->sector, disk_idx);
2670 			set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2671 			set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2672 			set_bit(R5_Wantcompute, &dev->flags);
2673 			sh->ops.target = disk_idx;
2674 			sh->ops.target2 = -1; /* no 2nd target */
2675 			s->req_compute = 1;
2676 			/* Careful: from this point on 'uptodate' is in the eye
2677 			 * of raid_run_ops which services 'compute' operations
2678 			 * before writes. R5_Wantcompute flags a block that will
2679 			 * be R5_UPTODATE by the time it is needed for a
2680 			 * subsequent operation.
2681 			 */
2682 			s->uptodate++;
2683 			return 1;
2684 		} else if (s->uptodate == disks-2 && s->failed >= 2) {
2685 			/* Computing 2-failure is *very* expensive; only
2686 			 * do it if failed >= 2
2687 			 */
2688 			int other;
2689 			for (other = disks; other--; ) {
2690 				if (other == disk_idx)
2691 					continue;
2692 				if (!test_bit(R5_UPTODATE,
2693 				      &sh->dev[other].flags))
2694 					break;
2695 			}
2696 			BUG_ON(other < 0);
2697 			pr_debug("Computing stripe %llu blocks %d,%d\n",
2698 			       (unsigned long long)sh->sector,
2699 			       disk_idx, other);
2700 			set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2701 			set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2702 			set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
2703 			set_bit(R5_Wantcompute, &sh->dev[other].flags);
2704 			sh->ops.target = disk_idx;
2705 			sh->ops.target2 = other;
2706 			s->uptodate += 2;
2707 			s->req_compute = 1;
2708 			return 1;
2709 		} else if (test_bit(R5_Insync, &dev->flags)) {
2710 			set_bit(R5_LOCKED, &dev->flags);
2711 			set_bit(R5_Wantread, &dev->flags);
2712 			s->locked++;
2713 			pr_debug("Reading block %d (sync=%d)\n",
2714 				disk_idx, s->syncing);
2715 		}
2716 	}
2717 
2718 	return 0;
2719 }
2720 
2721 /**
2722  * handle_stripe_fill - read or compute data to satisfy pending requests.
2723  */
2724 static void handle_stripe_fill(struct stripe_head *sh,
2725 			       struct stripe_head_state *s,
2726 			       int disks)
2727 {
2728 	int i;
2729 
2730 	/* look for blocks to read/compute, skip this if a compute
2731 	 * is already in flight, or if the stripe contents are in the
2732 	 * midst of changing due to a write
2733 	 */
2734 	if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
2735 	    !sh->reconstruct_state)
2736 		for (i = disks; i--; )
2737 			if (fetch_block(sh, s, i, disks))
2738 				break;
2739 	set_bit(STRIPE_HANDLE, &sh->state);
2740 }
2741 
2742 
2743 /* handle_stripe_clean_event
2744  * any written block on an uptodate or failed drive can be returned.
2745  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
2746  * never LOCKED, so we don't need to test 'failed' directly.
2747  */
2748 static void handle_stripe_clean_event(struct r5conf *conf,
2749 	struct stripe_head *sh, int disks, struct bio **return_bi)
2750 {
2751 	int i;
2752 	struct r5dev *dev;
2753 	int discard_pending = 0;
2754 
2755 	for (i = disks; i--; )
2756 		if (sh->dev[i].written) {
2757 			dev = &sh->dev[i];
2758 			if (!test_bit(R5_LOCKED, &dev->flags) &&
2759 			    (test_bit(R5_UPTODATE, &dev->flags) ||
2760 			     test_bit(R5_Discard, &dev->flags))) {
2761 				/* We can return any write requests */
2762 				struct bio *wbi, *wbi2;
2763 				pr_debug("Return write for disc %d\n", i);
2764 				if (test_and_clear_bit(R5_Discard, &dev->flags))
2765 					clear_bit(R5_UPTODATE, &dev->flags);
2766 				wbi = dev->written;
2767 				dev->written = NULL;
2768 				while (wbi && wbi->bi_sector <
2769 					dev->sector + STRIPE_SECTORS) {
2770 					wbi2 = r5_next_bio(wbi, dev->sector);
2771 					if (!raid5_dec_bi_active_stripes(wbi)) {
2772 						md_write_end(conf->mddev);
2773 						wbi->bi_next = *return_bi;
2774 						*return_bi = wbi;
2775 					}
2776 					wbi = wbi2;
2777 				}
2778 				bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2779 						STRIPE_SECTORS,
2780 					 !test_bit(STRIPE_DEGRADED, &sh->state),
2781 						0);
2782 			} else if (test_bit(R5_Discard, &dev->flags))
2783 				discard_pending = 1;
2784 		}
2785 	if (!discard_pending &&
2786 	    test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
2787 		clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
2788 		clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
2789 		if (sh->qd_idx >= 0) {
2790 			clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
2791 			clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
2792 		}
2793 		/* now that discard is done we can proceed with any sync */
2794 		clear_bit(STRIPE_DISCARD, &sh->state);
2795 		if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
2796 			set_bit(STRIPE_HANDLE, &sh->state);
2797 
2798 	}
2799 
2800 	if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2801 		if (atomic_dec_and_test(&conf->pending_full_writes))
2802 			md_wakeup_thread(conf->mddev->thread);
2803 }
2804 
2805 static void handle_stripe_dirtying(struct r5conf *conf,
2806 				   struct stripe_head *sh,
2807 				   struct stripe_head_state *s,
2808 				   int disks)
2809 {
2810 	int rmw = 0, rcw = 0, i;
2811 	sector_t recovery_cp = conf->mddev->recovery_cp;
2812 
2813 	/* RAID6 requires 'rcw' in current implementation.
2814 	 * Otherwise, check whether resync is now happening or should start.
2815 	 * If yes, then the array is dirty (after unclean shutdown or
2816 	 * initial creation), so parity in some stripes might be inconsistent.
2817 	 * In this case, we need to always do reconstruct-write, to ensure
2818 	 * that in case of drive failure or read-error correction, we
2819 	 * generate correct data from the parity.
2820 	 */
2821 	if (conf->max_degraded == 2 ||
2822 	    (recovery_cp < MaxSector && sh->sector >= recovery_cp)) {
2823 		/* Calculate the real rcw later - for now make it
2824 		 * look like rcw is cheaper
2825 		 */
2826 		rcw = 1; rmw = 2;
2827 		pr_debug("force RCW max_degraded=%u, recovery_cp=%llu sh->sector=%llu\n",
2828 			 conf->max_degraded, (unsigned long long)recovery_cp,
2829 			 (unsigned long long)sh->sector);
2830 	} else for (i = disks; i--; ) {
2831 		/* would I have to read this buffer for read_modify_write */
2832 		struct r5dev *dev = &sh->dev[i];
2833 		if ((dev->towrite || i == sh->pd_idx) &&
2834 		    !test_bit(R5_LOCKED, &dev->flags) &&
2835 		    !(test_bit(R5_UPTODATE, &dev->flags) ||
2836 		      test_bit(R5_Wantcompute, &dev->flags))) {
2837 			if (test_bit(R5_Insync, &dev->flags))
2838 				rmw++;
2839 			else
2840 				rmw += 2*disks;  /* cannot read it */
2841 		}
2842 		/* Would I have to read this buffer for reconstruct_write */
2843 		if (!test_bit(R5_OVERWRITE, &dev->flags) && i != sh->pd_idx &&
2844 		    !test_bit(R5_LOCKED, &dev->flags) &&
2845 		    !(test_bit(R5_UPTODATE, &dev->flags) ||
2846 		    test_bit(R5_Wantcompute, &dev->flags))) {
2847 			if (test_bit(R5_Insync, &dev->flags)) rcw++;
2848 			else
2849 				rcw += 2*disks;
2850 		}
2851 	}
2852 	pr_debug("for sector %llu, rmw=%d rcw=%d\n",
2853 		(unsigned long long)sh->sector, rmw, rcw);
2854 	set_bit(STRIPE_HANDLE, &sh->state);
2855 	if (rmw < rcw && rmw > 0) {
2856 		/* prefer read-modify-write, but need to get some data */
2857 		if (conf->mddev->queue)
2858 			blk_add_trace_msg(conf->mddev->queue,
2859 					  "raid5 rmw %llu %d",
2860 					  (unsigned long long)sh->sector, rmw);
2861 		for (i = disks; i--; ) {
2862 			struct r5dev *dev = &sh->dev[i];
2863 			if ((dev->towrite || i == sh->pd_idx) &&
2864 			    !test_bit(R5_LOCKED, &dev->flags) &&
2865 			    !(test_bit(R5_UPTODATE, &dev->flags) ||
2866 			    test_bit(R5_Wantcompute, &dev->flags)) &&
2867 			    test_bit(R5_Insync, &dev->flags)) {
2868 				if (
2869 				  test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2870 					pr_debug("Read_old block "
2871 						 "%d for r-m-w\n", i);
2872 					set_bit(R5_LOCKED, &dev->flags);
2873 					set_bit(R5_Wantread, &dev->flags);
2874 					s->locked++;
2875 				} else {
2876 					set_bit(STRIPE_DELAYED, &sh->state);
2877 					set_bit(STRIPE_HANDLE, &sh->state);
2878 				}
2879 			}
2880 		}
2881 	}
2882 	if (rcw <= rmw && rcw > 0) {
2883 		/* want reconstruct write, but need to get some data */
2884 		int qread =0;
2885 		rcw = 0;
2886 		for (i = disks; i--; ) {
2887 			struct r5dev *dev = &sh->dev[i];
2888 			if (!test_bit(R5_OVERWRITE, &dev->flags) &&
2889 			    i != sh->pd_idx && i != sh->qd_idx &&
2890 			    !test_bit(R5_LOCKED, &dev->flags) &&
2891 			    !(test_bit(R5_UPTODATE, &dev->flags) ||
2892 			      test_bit(R5_Wantcompute, &dev->flags))) {
2893 				rcw++;
2894 				if (!test_bit(R5_Insync, &dev->flags))
2895 					continue; /* it's a failed drive */
2896 				if (
2897 				  test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2898 					pr_debug("Read_old block "
2899 						"%d for Reconstruct\n", i);
2900 					set_bit(R5_LOCKED, &dev->flags);
2901 					set_bit(R5_Wantread, &dev->flags);
2902 					s->locked++;
2903 					qread++;
2904 				} else {
2905 					set_bit(STRIPE_DELAYED, &sh->state);
2906 					set_bit(STRIPE_HANDLE, &sh->state);
2907 				}
2908 			}
2909 		}
2910 		if (rcw && conf->mddev->queue)
2911 			blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
2912 					  (unsigned long long)sh->sector,
2913 					  rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
2914 	}
2915 	/* now if nothing is locked, and if we have enough data,
2916 	 * we can start a write request
2917 	 */
2918 	/* since handle_stripe can be called at any time we need to handle the
2919 	 * case where a compute block operation has been submitted and then a
2920 	 * subsequent call wants to start a write request.  raid_run_ops only
2921 	 * handles the case where compute block and reconstruct are requested
2922 	 * simultaneously.  If this is not the case then new writes need to be
2923 	 * held off until the compute completes.
2924 	 */
2925 	if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
2926 	    (s->locked == 0 && (rcw == 0 || rmw == 0) &&
2927 	    !test_bit(STRIPE_BIT_DELAY, &sh->state)))
2928 		schedule_reconstruction(sh, s, rcw == 0, 0);
2929 }
2930 
2931 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
2932 				struct stripe_head_state *s, int disks)
2933 {
2934 	struct r5dev *dev = NULL;
2935 
2936 	set_bit(STRIPE_HANDLE, &sh->state);
2937 
2938 	switch (sh->check_state) {
2939 	case check_state_idle:
2940 		/* start a new check operation if there are no failures */
2941 		if (s->failed == 0) {
2942 			BUG_ON(s->uptodate != disks);
2943 			sh->check_state = check_state_run;
2944 			set_bit(STRIPE_OP_CHECK, &s->ops_request);
2945 			clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
2946 			s->uptodate--;
2947 			break;
2948 		}
2949 		dev = &sh->dev[s->failed_num[0]];
2950 		/* fall through */
2951 	case check_state_compute_result:
2952 		sh->check_state = check_state_idle;
2953 		if (!dev)
2954 			dev = &sh->dev[sh->pd_idx];
2955 
2956 		/* check that a write has not made the stripe insync */
2957 		if (test_bit(STRIPE_INSYNC, &sh->state))
2958 			break;
2959 
2960 		/* either failed parity check, or recovery is happening */
2961 		BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
2962 		BUG_ON(s->uptodate != disks);
2963 
2964 		set_bit(R5_LOCKED, &dev->flags);
2965 		s->locked++;
2966 		set_bit(R5_Wantwrite, &dev->flags);
2967 
2968 		clear_bit(STRIPE_DEGRADED, &sh->state);
2969 		set_bit(STRIPE_INSYNC, &sh->state);
2970 		break;
2971 	case check_state_run:
2972 		break; /* we will be called again upon completion */
2973 	case check_state_check_result:
2974 		sh->check_state = check_state_idle;
2975 
2976 		/* if a failure occurred during the check operation, leave
2977 		 * STRIPE_INSYNC not set and let the stripe be handled again
2978 		 */
2979 		if (s->failed)
2980 			break;
2981 
2982 		/* handle a successful check operation, if parity is correct
2983 		 * we are done.  Otherwise update the mismatch count and repair
2984 		 * parity if !MD_RECOVERY_CHECK
2985 		 */
2986 		if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
2987 			/* parity is correct (on disc,
2988 			 * not in buffer any more)
2989 			 */
2990 			set_bit(STRIPE_INSYNC, &sh->state);
2991 		else {
2992 			atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
2993 			if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
2994 				/* don't try to repair!! */
2995 				set_bit(STRIPE_INSYNC, &sh->state);
2996 			else {
2997 				sh->check_state = check_state_compute_run;
2998 				set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2999 				set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3000 				set_bit(R5_Wantcompute,
3001 					&sh->dev[sh->pd_idx].flags);
3002 				sh->ops.target = sh->pd_idx;
3003 				sh->ops.target2 = -1;
3004 				s->uptodate++;
3005 			}
3006 		}
3007 		break;
3008 	case check_state_compute_run:
3009 		break;
3010 	default:
3011 		printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3012 		       __func__, sh->check_state,
3013 		       (unsigned long long) sh->sector);
3014 		BUG();
3015 	}
3016 }
3017 
3018 
3019 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
3020 				  struct stripe_head_state *s,
3021 				  int disks)
3022 {
3023 	int pd_idx = sh->pd_idx;
3024 	int qd_idx = sh->qd_idx;
3025 	struct r5dev *dev;
3026 
3027 	set_bit(STRIPE_HANDLE, &sh->state);
3028 
3029 	BUG_ON(s->failed > 2);
3030 
3031 	/* Want to check and possibly repair P and Q.
3032 	 * However there could be one 'failed' device, in which
3033 	 * case we can only check one of them, possibly using the
3034 	 * other to generate missing data
3035 	 */
3036 
3037 	switch (sh->check_state) {
3038 	case check_state_idle:
3039 		/* start a new check operation if there are < 2 failures */
3040 		if (s->failed == s->q_failed) {
3041 			/* The only possible failed device holds Q, so it
3042 			 * makes sense to check P (If anything else were failed,
3043 			 * we would have used P to recreate it).
3044 			 */
3045 			sh->check_state = check_state_run;
3046 		}
3047 		if (!s->q_failed && s->failed < 2) {
3048 			/* Q is not failed, and we didn't use it to generate
3049 			 * anything, so it makes sense to check it
3050 			 */
3051 			if (sh->check_state == check_state_run)
3052 				sh->check_state = check_state_run_pq;
3053 			else
3054 				sh->check_state = check_state_run_q;
3055 		}
3056 
3057 		/* discard potentially stale zero_sum_result */
3058 		sh->ops.zero_sum_result = 0;
3059 
3060 		if (sh->check_state == check_state_run) {
3061 			/* async_xor_zero_sum destroys the contents of P */
3062 			clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3063 			s->uptodate--;
3064 		}
3065 		if (sh->check_state >= check_state_run &&
3066 		    sh->check_state <= check_state_run_pq) {
3067 			/* async_syndrome_zero_sum preserves P and Q, so
3068 			 * no need to mark them !uptodate here
3069 			 */
3070 			set_bit(STRIPE_OP_CHECK, &s->ops_request);
3071 			break;
3072 		}
3073 
3074 		/* we have 2-disk failure */
3075 		BUG_ON(s->failed != 2);
3076 		/* fall through */
3077 	case check_state_compute_result:
3078 		sh->check_state = check_state_idle;
3079 
3080 		/* check that a write has not made the stripe insync */
3081 		if (test_bit(STRIPE_INSYNC, &sh->state))
3082 			break;
3083 
3084 		/* now write out any block on a failed drive,
3085 		 * or P or Q if they were recomputed
3086 		 */
3087 		BUG_ON(s->uptodate < disks - 1); /* We don't need Q to recover */
3088 		if (s->failed == 2) {
3089 			dev = &sh->dev[s->failed_num[1]];
3090 			s->locked++;
3091 			set_bit(R5_LOCKED, &dev->flags);
3092 			set_bit(R5_Wantwrite, &dev->flags);
3093 		}
3094 		if (s->failed >= 1) {
3095 			dev = &sh->dev[s->failed_num[0]];
3096 			s->locked++;
3097 			set_bit(R5_LOCKED, &dev->flags);
3098 			set_bit(R5_Wantwrite, &dev->flags);
3099 		}
3100 		if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3101 			dev = &sh->dev[pd_idx];
3102 			s->locked++;
3103 			set_bit(R5_LOCKED, &dev->flags);
3104 			set_bit(R5_Wantwrite, &dev->flags);
3105 		}
3106 		if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3107 			dev = &sh->dev[qd_idx];
3108 			s->locked++;
3109 			set_bit(R5_LOCKED, &dev->flags);
3110 			set_bit(R5_Wantwrite, &dev->flags);
3111 		}
3112 		clear_bit(STRIPE_DEGRADED, &sh->state);
3113 
3114 		set_bit(STRIPE_INSYNC, &sh->state);
3115 		break;
3116 	case check_state_run:
3117 	case check_state_run_q:
3118 	case check_state_run_pq:
3119 		break; /* we will be called again upon completion */
3120 	case check_state_check_result:
3121 		sh->check_state = check_state_idle;
3122 
3123 		/* handle a successful check operation, if parity is correct
3124 		 * we are done.  Otherwise update the mismatch count and repair
3125 		 * parity if !MD_RECOVERY_CHECK
3126 		 */
3127 		if (sh->ops.zero_sum_result == 0) {
3128 			/* both parities are correct */
3129 			if (!s->failed)
3130 				set_bit(STRIPE_INSYNC, &sh->state);
3131 			else {
3132 				/* in contrast to the raid5 case we can validate
3133 				 * parity, but still have a failure to write
3134 				 * back
3135 				 */
3136 				sh->check_state = check_state_compute_result;
3137 				/* Returning at this point means that we may go
3138 				 * off and bring p and/or q uptodate again so
3139 				 * we make sure to check zero_sum_result again
3140 				 * to verify if p or q need writeback
3141 				 */
3142 			}
3143 		} else {
3144 			atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3145 			if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3146 				/* don't try to repair!! */
3147 				set_bit(STRIPE_INSYNC, &sh->state);
3148 			else {
3149 				int *target = &sh->ops.target;
3150 
3151 				sh->ops.target = -1;
3152 				sh->ops.target2 = -1;
3153 				sh->check_state = check_state_compute_run;
3154 				set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3155 				set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3156 				if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3157 					set_bit(R5_Wantcompute,
3158 						&sh->dev[pd_idx].flags);
3159 					*target = pd_idx;
3160 					target = &sh->ops.target2;
3161 					s->uptodate++;
3162 				}
3163 				if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3164 					set_bit(R5_Wantcompute,
3165 						&sh->dev[qd_idx].flags);
3166 					*target = qd_idx;
3167 					s->uptodate++;
3168 				}
3169 			}
3170 		}
3171 		break;
3172 	case check_state_compute_run:
3173 		break;
3174 	default:
3175 		printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3176 		       __func__, sh->check_state,
3177 		       (unsigned long long) sh->sector);
3178 		BUG();
3179 	}
3180 }
3181 
3182 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
3183 {
3184 	int i;
3185 
3186 	/* We have read all the blocks in this stripe and now we need to
3187 	 * copy some of them into a target stripe for expand.
3188 	 */
3189 	struct dma_async_tx_descriptor *tx = NULL;
3190 	clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3191 	for (i = 0; i < sh->disks; i++)
3192 		if (i != sh->pd_idx && i != sh->qd_idx) {
3193 			int dd_idx, j;
3194 			struct stripe_head *sh2;
3195 			struct async_submit_ctl submit;
3196 
3197 			sector_t bn = compute_blocknr(sh, i, 1);
3198 			sector_t s = raid5_compute_sector(conf, bn, 0,
3199 							  &dd_idx, NULL);
3200 			sh2 = get_active_stripe(conf, s, 0, 1, 1);
3201 			if (sh2 == NULL)
3202 				/* so far only the early blocks of this stripe
3203 				 * have been requested.  When later blocks
3204 				 * get requested, we will try again
3205 				 */
3206 				continue;
3207 			if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
3208 			   test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
3209 				/* must have already done this block */
3210 				release_stripe(sh2);
3211 				continue;
3212 			}
3213 
3214 			/* place all the copies on one channel */
3215 			init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
3216 			tx = async_memcpy(sh2->dev[dd_idx].page,
3217 					  sh->dev[i].page, 0, 0, STRIPE_SIZE,
3218 					  &submit);
3219 
3220 			set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
3221 			set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
3222 			for (j = 0; j < conf->raid_disks; j++)
3223 				if (j != sh2->pd_idx &&
3224 				    j != sh2->qd_idx &&
3225 				    !test_bit(R5_Expanded, &sh2->dev[j].flags))
3226 					break;
3227 			if (j == conf->raid_disks) {
3228 				set_bit(STRIPE_EXPAND_READY, &sh2->state);
3229 				set_bit(STRIPE_HANDLE, &sh2->state);
3230 			}
3231 			release_stripe(sh2);
3232 
3233 		}
3234 	/* done submitting copies, wait for them to complete */
3235 	async_tx_quiesce(&tx);
3236 }
3237 
3238 /*
3239  * handle_stripe - do things to a stripe.
3240  *
3241  * We lock the stripe by setting STRIPE_ACTIVE and then examine the
3242  * state of various bits to see what needs to be done.
3243  * Possible results:
3244  *    return some read requests which now have data
3245  *    return some write requests which are safely on storage
3246  *    schedule a read on some buffers
3247  *    schedule a write of some buffers
3248  *    return confirmation of parity correctness
3249  *
3250  */
3251 
3252 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
3253 {
3254 	struct r5conf *conf = sh->raid_conf;
3255 	int disks = sh->disks;
3256 	struct r5dev *dev;
3257 	int i;
3258 	int do_recovery = 0;
3259 
3260 	memset(s, 0, sizeof(*s));
3261 
3262 	s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3263 	s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
3264 	s->failed_num[0] = -1;
3265 	s->failed_num[1] = -1;
3266 
3267 	/* Now to look around and see what can be done */
3268 	rcu_read_lock();
3269 	for (i=disks; i--; ) {
3270 		struct md_rdev *rdev;
3271 		sector_t first_bad;
3272 		int bad_sectors;
3273 		int is_bad = 0;
3274 
3275 		dev = &sh->dev[i];
3276 
3277 		pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
3278 			 i, dev->flags,
3279 			 dev->toread, dev->towrite, dev->written);
3280 		/* maybe we can reply to a read
3281 		 *
3282 		 * new wantfill requests are only permitted while
3283 		 * ops_complete_biofill is guaranteed to be inactive
3284 		 */
3285 		if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
3286 		    !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
3287 			set_bit(R5_Wantfill, &dev->flags);
3288 
3289 		/* now count some things */
3290 		if (test_bit(R5_LOCKED, &dev->flags))
3291 			s->locked++;
3292 		if (test_bit(R5_UPTODATE, &dev->flags))
3293 			s->uptodate++;
3294 		if (test_bit(R5_Wantcompute, &dev->flags)) {
3295 			s->compute++;
3296 			BUG_ON(s->compute > 2);
3297 		}
3298 
3299 		if (test_bit(R5_Wantfill, &dev->flags))
3300 			s->to_fill++;
3301 		else if (dev->toread)
3302 			s->to_read++;
3303 		if (dev->towrite) {
3304 			s->to_write++;
3305 			if (!test_bit(R5_OVERWRITE, &dev->flags))
3306 				s->non_overwrite++;
3307 		}
3308 		if (dev->written)
3309 			s->written++;
3310 		/* Prefer to use the replacement for reads, but only
3311 		 * if it is recovered enough and has no bad blocks.
3312 		 */
3313 		rdev = rcu_dereference(conf->disks[i].replacement);
3314 		if (rdev && !test_bit(Faulty, &rdev->flags) &&
3315 		    rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
3316 		    !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
3317 				 &first_bad, &bad_sectors))
3318 			set_bit(R5_ReadRepl, &dev->flags);
3319 		else {
3320 			if (rdev)
3321 				set_bit(R5_NeedReplace, &dev->flags);
3322 			rdev = rcu_dereference(conf->disks[i].rdev);
3323 			clear_bit(R5_ReadRepl, &dev->flags);
3324 		}
3325 		if (rdev && test_bit(Faulty, &rdev->flags))
3326 			rdev = NULL;
3327 		if (rdev) {
3328 			is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
3329 					     &first_bad, &bad_sectors);
3330 			if (s->blocked_rdev == NULL
3331 			    && (test_bit(Blocked, &rdev->flags)
3332 				|| is_bad < 0)) {
3333 				if (is_bad < 0)
3334 					set_bit(BlockedBadBlocks,
3335 						&rdev->flags);
3336 				s->blocked_rdev = rdev;
3337 				atomic_inc(&rdev->nr_pending);
3338 			}
3339 		}
3340 		clear_bit(R5_Insync, &dev->flags);
3341 		if (!rdev)
3342 			/* Not in-sync */;
3343 		else if (is_bad) {
3344 			/* also not in-sync */
3345 			if (!test_bit(WriteErrorSeen, &rdev->flags) &&
3346 			    test_bit(R5_UPTODATE, &dev->flags)) {
3347 				/* treat as in-sync, but with a read error
3348 				 * which we can now try to correct
3349 				 */
3350 				set_bit(R5_Insync, &dev->flags);
3351 				set_bit(R5_ReadError, &dev->flags);
3352 			}
3353 		} else if (test_bit(In_sync, &rdev->flags))
3354 			set_bit(R5_Insync, &dev->flags);
3355 		else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
3356 			/* in sync if before recovery_offset */
3357 			set_bit(R5_Insync, &dev->flags);
3358 		else if (test_bit(R5_UPTODATE, &dev->flags) &&
3359 			 test_bit(R5_Expanded, &dev->flags))
3360 			/* If we've reshaped into here, we assume it is Insync.
3361 			 * We will shortly update recovery_offset to make
3362 			 * it official.
3363 			 */
3364 			set_bit(R5_Insync, &dev->flags);
3365 
3366 		if (rdev && test_bit(R5_WriteError, &dev->flags)) {
3367 			/* This flag does not apply to '.replacement'
3368 			 * only to .rdev, so make sure to check that*/
3369 			struct md_rdev *rdev2 = rcu_dereference(
3370 				conf->disks[i].rdev);
3371 			if (rdev2 == rdev)
3372 				clear_bit(R5_Insync, &dev->flags);
3373 			if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3374 				s->handle_bad_blocks = 1;
3375 				atomic_inc(&rdev2->nr_pending);
3376 			} else
3377 				clear_bit(R5_WriteError, &dev->flags);
3378 		}
3379 		if (rdev && test_bit(R5_MadeGood, &dev->flags)) {
3380 			/* This flag does not apply to '.replacement'
3381 			 * only to .rdev, so make sure to check that*/
3382 			struct md_rdev *rdev2 = rcu_dereference(
3383 				conf->disks[i].rdev);
3384 			if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3385 				s->handle_bad_blocks = 1;
3386 				atomic_inc(&rdev2->nr_pending);
3387 			} else
3388 				clear_bit(R5_MadeGood, &dev->flags);
3389 		}
3390 		if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
3391 			struct md_rdev *rdev2 = rcu_dereference(
3392 				conf->disks[i].replacement);
3393 			if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3394 				s->handle_bad_blocks = 1;
3395 				atomic_inc(&rdev2->nr_pending);
3396 			} else
3397 				clear_bit(R5_MadeGoodRepl, &dev->flags);
3398 		}
3399 		if (!test_bit(R5_Insync, &dev->flags)) {
3400 			/* The ReadError flag will just be confusing now */
3401 			clear_bit(R5_ReadError, &dev->flags);
3402 			clear_bit(R5_ReWrite, &dev->flags);
3403 		}
3404 		if (test_bit(R5_ReadError, &dev->flags))
3405 			clear_bit(R5_Insync, &dev->flags);
3406 		if (!test_bit(R5_Insync, &dev->flags)) {
3407 			if (s->failed < 2)
3408 				s->failed_num[s->failed] = i;
3409 			s->failed++;
3410 			if (rdev && !test_bit(Faulty, &rdev->flags))
3411 				do_recovery = 1;
3412 		}
3413 	}
3414 	if (test_bit(STRIPE_SYNCING, &sh->state)) {
3415 		/* If there is a failed device being replaced,
3416 		 *     we must be recovering.
3417 		 * else if we are after recovery_cp, we must be syncing
3418 		 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
3419 		 * else we can only be replacing
3420 		 * sync and recovery both need to read all devices, and so
3421 		 * use the same flag.
3422 		 */
3423 		if (do_recovery ||
3424 		    sh->sector >= conf->mddev->recovery_cp ||
3425 		    test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
3426 			s->syncing = 1;
3427 		else
3428 			s->replacing = 1;
3429 	}
3430 	rcu_read_unlock();
3431 }
3432 
3433 static void handle_stripe(struct stripe_head *sh)
3434 {
3435 	struct stripe_head_state s;
3436 	struct r5conf *conf = sh->raid_conf;
3437 	int i;
3438 	int prexor;
3439 	int disks = sh->disks;
3440 	struct r5dev *pdev, *qdev;
3441 
3442 	clear_bit(STRIPE_HANDLE, &sh->state);
3443 	if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
3444 		/* already being handled, ensure it gets handled
3445 		 * again when current action finishes */
3446 		set_bit(STRIPE_HANDLE, &sh->state);
3447 		return;
3448 	}
3449 
3450 	if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
3451 		spin_lock(&sh->stripe_lock);
3452 		/* Cannot process 'sync' concurrently with 'discard' */
3453 		if (!test_bit(STRIPE_DISCARD, &sh->state) &&
3454 		    test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
3455 			set_bit(STRIPE_SYNCING, &sh->state);
3456 			clear_bit(STRIPE_INSYNC, &sh->state);
3457 		}
3458 		spin_unlock(&sh->stripe_lock);
3459 	}
3460 	clear_bit(STRIPE_DELAYED, &sh->state);
3461 
3462 	pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
3463 		"pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
3464 	       (unsigned long long)sh->sector, sh->state,
3465 	       atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
3466 	       sh->check_state, sh->reconstruct_state);
3467 
3468 	analyse_stripe(sh, &s);
3469 
3470 	if (s.handle_bad_blocks) {
3471 		set_bit(STRIPE_HANDLE, &sh->state);
3472 		goto finish;
3473 	}
3474 
3475 	if (unlikely(s.blocked_rdev)) {
3476 		if (s.syncing || s.expanding || s.expanded ||
3477 		    s.replacing || s.to_write || s.written) {
3478 			set_bit(STRIPE_HANDLE, &sh->state);
3479 			goto finish;
3480 		}
3481 		/* There is nothing for the blocked_rdev to block */
3482 		rdev_dec_pending(s.blocked_rdev, conf->mddev);
3483 		s.blocked_rdev = NULL;
3484 	}
3485 
3486 	if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
3487 		set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
3488 		set_bit(STRIPE_BIOFILL_RUN, &sh->state);
3489 	}
3490 
3491 	pr_debug("locked=%d uptodate=%d to_read=%d"
3492 	       " to_write=%d failed=%d failed_num=%d,%d\n",
3493 	       s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
3494 	       s.failed_num[0], s.failed_num[1]);
3495 	/* check if the array has lost more than max_degraded devices and,
3496 	 * if so, some requests might need to be failed.
3497 	 */
3498 	if (s.failed > conf->max_degraded) {
3499 		sh->check_state = 0;
3500 		sh->reconstruct_state = 0;
3501 		if (s.to_read+s.to_write+s.written)
3502 			handle_failed_stripe(conf, sh, &s, disks, &s.return_bi);
3503 		if (s.syncing + s.replacing)
3504 			handle_failed_sync(conf, sh, &s);
3505 	}
3506 
3507 	/* Now we check to see if any write operations have recently
3508 	 * completed
3509 	 */
3510 	prexor = 0;
3511 	if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
3512 		prexor = 1;
3513 	if (sh->reconstruct_state == reconstruct_state_drain_result ||
3514 	    sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
3515 		sh->reconstruct_state = reconstruct_state_idle;
3516 
3517 		/* All the 'written' buffers and the parity block are ready to
3518 		 * be written back to disk
3519 		 */
3520 		BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
3521 		       !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
3522 		BUG_ON(sh->qd_idx >= 0 &&
3523 		       !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
3524 		       !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
3525 		for (i = disks; i--; ) {
3526 			struct r5dev *dev = &sh->dev[i];
3527 			if (test_bit(R5_LOCKED, &dev->flags) &&
3528 				(i == sh->pd_idx || i == sh->qd_idx ||
3529 				 dev->written)) {
3530 				pr_debug("Writing block %d\n", i);
3531 				set_bit(R5_Wantwrite, &dev->flags);
3532 				if (prexor)
3533 					continue;
3534 				if (!test_bit(R5_Insync, &dev->flags) ||
3535 				    ((i == sh->pd_idx || i == sh->qd_idx)  &&
3536 				     s.failed == 0))
3537 					set_bit(STRIPE_INSYNC, &sh->state);
3538 			}
3539 		}
3540 		if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3541 			s.dec_preread_active = 1;
3542 	}
3543 
3544 	/*
3545 	 * might be able to return some write requests if the parity blocks
3546 	 * are safe, or on a failed drive
3547 	 */
3548 	pdev = &sh->dev[sh->pd_idx];
3549 	s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
3550 		|| (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
3551 	qdev = &sh->dev[sh->qd_idx];
3552 	s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
3553 		|| (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
3554 		|| conf->level < 6;
3555 
3556 	if (s.written &&
3557 	    (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
3558 			     && !test_bit(R5_LOCKED, &pdev->flags)
3559 			     && (test_bit(R5_UPTODATE, &pdev->flags) ||
3560 				 test_bit(R5_Discard, &pdev->flags))))) &&
3561 	    (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
3562 			     && !test_bit(R5_LOCKED, &qdev->flags)
3563 			     && (test_bit(R5_UPTODATE, &qdev->flags) ||
3564 				 test_bit(R5_Discard, &qdev->flags))))))
3565 		handle_stripe_clean_event(conf, sh, disks, &s.return_bi);
3566 
3567 	/* Now we might consider reading some blocks, either to check/generate
3568 	 * parity, or to satisfy requests
3569 	 * or to load a block that is being partially written.
3570 	 */
3571 	if (s.to_read || s.non_overwrite
3572 	    || (conf->level == 6 && s.to_write && s.failed)
3573 	    || (s.syncing && (s.uptodate + s.compute < disks))
3574 	    || s.replacing
3575 	    || s.expanding)
3576 		handle_stripe_fill(sh, &s, disks);
3577 
3578 	/* Now to consider new write requests and what else, if anything
3579 	 * should be read.  We do not handle new writes when:
3580 	 * 1/ A 'write' operation (copy+xor) is already in flight.
3581 	 * 2/ A 'check' operation is in flight, as it may clobber the parity
3582 	 *    block.
3583 	 */
3584 	if (s.to_write && !sh->reconstruct_state && !sh->check_state)
3585 		handle_stripe_dirtying(conf, sh, &s, disks);
3586 
3587 	/* maybe we need to check and possibly fix the parity for this stripe
3588 	 * Any reads will already have been scheduled, so we just see if enough
3589 	 * data is available.  The parity check is held off while parity
3590 	 * dependent operations are in flight.
3591 	 */
3592 	if (sh->check_state ||
3593 	    (s.syncing && s.locked == 0 &&
3594 	     !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
3595 	     !test_bit(STRIPE_INSYNC, &sh->state))) {
3596 		if (conf->level == 6)
3597 			handle_parity_checks6(conf, sh, &s, disks);
3598 		else
3599 			handle_parity_checks5(conf, sh, &s, disks);
3600 	}
3601 
3602 	if (s.replacing && s.locked == 0
3603 	    && !test_bit(STRIPE_INSYNC, &sh->state)) {
3604 		/* Write out to replacement devices where possible */
3605 		for (i = 0; i < conf->raid_disks; i++)
3606 			if (test_bit(R5_UPTODATE, &sh->dev[i].flags) &&
3607 			    test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
3608 				set_bit(R5_WantReplace, &sh->dev[i].flags);
3609 				set_bit(R5_LOCKED, &sh->dev[i].flags);
3610 				s.locked++;
3611 			}
3612 		set_bit(STRIPE_INSYNC, &sh->state);
3613 	}
3614 	if ((s.syncing || s.replacing) && s.locked == 0 &&
3615 	    test_bit(STRIPE_INSYNC, &sh->state)) {
3616 		md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3617 		clear_bit(STRIPE_SYNCING, &sh->state);
3618 		if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3619 			wake_up(&conf->wait_for_overlap);
3620 	}
3621 
3622 	/* If the failed drives are just a ReadError, then we might need
3623 	 * to progress the repair/check process
3624 	 */
3625 	if (s.failed <= conf->max_degraded && !conf->mddev->ro)
3626 		for (i = 0; i < s.failed; i++) {
3627 			struct r5dev *dev = &sh->dev[s.failed_num[i]];
3628 			if (test_bit(R5_ReadError, &dev->flags)
3629 			    && !test_bit(R5_LOCKED, &dev->flags)
3630 			    && test_bit(R5_UPTODATE, &dev->flags)
3631 				) {
3632 				if (!test_bit(R5_ReWrite, &dev->flags)) {
3633 					set_bit(R5_Wantwrite, &dev->flags);
3634 					set_bit(R5_ReWrite, &dev->flags);
3635 					set_bit(R5_LOCKED, &dev->flags);
3636 					s.locked++;
3637 				} else {
3638 					/* let's read it back */
3639 					set_bit(R5_Wantread, &dev->flags);
3640 					set_bit(R5_LOCKED, &dev->flags);
3641 					s.locked++;
3642 				}
3643 			}
3644 		}
3645 
3646 
3647 	/* Finish reconstruct operations initiated by the expansion process */
3648 	if (sh->reconstruct_state == reconstruct_state_result) {
3649 		struct stripe_head *sh_src
3650 			= get_active_stripe(conf, sh->sector, 1, 1, 1);
3651 		if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
3652 			/* sh cannot be written until sh_src has been read.
3653 			 * so arrange for sh to be delayed a little
3654 			 */
3655 			set_bit(STRIPE_DELAYED, &sh->state);
3656 			set_bit(STRIPE_HANDLE, &sh->state);
3657 			if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
3658 					      &sh_src->state))
3659 				atomic_inc(&conf->preread_active_stripes);
3660 			release_stripe(sh_src);
3661 			goto finish;
3662 		}
3663 		if (sh_src)
3664 			release_stripe(sh_src);
3665 
3666 		sh->reconstruct_state = reconstruct_state_idle;
3667 		clear_bit(STRIPE_EXPANDING, &sh->state);
3668 		for (i = conf->raid_disks; i--; ) {
3669 			set_bit(R5_Wantwrite, &sh->dev[i].flags);
3670 			set_bit(R5_LOCKED, &sh->dev[i].flags);
3671 			s.locked++;
3672 		}
3673 	}
3674 
3675 	if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
3676 	    !sh->reconstruct_state) {
3677 		/* Need to write out all blocks after computing parity */
3678 		sh->disks = conf->raid_disks;
3679 		stripe_set_idx(sh->sector, conf, 0, sh);
3680 		schedule_reconstruction(sh, &s, 1, 1);
3681 	} else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
3682 		clear_bit(STRIPE_EXPAND_READY, &sh->state);
3683 		atomic_dec(&conf->reshape_stripes);
3684 		wake_up(&conf->wait_for_overlap);
3685 		md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3686 	}
3687 
3688 	if (s.expanding && s.locked == 0 &&
3689 	    !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
3690 		handle_stripe_expansion(conf, sh);
3691 
3692 finish:
3693 	/* wait for this device to become unblocked */
3694 	if (unlikely(s.blocked_rdev)) {
3695 		if (conf->mddev->external)
3696 			md_wait_for_blocked_rdev(s.blocked_rdev,
3697 						 conf->mddev);
3698 		else
3699 			/* Internal metadata will immediately
3700 			 * be written by raid5d, so we don't
3701 			 * need to wait here.
3702 			 */
3703 			rdev_dec_pending(s.blocked_rdev,
3704 					 conf->mddev);
3705 	}
3706 
3707 	if (s.handle_bad_blocks)
3708 		for (i = disks; i--; ) {
3709 			struct md_rdev *rdev;
3710 			struct r5dev *dev = &sh->dev[i];
3711 			if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
3712 				/* We own a safe reference to the rdev */
3713 				rdev = conf->disks[i].rdev;
3714 				if (!rdev_set_badblocks(rdev, sh->sector,
3715 							STRIPE_SECTORS, 0))
3716 					md_error(conf->mddev, rdev);
3717 				rdev_dec_pending(rdev, conf->mddev);
3718 			}
3719 			if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
3720 				rdev = conf->disks[i].rdev;
3721 				rdev_clear_badblocks(rdev, sh->sector,
3722 						     STRIPE_SECTORS, 0);
3723 				rdev_dec_pending(rdev, conf->mddev);
3724 			}
3725 			if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
3726 				rdev = conf->disks[i].replacement;
3727 				if (!rdev)
3728 					/* rdev have been moved down */
3729 					rdev = conf->disks[i].rdev;
3730 				rdev_clear_badblocks(rdev, sh->sector,
3731 						     STRIPE_SECTORS, 0);
3732 				rdev_dec_pending(rdev, conf->mddev);
3733 			}
3734 		}
3735 
3736 	if (s.ops_request)
3737 		raid_run_ops(sh, s.ops_request);
3738 
3739 	ops_run_io(sh, &s);
3740 
3741 	if (s.dec_preread_active) {
3742 		/* We delay this until after ops_run_io so that if make_request
3743 		 * is waiting on a flush, it won't continue until the writes
3744 		 * have actually been submitted.
3745 		 */
3746 		atomic_dec(&conf->preread_active_stripes);
3747 		if (atomic_read(&conf->preread_active_stripes) <
3748 		    IO_THRESHOLD)
3749 			md_wakeup_thread(conf->mddev->thread);
3750 	}
3751 
3752 	return_io(s.return_bi);
3753 
3754 	clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
3755 }
3756 
3757 static void raid5_activate_delayed(struct r5conf *conf)
3758 {
3759 	if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
3760 		while (!list_empty(&conf->delayed_list)) {
3761 			struct list_head *l = conf->delayed_list.next;
3762 			struct stripe_head *sh;
3763 			sh = list_entry(l, struct stripe_head, lru);
3764 			list_del_init(l);
3765 			clear_bit(STRIPE_DELAYED, &sh->state);
3766 			if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3767 				atomic_inc(&conf->preread_active_stripes);
3768 			list_add_tail(&sh->lru, &conf->hold_list);
3769 		}
3770 	}
3771 }
3772 
3773 static void activate_bit_delay(struct r5conf *conf)
3774 {
3775 	/* device_lock is held */
3776 	struct list_head head;
3777 	list_add(&head, &conf->bitmap_list);
3778 	list_del_init(&conf->bitmap_list);
3779 	while (!list_empty(&head)) {
3780 		struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
3781 		list_del_init(&sh->lru);
3782 		atomic_inc(&sh->count);
3783 		__release_stripe(conf, sh);
3784 	}
3785 }
3786 
3787 int md_raid5_congested(struct mddev *mddev, int bits)
3788 {
3789 	struct r5conf *conf = mddev->private;
3790 
3791 	/* No difference between reads and writes.  Just check
3792 	 * how busy the stripe_cache is
3793 	 */
3794 
3795 	if (conf->inactive_blocked)
3796 		return 1;
3797 	if (conf->quiesce)
3798 		return 1;
3799 	if (list_empty_careful(&conf->inactive_list))
3800 		return 1;
3801 
3802 	return 0;
3803 }
3804 EXPORT_SYMBOL_GPL(md_raid5_congested);
3805 
3806 static int raid5_congested(void *data, int bits)
3807 {
3808 	struct mddev *mddev = data;
3809 
3810 	return mddev_congested(mddev, bits) ||
3811 		md_raid5_congested(mddev, bits);
3812 }
3813 
3814 /* We want read requests to align with chunks where possible,
3815  * but write requests don't need to.
3816  */
3817 static int raid5_mergeable_bvec(struct request_queue *q,
3818 				struct bvec_merge_data *bvm,
3819 				struct bio_vec *biovec)
3820 {
3821 	struct mddev *mddev = q->queuedata;
3822 	sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
3823 	int max;
3824 	unsigned int chunk_sectors = mddev->chunk_sectors;
3825 	unsigned int bio_sectors = bvm->bi_size >> 9;
3826 
3827 	if ((bvm->bi_rw & 1) == WRITE)
3828 		return biovec->bv_len; /* always allow writes to be mergeable */
3829 
3830 	if (mddev->new_chunk_sectors < mddev->chunk_sectors)
3831 		chunk_sectors = mddev->new_chunk_sectors;
3832 	max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
3833 	if (max < 0) max = 0;
3834 	if (max <= biovec->bv_len && bio_sectors == 0)
3835 		return biovec->bv_len;
3836 	else
3837 		return max;
3838 }
3839 
3840 
3841 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
3842 {
3843 	sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
3844 	unsigned int chunk_sectors = mddev->chunk_sectors;
3845 	unsigned int bio_sectors = bio->bi_size >> 9;
3846 
3847 	if (mddev->new_chunk_sectors < mddev->chunk_sectors)
3848 		chunk_sectors = mddev->new_chunk_sectors;
3849 	return  chunk_sectors >=
3850 		((sector & (chunk_sectors - 1)) + bio_sectors);
3851 }
3852 
3853 /*
3854  *  add bio to the retry LIFO  ( in O(1) ... we are in interrupt )
3855  *  later sampled by raid5d.
3856  */
3857 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
3858 {
3859 	unsigned long flags;
3860 
3861 	spin_lock_irqsave(&conf->device_lock, flags);
3862 
3863 	bi->bi_next = conf->retry_read_aligned_list;
3864 	conf->retry_read_aligned_list = bi;
3865 
3866 	spin_unlock_irqrestore(&conf->device_lock, flags);
3867 	md_wakeup_thread(conf->mddev->thread);
3868 }
3869 
3870 
3871 static struct bio *remove_bio_from_retry(struct r5conf *conf)
3872 {
3873 	struct bio *bi;
3874 
3875 	bi = conf->retry_read_aligned;
3876 	if (bi) {
3877 		conf->retry_read_aligned = NULL;
3878 		return bi;
3879 	}
3880 	bi = conf->retry_read_aligned_list;
3881 	if(bi) {
3882 		conf->retry_read_aligned_list = bi->bi_next;
3883 		bi->bi_next = NULL;
3884 		/*
3885 		 * this sets the active strip count to 1 and the processed
3886 		 * strip count to zero (upper 8 bits)
3887 		 */
3888 		raid5_set_bi_stripes(bi, 1); /* biased count of active stripes */
3889 	}
3890 
3891 	return bi;
3892 }
3893 
3894 
3895 /*
3896  *  The "raid5_align_endio" should check if the read succeeded and if it
3897  *  did, call bio_endio on the original bio (having bio_put the new bio
3898  *  first).
3899  *  If the read failed..
3900  */
3901 static void raid5_align_endio(struct bio *bi, int error)
3902 {
3903 	struct bio* raid_bi  = bi->bi_private;
3904 	struct mddev *mddev;
3905 	struct r5conf *conf;
3906 	int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
3907 	struct md_rdev *rdev;
3908 
3909 	bio_put(bi);
3910 
3911 	rdev = (void*)raid_bi->bi_next;
3912 	raid_bi->bi_next = NULL;
3913 	mddev = rdev->mddev;
3914 	conf = mddev->private;
3915 
3916 	rdev_dec_pending(rdev, conf->mddev);
3917 
3918 	if (!error && uptodate) {
3919 		trace_block_bio_complete(bdev_get_queue(raid_bi->bi_bdev),
3920 					 raid_bi, 0);
3921 		bio_endio(raid_bi, 0);
3922 		if (atomic_dec_and_test(&conf->active_aligned_reads))
3923 			wake_up(&conf->wait_for_stripe);
3924 		return;
3925 	}
3926 
3927 
3928 	pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
3929 
3930 	add_bio_to_retry(raid_bi, conf);
3931 }
3932 
3933 static int bio_fits_rdev(struct bio *bi)
3934 {
3935 	struct request_queue *q = bdev_get_queue(bi->bi_bdev);
3936 
3937 	if ((bi->bi_size>>9) > queue_max_sectors(q))
3938 		return 0;
3939 	blk_recount_segments(q, bi);
3940 	if (bi->bi_phys_segments > queue_max_segments(q))
3941 		return 0;
3942 
3943 	if (q->merge_bvec_fn)
3944 		/* it's too hard to apply the merge_bvec_fn at this stage,
3945 		 * just just give up
3946 		 */
3947 		return 0;
3948 
3949 	return 1;
3950 }
3951 
3952 
3953 static int chunk_aligned_read(struct mddev *mddev, struct bio * raid_bio)
3954 {
3955 	struct r5conf *conf = mddev->private;
3956 	int dd_idx;
3957 	struct bio* align_bi;
3958 	struct md_rdev *rdev;
3959 	sector_t end_sector;
3960 
3961 	if (!in_chunk_boundary(mddev, raid_bio)) {
3962 		pr_debug("chunk_aligned_read : non aligned\n");
3963 		return 0;
3964 	}
3965 	/*
3966 	 * use bio_clone_mddev to make a copy of the bio
3967 	 */
3968 	align_bi = bio_clone_mddev(raid_bio, GFP_NOIO, mddev);
3969 	if (!align_bi)
3970 		return 0;
3971 	/*
3972 	 *   set bi_end_io to a new function, and set bi_private to the
3973 	 *     original bio.
3974 	 */
3975 	align_bi->bi_end_io  = raid5_align_endio;
3976 	align_bi->bi_private = raid_bio;
3977 	/*
3978 	 *	compute position
3979 	 */
3980 	align_bi->bi_sector =  raid5_compute_sector(conf, raid_bio->bi_sector,
3981 						    0,
3982 						    &dd_idx, NULL);
3983 
3984 	end_sector = align_bi->bi_sector + (align_bi->bi_size >> 9);
3985 	rcu_read_lock();
3986 	rdev = rcu_dereference(conf->disks[dd_idx].replacement);
3987 	if (!rdev || test_bit(Faulty, &rdev->flags) ||
3988 	    rdev->recovery_offset < end_sector) {
3989 		rdev = rcu_dereference(conf->disks[dd_idx].rdev);
3990 		if (rdev &&
3991 		    (test_bit(Faulty, &rdev->flags) ||
3992 		    !(test_bit(In_sync, &rdev->flags) ||
3993 		      rdev->recovery_offset >= end_sector)))
3994 			rdev = NULL;
3995 	}
3996 	if (rdev) {
3997 		sector_t first_bad;
3998 		int bad_sectors;
3999 
4000 		atomic_inc(&rdev->nr_pending);
4001 		rcu_read_unlock();
4002 		raid_bio->bi_next = (void*)rdev;
4003 		align_bi->bi_bdev =  rdev->bdev;
4004 		align_bi->bi_flags &= ~(1 << BIO_SEG_VALID);
4005 
4006 		if (!bio_fits_rdev(align_bi) ||
4007 		    is_badblock(rdev, align_bi->bi_sector, align_bi->bi_size>>9,
4008 				&first_bad, &bad_sectors)) {
4009 			/* too big in some way, or has a known bad block */
4010 			bio_put(align_bi);
4011 			rdev_dec_pending(rdev, mddev);
4012 			return 0;
4013 		}
4014 
4015 		/* No reshape active, so we can trust rdev->data_offset */
4016 		align_bi->bi_sector += rdev->data_offset;
4017 
4018 		spin_lock_irq(&conf->device_lock);
4019 		wait_event_lock_irq(conf->wait_for_stripe,
4020 				    conf->quiesce == 0,
4021 				    conf->device_lock);
4022 		atomic_inc(&conf->active_aligned_reads);
4023 		spin_unlock_irq(&conf->device_lock);
4024 
4025 		if (mddev->gendisk)
4026 			trace_block_bio_remap(bdev_get_queue(align_bi->bi_bdev),
4027 					      align_bi, disk_devt(mddev->gendisk),
4028 					      raid_bio->bi_sector);
4029 		generic_make_request(align_bi);
4030 		return 1;
4031 	} else {
4032 		rcu_read_unlock();
4033 		bio_put(align_bi);
4034 		return 0;
4035 	}
4036 }
4037 
4038 /* __get_priority_stripe - get the next stripe to process
4039  *
4040  * Full stripe writes are allowed to pass preread active stripes up until
4041  * the bypass_threshold is exceeded.  In general the bypass_count
4042  * increments when the handle_list is handled before the hold_list; however, it
4043  * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
4044  * stripe with in flight i/o.  The bypass_count will be reset when the
4045  * head of the hold_list has changed, i.e. the head was promoted to the
4046  * handle_list.
4047  */
4048 static struct stripe_head *__get_priority_stripe(struct r5conf *conf)
4049 {
4050 	struct stripe_head *sh;
4051 
4052 	pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
4053 		  __func__,
4054 		  list_empty(&conf->handle_list) ? "empty" : "busy",
4055 		  list_empty(&conf->hold_list) ? "empty" : "busy",
4056 		  atomic_read(&conf->pending_full_writes), conf->bypass_count);
4057 
4058 	if (!list_empty(&conf->handle_list)) {
4059 		sh = list_entry(conf->handle_list.next, typeof(*sh), lru);
4060 
4061 		if (list_empty(&conf->hold_list))
4062 			conf->bypass_count = 0;
4063 		else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
4064 			if (conf->hold_list.next == conf->last_hold)
4065 				conf->bypass_count++;
4066 			else {
4067 				conf->last_hold = conf->hold_list.next;
4068 				conf->bypass_count -= conf->bypass_threshold;
4069 				if (conf->bypass_count < 0)
4070 					conf->bypass_count = 0;
4071 			}
4072 		}
4073 	} else if (!list_empty(&conf->hold_list) &&
4074 		   ((conf->bypass_threshold &&
4075 		     conf->bypass_count > conf->bypass_threshold) ||
4076 		    atomic_read(&conf->pending_full_writes) == 0)) {
4077 		sh = list_entry(conf->hold_list.next,
4078 				typeof(*sh), lru);
4079 		conf->bypass_count -= conf->bypass_threshold;
4080 		if (conf->bypass_count < 0)
4081 			conf->bypass_count = 0;
4082 	} else
4083 		return NULL;
4084 
4085 	list_del_init(&sh->lru);
4086 	atomic_inc(&sh->count);
4087 	BUG_ON(atomic_read(&sh->count) != 1);
4088 	return sh;
4089 }
4090 
4091 struct raid5_plug_cb {
4092 	struct blk_plug_cb	cb;
4093 	struct list_head	list;
4094 };
4095 
4096 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
4097 {
4098 	struct raid5_plug_cb *cb = container_of(
4099 		blk_cb, struct raid5_plug_cb, cb);
4100 	struct stripe_head *sh;
4101 	struct mddev *mddev = cb->cb.data;
4102 	struct r5conf *conf = mddev->private;
4103 	int cnt = 0;
4104 
4105 	if (cb->list.next && !list_empty(&cb->list)) {
4106 		spin_lock_irq(&conf->device_lock);
4107 		while (!list_empty(&cb->list)) {
4108 			sh = list_first_entry(&cb->list, struct stripe_head, lru);
4109 			list_del_init(&sh->lru);
4110 			/*
4111 			 * avoid race release_stripe_plug() sees
4112 			 * STRIPE_ON_UNPLUG_LIST clear but the stripe
4113 			 * is still in our list
4114 			 */
4115 			smp_mb__before_clear_bit();
4116 			clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
4117 			__release_stripe(conf, sh);
4118 			cnt++;
4119 		}
4120 		spin_unlock_irq(&conf->device_lock);
4121 	}
4122 	if (mddev->queue)
4123 		trace_block_unplug(mddev->queue, cnt, !from_schedule);
4124 	kfree(cb);
4125 }
4126 
4127 static void release_stripe_plug(struct mddev *mddev,
4128 				struct stripe_head *sh)
4129 {
4130 	struct blk_plug_cb *blk_cb = blk_check_plugged(
4131 		raid5_unplug, mddev,
4132 		sizeof(struct raid5_plug_cb));
4133 	struct raid5_plug_cb *cb;
4134 
4135 	if (!blk_cb) {
4136 		release_stripe(sh);
4137 		return;
4138 	}
4139 
4140 	cb = container_of(blk_cb, struct raid5_plug_cb, cb);
4141 
4142 	if (cb->list.next == NULL)
4143 		INIT_LIST_HEAD(&cb->list);
4144 
4145 	if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
4146 		list_add_tail(&sh->lru, &cb->list);
4147 	else
4148 		release_stripe(sh);
4149 }
4150 
4151 static void make_discard_request(struct mddev *mddev, struct bio *bi)
4152 {
4153 	struct r5conf *conf = mddev->private;
4154 	sector_t logical_sector, last_sector;
4155 	struct stripe_head *sh;
4156 	int remaining;
4157 	int stripe_sectors;
4158 
4159 	if (mddev->reshape_position != MaxSector)
4160 		/* Skip discard while reshape is happening */
4161 		return;
4162 
4163 	logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4164 	last_sector = bi->bi_sector + (bi->bi_size>>9);
4165 
4166 	bi->bi_next = NULL;
4167 	bi->bi_phys_segments = 1; /* over-loaded to count active stripes */
4168 
4169 	stripe_sectors = conf->chunk_sectors *
4170 		(conf->raid_disks - conf->max_degraded);
4171 	logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
4172 					       stripe_sectors);
4173 	sector_div(last_sector, stripe_sectors);
4174 
4175 	logical_sector *= conf->chunk_sectors;
4176 	last_sector *= conf->chunk_sectors;
4177 
4178 	for (; logical_sector < last_sector;
4179 	     logical_sector += STRIPE_SECTORS) {
4180 		DEFINE_WAIT(w);
4181 		int d;
4182 	again:
4183 		sh = get_active_stripe(conf, logical_sector, 0, 0, 0);
4184 		prepare_to_wait(&conf->wait_for_overlap, &w,
4185 				TASK_UNINTERRUPTIBLE);
4186 		set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
4187 		if (test_bit(STRIPE_SYNCING, &sh->state)) {
4188 			release_stripe(sh);
4189 			schedule();
4190 			goto again;
4191 		}
4192 		clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
4193 		spin_lock_irq(&sh->stripe_lock);
4194 		for (d = 0; d < conf->raid_disks; d++) {
4195 			if (d == sh->pd_idx || d == sh->qd_idx)
4196 				continue;
4197 			if (sh->dev[d].towrite || sh->dev[d].toread) {
4198 				set_bit(R5_Overlap, &sh->dev[d].flags);
4199 				spin_unlock_irq(&sh->stripe_lock);
4200 				release_stripe(sh);
4201 				schedule();
4202 				goto again;
4203 			}
4204 		}
4205 		set_bit(STRIPE_DISCARD, &sh->state);
4206 		finish_wait(&conf->wait_for_overlap, &w);
4207 		for (d = 0; d < conf->raid_disks; d++) {
4208 			if (d == sh->pd_idx || d == sh->qd_idx)
4209 				continue;
4210 			sh->dev[d].towrite = bi;
4211 			set_bit(R5_OVERWRITE, &sh->dev[d].flags);
4212 			raid5_inc_bi_active_stripes(bi);
4213 		}
4214 		spin_unlock_irq(&sh->stripe_lock);
4215 		if (conf->mddev->bitmap) {
4216 			for (d = 0;
4217 			     d < conf->raid_disks - conf->max_degraded;
4218 			     d++)
4219 				bitmap_startwrite(mddev->bitmap,
4220 						  sh->sector,
4221 						  STRIPE_SECTORS,
4222 						  0);
4223 			sh->bm_seq = conf->seq_flush + 1;
4224 			set_bit(STRIPE_BIT_DELAY, &sh->state);
4225 		}
4226 
4227 		set_bit(STRIPE_HANDLE, &sh->state);
4228 		clear_bit(STRIPE_DELAYED, &sh->state);
4229 		if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4230 			atomic_inc(&conf->preread_active_stripes);
4231 		release_stripe_plug(mddev, sh);
4232 	}
4233 
4234 	remaining = raid5_dec_bi_active_stripes(bi);
4235 	if (remaining == 0) {
4236 		md_write_end(mddev);
4237 		bio_endio(bi, 0);
4238 	}
4239 }
4240 
4241 static void make_request(struct mddev *mddev, struct bio * bi)
4242 {
4243 	struct r5conf *conf = mddev->private;
4244 	int dd_idx;
4245 	sector_t new_sector;
4246 	sector_t logical_sector, last_sector;
4247 	struct stripe_head *sh;
4248 	const int rw = bio_data_dir(bi);
4249 	int remaining;
4250 
4251 	if (unlikely(bi->bi_rw & REQ_FLUSH)) {
4252 		md_flush_request(mddev, bi);
4253 		return;
4254 	}
4255 
4256 	md_write_start(mddev, bi);
4257 
4258 	if (rw == READ &&
4259 	     mddev->reshape_position == MaxSector &&
4260 	     chunk_aligned_read(mddev,bi))
4261 		return;
4262 
4263 	if (unlikely(bi->bi_rw & REQ_DISCARD)) {
4264 		make_discard_request(mddev, bi);
4265 		return;
4266 	}
4267 
4268 	logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4269 	last_sector = bi->bi_sector + (bi->bi_size>>9);
4270 	bi->bi_next = NULL;
4271 	bi->bi_phys_segments = 1;	/* over-loaded to count active stripes */
4272 
4273 	for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
4274 		DEFINE_WAIT(w);
4275 		int previous;
4276 
4277 	retry:
4278 		previous = 0;
4279 		prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
4280 		if (unlikely(conf->reshape_progress != MaxSector)) {
4281 			/* spinlock is needed as reshape_progress may be
4282 			 * 64bit on a 32bit platform, and so it might be
4283 			 * possible to see a half-updated value
4284 			 * Of course reshape_progress could change after
4285 			 * the lock is dropped, so once we get a reference
4286 			 * to the stripe that we think it is, we will have
4287 			 * to check again.
4288 			 */
4289 			spin_lock_irq(&conf->device_lock);
4290 			if (mddev->reshape_backwards
4291 			    ? logical_sector < conf->reshape_progress
4292 			    : logical_sector >= conf->reshape_progress) {
4293 				previous = 1;
4294 			} else {
4295 				if (mddev->reshape_backwards
4296 				    ? logical_sector < conf->reshape_safe
4297 				    : logical_sector >= conf->reshape_safe) {
4298 					spin_unlock_irq(&conf->device_lock);
4299 					schedule();
4300 					goto retry;
4301 				}
4302 			}
4303 			spin_unlock_irq(&conf->device_lock);
4304 		}
4305 
4306 		new_sector = raid5_compute_sector(conf, logical_sector,
4307 						  previous,
4308 						  &dd_idx, NULL);
4309 		pr_debug("raid456: make_request, sector %llu logical %llu\n",
4310 			(unsigned long long)new_sector,
4311 			(unsigned long long)logical_sector);
4312 
4313 		sh = get_active_stripe(conf, new_sector, previous,
4314 				       (bi->bi_rw&RWA_MASK), 0);
4315 		if (sh) {
4316 			if (unlikely(previous)) {
4317 				/* expansion might have moved on while waiting for a
4318 				 * stripe, so we must do the range check again.
4319 				 * Expansion could still move past after this
4320 				 * test, but as we are holding a reference to
4321 				 * 'sh', we know that if that happens,
4322 				 *  STRIPE_EXPANDING will get set and the expansion
4323 				 * won't proceed until we finish with the stripe.
4324 				 */
4325 				int must_retry = 0;
4326 				spin_lock_irq(&conf->device_lock);
4327 				if (mddev->reshape_backwards
4328 				    ? logical_sector >= conf->reshape_progress
4329 				    : logical_sector < conf->reshape_progress)
4330 					/* mismatch, need to try again */
4331 					must_retry = 1;
4332 				spin_unlock_irq(&conf->device_lock);
4333 				if (must_retry) {
4334 					release_stripe(sh);
4335 					schedule();
4336 					goto retry;
4337 				}
4338 			}
4339 
4340 			if (rw == WRITE &&
4341 			    logical_sector >= mddev->suspend_lo &&
4342 			    logical_sector < mddev->suspend_hi) {
4343 				release_stripe(sh);
4344 				/* As the suspend_* range is controlled by
4345 				 * userspace, we want an interruptible
4346 				 * wait.
4347 				 */
4348 				flush_signals(current);
4349 				prepare_to_wait(&conf->wait_for_overlap,
4350 						&w, TASK_INTERRUPTIBLE);
4351 				if (logical_sector >= mddev->suspend_lo &&
4352 				    logical_sector < mddev->suspend_hi)
4353 					schedule();
4354 				goto retry;
4355 			}
4356 
4357 			if (test_bit(STRIPE_EXPANDING, &sh->state) ||
4358 			    !add_stripe_bio(sh, bi, dd_idx, rw)) {
4359 				/* Stripe is busy expanding or
4360 				 * add failed due to overlap.  Flush everything
4361 				 * and wait a while
4362 				 */
4363 				md_wakeup_thread(mddev->thread);
4364 				release_stripe(sh);
4365 				schedule();
4366 				goto retry;
4367 			}
4368 			finish_wait(&conf->wait_for_overlap, &w);
4369 			set_bit(STRIPE_HANDLE, &sh->state);
4370 			clear_bit(STRIPE_DELAYED, &sh->state);
4371 			if ((bi->bi_rw & REQ_SYNC) &&
4372 			    !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4373 				atomic_inc(&conf->preread_active_stripes);
4374 			release_stripe_plug(mddev, sh);
4375 		} else {
4376 			/* cannot get stripe for read-ahead, just give-up */
4377 			clear_bit(BIO_UPTODATE, &bi->bi_flags);
4378 			finish_wait(&conf->wait_for_overlap, &w);
4379 			break;
4380 		}
4381 	}
4382 
4383 	remaining = raid5_dec_bi_active_stripes(bi);
4384 	if (remaining == 0) {
4385 
4386 		if ( rw == WRITE )
4387 			md_write_end(mddev);
4388 
4389 		trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
4390 					 bi, 0);
4391 		bio_endio(bi, 0);
4392 	}
4393 }
4394 
4395 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
4396 
4397 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
4398 {
4399 	/* reshaping is quite different to recovery/resync so it is
4400 	 * handled quite separately ... here.
4401 	 *
4402 	 * On each call to sync_request, we gather one chunk worth of
4403 	 * destination stripes and flag them as expanding.
4404 	 * Then we find all the source stripes and request reads.
4405 	 * As the reads complete, handle_stripe will copy the data
4406 	 * into the destination stripe and release that stripe.
4407 	 */
4408 	struct r5conf *conf = mddev->private;
4409 	struct stripe_head *sh;
4410 	sector_t first_sector, last_sector;
4411 	int raid_disks = conf->previous_raid_disks;
4412 	int data_disks = raid_disks - conf->max_degraded;
4413 	int new_data_disks = conf->raid_disks - conf->max_degraded;
4414 	int i;
4415 	int dd_idx;
4416 	sector_t writepos, readpos, safepos;
4417 	sector_t stripe_addr;
4418 	int reshape_sectors;
4419 	struct list_head stripes;
4420 
4421 	if (sector_nr == 0) {
4422 		/* If restarting in the middle, skip the initial sectors */
4423 		if (mddev->reshape_backwards &&
4424 		    conf->reshape_progress < raid5_size(mddev, 0, 0)) {
4425 			sector_nr = raid5_size(mddev, 0, 0)
4426 				- conf->reshape_progress;
4427 		} else if (!mddev->reshape_backwards &&
4428 			   conf->reshape_progress > 0)
4429 			sector_nr = conf->reshape_progress;
4430 		sector_div(sector_nr, new_data_disks);
4431 		if (sector_nr) {
4432 			mddev->curr_resync_completed = sector_nr;
4433 			sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4434 			*skipped = 1;
4435 			return sector_nr;
4436 		}
4437 	}
4438 
4439 	/* We need to process a full chunk at a time.
4440 	 * If old and new chunk sizes differ, we need to process the
4441 	 * largest of these
4442 	 */
4443 	if (mddev->new_chunk_sectors > mddev->chunk_sectors)
4444 		reshape_sectors = mddev->new_chunk_sectors;
4445 	else
4446 		reshape_sectors = mddev->chunk_sectors;
4447 
4448 	/* We update the metadata at least every 10 seconds, or when
4449 	 * the data about to be copied would over-write the source of
4450 	 * the data at the front of the range.  i.e. one new_stripe
4451 	 * along from reshape_progress new_maps to after where
4452 	 * reshape_safe old_maps to
4453 	 */
4454 	writepos = conf->reshape_progress;
4455 	sector_div(writepos, new_data_disks);
4456 	readpos = conf->reshape_progress;
4457 	sector_div(readpos, data_disks);
4458 	safepos = conf->reshape_safe;
4459 	sector_div(safepos, data_disks);
4460 	if (mddev->reshape_backwards) {
4461 		writepos -= min_t(sector_t, reshape_sectors, writepos);
4462 		readpos += reshape_sectors;
4463 		safepos += reshape_sectors;
4464 	} else {
4465 		writepos += reshape_sectors;
4466 		readpos -= min_t(sector_t, reshape_sectors, readpos);
4467 		safepos -= min_t(sector_t, reshape_sectors, safepos);
4468 	}
4469 
4470 	/* Having calculated the 'writepos' possibly use it
4471 	 * to set 'stripe_addr' which is where we will write to.
4472 	 */
4473 	if (mddev->reshape_backwards) {
4474 		BUG_ON(conf->reshape_progress == 0);
4475 		stripe_addr = writepos;
4476 		BUG_ON((mddev->dev_sectors &
4477 			~((sector_t)reshape_sectors - 1))
4478 		       - reshape_sectors - stripe_addr
4479 		       != sector_nr);
4480 	} else {
4481 		BUG_ON(writepos != sector_nr + reshape_sectors);
4482 		stripe_addr = sector_nr;
4483 	}
4484 
4485 	/* 'writepos' is the most advanced device address we might write.
4486 	 * 'readpos' is the least advanced device address we might read.
4487 	 * 'safepos' is the least address recorded in the metadata as having
4488 	 *     been reshaped.
4489 	 * If there is a min_offset_diff, these are adjusted either by
4490 	 * increasing the safepos/readpos if diff is negative, or
4491 	 * increasing writepos if diff is positive.
4492 	 * If 'readpos' is then behind 'writepos', there is no way that we can
4493 	 * ensure safety in the face of a crash - that must be done by userspace
4494 	 * making a backup of the data.  So in that case there is no particular
4495 	 * rush to update metadata.
4496 	 * Otherwise if 'safepos' is behind 'writepos', then we really need to
4497 	 * update the metadata to advance 'safepos' to match 'readpos' so that
4498 	 * we can be safe in the event of a crash.
4499 	 * So we insist on updating metadata if safepos is behind writepos and
4500 	 * readpos is beyond writepos.
4501 	 * In any case, update the metadata every 10 seconds.
4502 	 * Maybe that number should be configurable, but I'm not sure it is
4503 	 * worth it.... maybe it could be a multiple of safemode_delay???
4504 	 */
4505 	if (conf->min_offset_diff < 0) {
4506 		safepos += -conf->min_offset_diff;
4507 		readpos += -conf->min_offset_diff;
4508 	} else
4509 		writepos += conf->min_offset_diff;
4510 
4511 	if ((mddev->reshape_backwards
4512 	     ? (safepos > writepos && readpos < writepos)
4513 	     : (safepos < writepos && readpos > writepos)) ||
4514 	    time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
4515 		/* Cannot proceed until we've updated the superblock... */
4516 		wait_event(conf->wait_for_overlap,
4517 			   atomic_read(&conf->reshape_stripes)==0);
4518 		mddev->reshape_position = conf->reshape_progress;
4519 		mddev->curr_resync_completed = sector_nr;
4520 		conf->reshape_checkpoint = jiffies;
4521 		set_bit(MD_CHANGE_DEVS, &mddev->flags);
4522 		md_wakeup_thread(mddev->thread);
4523 		wait_event(mddev->sb_wait, mddev->flags == 0 ||
4524 			   kthread_should_stop());
4525 		spin_lock_irq(&conf->device_lock);
4526 		conf->reshape_safe = mddev->reshape_position;
4527 		spin_unlock_irq(&conf->device_lock);
4528 		wake_up(&conf->wait_for_overlap);
4529 		sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4530 	}
4531 
4532 	INIT_LIST_HEAD(&stripes);
4533 	for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
4534 		int j;
4535 		int skipped_disk = 0;
4536 		sh = get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
4537 		set_bit(STRIPE_EXPANDING, &sh->state);
4538 		atomic_inc(&conf->reshape_stripes);
4539 		/* If any of this stripe is beyond the end of the old
4540 		 * array, then we need to zero those blocks
4541 		 */
4542 		for (j=sh->disks; j--;) {
4543 			sector_t s;
4544 			if (j == sh->pd_idx)
4545 				continue;
4546 			if (conf->level == 6 &&
4547 			    j == sh->qd_idx)
4548 				continue;
4549 			s = compute_blocknr(sh, j, 0);
4550 			if (s < raid5_size(mddev, 0, 0)) {
4551 				skipped_disk = 1;
4552 				continue;
4553 			}
4554 			memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
4555 			set_bit(R5_Expanded, &sh->dev[j].flags);
4556 			set_bit(R5_UPTODATE, &sh->dev[j].flags);
4557 		}
4558 		if (!skipped_disk) {
4559 			set_bit(STRIPE_EXPAND_READY, &sh->state);
4560 			set_bit(STRIPE_HANDLE, &sh->state);
4561 		}
4562 		list_add(&sh->lru, &stripes);
4563 	}
4564 	spin_lock_irq(&conf->device_lock);
4565 	if (mddev->reshape_backwards)
4566 		conf->reshape_progress -= reshape_sectors * new_data_disks;
4567 	else
4568 		conf->reshape_progress += reshape_sectors * new_data_disks;
4569 	spin_unlock_irq(&conf->device_lock);
4570 	/* Ok, those stripe are ready. We can start scheduling
4571 	 * reads on the source stripes.
4572 	 * The source stripes are determined by mapping the first and last
4573 	 * block on the destination stripes.
4574 	 */
4575 	first_sector =
4576 		raid5_compute_sector(conf, stripe_addr*(new_data_disks),
4577 				     1, &dd_idx, NULL);
4578 	last_sector =
4579 		raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
4580 					    * new_data_disks - 1),
4581 				     1, &dd_idx, NULL);
4582 	if (last_sector >= mddev->dev_sectors)
4583 		last_sector = mddev->dev_sectors - 1;
4584 	while (first_sector <= last_sector) {
4585 		sh = get_active_stripe(conf, first_sector, 1, 0, 1);
4586 		set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4587 		set_bit(STRIPE_HANDLE, &sh->state);
4588 		release_stripe(sh);
4589 		first_sector += STRIPE_SECTORS;
4590 	}
4591 	/* Now that the sources are clearly marked, we can release
4592 	 * the destination stripes
4593 	 */
4594 	while (!list_empty(&stripes)) {
4595 		sh = list_entry(stripes.next, struct stripe_head, lru);
4596 		list_del_init(&sh->lru);
4597 		release_stripe(sh);
4598 	}
4599 	/* If this takes us to the resync_max point where we have to pause,
4600 	 * then we need to write out the superblock.
4601 	 */
4602 	sector_nr += reshape_sectors;
4603 	if ((sector_nr - mddev->curr_resync_completed) * 2
4604 	    >= mddev->resync_max - mddev->curr_resync_completed) {
4605 		/* Cannot proceed until we've updated the superblock... */
4606 		wait_event(conf->wait_for_overlap,
4607 			   atomic_read(&conf->reshape_stripes) == 0);
4608 		mddev->reshape_position = conf->reshape_progress;
4609 		mddev->curr_resync_completed = sector_nr;
4610 		conf->reshape_checkpoint = jiffies;
4611 		set_bit(MD_CHANGE_DEVS, &mddev->flags);
4612 		md_wakeup_thread(mddev->thread);
4613 		wait_event(mddev->sb_wait,
4614 			   !test_bit(MD_CHANGE_DEVS, &mddev->flags)
4615 			   || kthread_should_stop());
4616 		spin_lock_irq(&conf->device_lock);
4617 		conf->reshape_safe = mddev->reshape_position;
4618 		spin_unlock_irq(&conf->device_lock);
4619 		wake_up(&conf->wait_for_overlap);
4620 		sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4621 	}
4622 	return reshape_sectors;
4623 }
4624 
4625 /* FIXME go_faster isn't used */
4626 static inline sector_t sync_request(struct mddev *mddev, sector_t sector_nr, int *skipped, int go_faster)
4627 {
4628 	struct r5conf *conf = mddev->private;
4629 	struct stripe_head *sh;
4630 	sector_t max_sector = mddev->dev_sectors;
4631 	sector_t sync_blocks;
4632 	int still_degraded = 0;
4633 	int i;
4634 
4635 	if (sector_nr >= max_sector) {
4636 		/* just being told to finish up .. nothing much to do */
4637 
4638 		if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
4639 			end_reshape(conf);
4640 			return 0;
4641 		}
4642 
4643 		if (mddev->curr_resync < max_sector) /* aborted */
4644 			bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
4645 					&sync_blocks, 1);
4646 		else /* completed sync */
4647 			conf->fullsync = 0;
4648 		bitmap_close_sync(mddev->bitmap);
4649 
4650 		return 0;
4651 	}
4652 
4653 	/* Allow raid5_quiesce to complete */
4654 	wait_event(conf->wait_for_overlap, conf->quiesce != 2);
4655 
4656 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4657 		return reshape_request(mddev, sector_nr, skipped);
4658 
4659 	/* No need to check resync_max as we never do more than one
4660 	 * stripe, and as resync_max will always be on a chunk boundary,
4661 	 * if the check in md_do_sync didn't fire, there is no chance
4662 	 * of overstepping resync_max here
4663 	 */
4664 
4665 	/* if there is too many failed drives and we are trying
4666 	 * to resync, then assert that we are finished, because there is
4667 	 * nothing we can do.
4668 	 */
4669 	if (mddev->degraded >= conf->max_degraded &&
4670 	    test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4671 		sector_t rv = mddev->dev_sectors - sector_nr;
4672 		*skipped = 1;
4673 		return rv;
4674 	}
4675 	if (!bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
4676 	    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
4677 	    !conf->fullsync && sync_blocks >= STRIPE_SECTORS) {
4678 		/* we can skip this block, and probably more */
4679 		sync_blocks /= STRIPE_SECTORS;
4680 		*skipped = 1;
4681 		return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
4682 	}
4683 
4684 	bitmap_cond_end_sync(mddev->bitmap, sector_nr);
4685 
4686 	sh = get_active_stripe(conf, sector_nr, 0, 1, 0);
4687 	if (sh == NULL) {
4688 		sh = get_active_stripe(conf, sector_nr, 0, 0, 0);
4689 		/* make sure we don't swamp the stripe cache if someone else
4690 		 * is trying to get access
4691 		 */
4692 		schedule_timeout_uninterruptible(1);
4693 	}
4694 	/* Need to check if array will still be degraded after recovery/resync
4695 	 * We don't need to check the 'failed' flag as when that gets set,
4696 	 * recovery aborts.
4697 	 */
4698 	for (i = 0; i < conf->raid_disks; i++)
4699 		if (conf->disks[i].rdev == NULL)
4700 			still_degraded = 1;
4701 
4702 	bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
4703 
4704 	set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
4705 
4706 	handle_stripe(sh);
4707 	release_stripe(sh);
4708 
4709 	return STRIPE_SECTORS;
4710 }
4711 
4712 static int  retry_aligned_read(struct r5conf *conf, struct bio *raid_bio)
4713 {
4714 	/* We may not be able to submit a whole bio at once as there
4715 	 * may not be enough stripe_heads available.
4716 	 * We cannot pre-allocate enough stripe_heads as we may need
4717 	 * more than exist in the cache (if we allow ever large chunks).
4718 	 * So we do one stripe head at a time and record in
4719 	 * ->bi_hw_segments how many have been done.
4720 	 *
4721 	 * We *know* that this entire raid_bio is in one chunk, so
4722 	 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
4723 	 */
4724 	struct stripe_head *sh;
4725 	int dd_idx;
4726 	sector_t sector, logical_sector, last_sector;
4727 	int scnt = 0;
4728 	int remaining;
4729 	int handled = 0;
4730 
4731 	logical_sector = raid_bio->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4732 	sector = raid5_compute_sector(conf, logical_sector,
4733 				      0, &dd_idx, NULL);
4734 	last_sector = raid_bio->bi_sector + (raid_bio->bi_size>>9);
4735 
4736 	for (; logical_sector < last_sector;
4737 	     logical_sector += STRIPE_SECTORS,
4738 		     sector += STRIPE_SECTORS,
4739 		     scnt++) {
4740 
4741 		if (scnt < raid5_bi_processed_stripes(raid_bio))
4742 			/* already done this stripe */
4743 			continue;
4744 
4745 		sh = get_active_stripe(conf, sector, 0, 1, 0);
4746 
4747 		if (!sh) {
4748 			/* failed to get a stripe - must wait */
4749 			raid5_set_bi_processed_stripes(raid_bio, scnt);
4750 			conf->retry_read_aligned = raid_bio;
4751 			return handled;
4752 		}
4753 
4754 		if (!add_stripe_bio(sh, raid_bio, dd_idx, 0)) {
4755 			release_stripe(sh);
4756 			raid5_set_bi_processed_stripes(raid_bio, scnt);
4757 			conf->retry_read_aligned = raid_bio;
4758 			return handled;
4759 		}
4760 
4761 		set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
4762 		handle_stripe(sh);
4763 		release_stripe(sh);
4764 		handled++;
4765 	}
4766 	remaining = raid5_dec_bi_active_stripes(raid_bio);
4767 	if (remaining == 0) {
4768 		trace_block_bio_complete(bdev_get_queue(raid_bio->bi_bdev),
4769 					 raid_bio, 0);
4770 		bio_endio(raid_bio, 0);
4771 	}
4772 	if (atomic_dec_and_test(&conf->active_aligned_reads))
4773 		wake_up(&conf->wait_for_stripe);
4774 	return handled;
4775 }
4776 
4777 #define MAX_STRIPE_BATCH 8
4778 static int handle_active_stripes(struct r5conf *conf)
4779 {
4780 	struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
4781 	int i, batch_size = 0;
4782 
4783 	while (batch_size < MAX_STRIPE_BATCH &&
4784 			(sh = __get_priority_stripe(conf)) != NULL)
4785 		batch[batch_size++] = sh;
4786 
4787 	if (batch_size == 0)
4788 		return batch_size;
4789 	spin_unlock_irq(&conf->device_lock);
4790 
4791 	for (i = 0; i < batch_size; i++)
4792 		handle_stripe(batch[i]);
4793 
4794 	cond_resched();
4795 
4796 	spin_lock_irq(&conf->device_lock);
4797 	for (i = 0; i < batch_size; i++)
4798 		__release_stripe(conf, batch[i]);
4799 	return batch_size;
4800 }
4801 
4802 /*
4803  * This is our raid5 kernel thread.
4804  *
4805  * We scan the hash table for stripes which can be handled now.
4806  * During the scan, completed stripes are saved for us by the interrupt
4807  * handler, so that they will not have to wait for our next wakeup.
4808  */
4809 static void raid5d(struct md_thread *thread)
4810 {
4811 	struct mddev *mddev = thread->mddev;
4812 	struct r5conf *conf = mddev->private;
4813 	int handled;
4814 	struct blk_plug plug;
4815 
4816 	pr_debug("+++ raid5d active\n");
4817 
4818 	md_check_recovery(mddev);
4819 
4820 	blk_start_plug(&plug);
4821 	handled = 0;
4822 	spin_lock_irq(&conf->device_lock);
4823 	while (1) {
4824 		struct bio *bio;
4825 		int batch_size;
4826 
4827 		if (
4828 		    !list_empty(&conf->bitmap_list)) {
4829 			/* Now is a good time to flush some bitmap updates */
4830 			conf->seq_flush++;
4831 			spin_unlock_irq(&conf->device_lock);
4832 			bitmap_unplug(mddev->bitmap);
4833 			spin_lock_irq(&conf->device_lock);
4834 			conf->seq_write = conf->seq_flush;
4835 			activate_bit_delay(conf);
4836 		}
4837 		raid5_activate_delayed(conf);
4838 
4839 		while ((bio = remove_bio_from_retry(conf))) {
4840 			int ok;
4841 			spin_unlock_irq(&conf->device_lock);
4842 			ok = retry_aligned_read(conf, bio);
4843 			spin_lock_irq(&conf->device_lock);
4844 			if (!ok)
4845 				break;
4846 			handled++;
4847 		}
4848 
4849 		batch_size = handle_active_stripes(conf);
4850 		if (!batch_size)
4851 			break;
4852 		handled += batch_size;
4853 
4854 		if (mddev->flags & ~(1<<MD_CHANGE_PENDING)) {
4855 			spin_unlock_irq(&conf->device_lock);
4856 			md_check_recovery(mddev);
4857 			spin_lock_irq(&conf->device_lock);
4858 		}
4859 	}
4860 	pr_debug("%d stripes handled\n", handled);
4861 
4862 	spin_unlock_irq(&conf->device_lock);
4863 
4864 	async_tx_issue_pending_all();
4865 	blk_finish_plug(&plug);
4866 
4867 	pr_debug("--- raid5d inactive\n");
4868 }
4869 
4870 static ssize_t
4871 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
4872 {
4873 	struct r5conf *conf = mddev->private;
4874 	if (conf)
4875 		return sprintf(page, "%d\n", conf->max_nr_stripes);
4876 	else
4877 		return 0;
4878 }
4879 
4880 int
4881 raid5_set_cache_size(struct mddev *mddev, int size)
4882 {
4883 	struct r5conf *conf = mddev->private;
4884 	int err;
4885 
4886 	if (size <= 16 || size > 32768)
4887 		return -EINVAL;
4888 	while (size < conf->max_nr_stripes) {
4889 		if (drop_one_stripe(conf))
4890 			conf->max_nr_stripes--;
4891 		else
4892 			break;
4893 	}
4894 	err = md_allow_write(mddev);
4895 	if (err)
4896 		return err;
4897 	while (size > conf->max_nr_stripes) {
4898 		if (grow_one_stripe(conf))
4899 			conf->max_nr_stripes++;
4900 		else break;
4901 	}
4902 	return 0;
4903 }
4904 EXPORT_SYMBOL(raid5_set_cache_size);
4905 
4906 static ssize_t
4907 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
4908 {
4909 	struct r5conf *conf = mddev->private;
4910 	unsigned long new;
4911 	int err;
4912 
4913 	if (len >= PAGE_SIZE)
4914 		return -EINVAL;
4915 	if (!conf)
4916 		return -ENODEV;
4917 
4918 	if (strict_strtoul(page, 10, &new))
4919 		return -EINVAL;
4920 	err = raid5_set_cache_size(mddev, new);
4921 	if (err)
4922 		return err;
4923 	return len;
4924 }
4925 
4926 static struct md_sysfs_entry
4927 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
4928 				raid5_show_stripe_cache_size,
4929 				raid5_store_stripe_cache_size);
4930 
4931 static ssize_t
4932 raid5_show_preread_threshold(struct mddev *mddev, char *page)
4933 {
4934 	struct r5conf *conf = mddev->private;
4935 	if (conf)
4936 		return sprintf(page, "%d\n", conf->bypass_threshold);
4937 	else
4938 		return 0;
4939 }
4940 
4941 static ssize_t
4942 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
4943 {
4944 	struct r5conf *conf = mddev->private;
4945 	unsigned long new;
4946 	if (len >= PAGE_SIZE)
4947 		return -EINVAL;
4948 	if (!conf)
4949 		return -ENODEV;
4950 
4951 	if (strict_strtoul(page, 10, &new))
4952 		return -EINVAL;
4953 	if (new > conf->max_nr_stripes)
4954 		return -EINVAL;
4955 	conf->bypass_threshold = new;
4956 	return len;
4957 }
4958 
4959 static struct md_sysfs_entry
4960 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
4961 					S_IRUGO | S_IWUSR,
4962 					raid5_show_preread_threshold,
4963 					raid5_store_preread_threshold);
4964 
4965 static ssize_t
4966 stripe_cache_active_show(struct mddev *mddev, char *page)
4967 {
4968 	struct r5conf *conf = mddev->private;
4969 	if (conf)
4970 		return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
4971 	else
4972 		return 0;
4973 }
4974 
4975 static struct md_sysfs_entry
4976 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
4977 
4978 static struct attribute *raid5_attrs[] =  {
4979 	&raid5_stripecache_size.attr,
4980 	&raid5_stripecache_active.attr,
4981 	&raid5_preread_bypass_threshold.attr,
4982 	NULL,
4983 };
4984 static struct attribute_group raid5_attrs_group = {
4985 	.name = NULL,
4986 	.attrs = raid5_attrs,
4987 };
4988 
4989 static sector_t
4990 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
4991 {
4992 	struct r5conf *conf = mddev->private;
4993 
4994 	if (!sectors)
4995 		sectors = mddev->dev_sectors;
4996 	if (!raid_disks)
4997 		/* size is defined by the smallest of previous and new size */
4998 		raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
4999 
5000 	sectors &= ~((sector_t)mddev->chunk_sectors - 1);
5001 	sectors &= ~((sector_t)mddev->new_chunk_sectors - 1);
5002 	return sectors * (raid_disks - conf->max_degraded);
5003 }
5004 
5005 static void raid5_free_percpu(struct r5conf *conf)
5006 {
5007 	struct raid5_percpu *percpu;
5008 	unsigned long cpu;
5009 
5010 	if (!conf->percpu)
5011 		return;
5012 
5013 	get_online_cpus();
5014 	for_each_possible_cpu(cpu) {
5015 		percpu = per_cpu_ptr(conf->percpu, cpu);
5016 		safe_put_page(percpu->spare_page);
5017 		kfree(percpu->scribble);
5018 	}
5019 #ifdef CONFIG_HOTPLUG_CPU
5020 	unregister_cpu_notifier(&conf->cpu_notify);
5021 #endif
5022 	put_online_cpus();
5023 
5024 	free_percpu(conf->percpu);
5025 }
5026 
5027 static void free_conf(struct r5conf *conf)
5028 {
5029 	shrink_stripes(conf);
5030 	raid5_free_percpu(conf);
5031 	kfree(conf->disks);
5032 	kfree(conf->stripe_hashtbl);
5033 	kfree(conf);
5034 }
5035 
5036 #ifdef CONFIG_HOTPLUG_CPU
5037 static int raid456_cpu_notify(struct notifier_block *nfb, unsigned long action,
5038 			      void *hcpu)
5039 {
5040 	struct r5conf *conf = container_of(nfb, struct r5conf, cpu_notify);
5041 	long cpu = (long)hcpu;
5042 	struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
5043 
5044 	switch (action) {
5045 	case CPU_UP_PREPARE:
5046 	case CPU_UP_PREPARE_FROZEN:
5047 		if (conf->level == 6 && !percpu->spare_page)
5048 			percpu->spare_page = alloc_page(GFP_KERNEL);
5049 		if (!percpu->scribble)
5050 			percpu->scribble = kmalloc(conf->scribble_len, GFP_KERNEL);
5051 
5052 		if (!percpu->scribble ||
5053 		    (conf->level == 6 && !percpu->spare_page)) {
5054 			safe_put_page(percpu->spare_page);
5055 			kfree(percpu->scribble);
5056 			pr_err("%s: failed memory allocation for cpu%ld\n",
5057 			       __func__, cpu);
5058 			return notifier_from_errno(-ENOMEM);
5059 		}
5060 		break;
5061 	case CPU_DEAD:
5062 	case CPU_DEAD_FROZEN:
5063 		safe_put_page(percpu->spare_page);
5064 		kfree(percpu->scribble);
5065 		percpu->spare_page = NULL;
5066 		percpu->scribble = NULL;
5067 		break;
5068 	default:
5069 		break;
5070 	}
5071 	return NOTIFY_OK;
5072 }
5073 #endif
5074 
5075 static int raid5_alloc_percpu(struct r5conf *conf)
5076 {
5077 	unsigned long cpu;
5078 	struct page *spare_page;
5079 	struct raid5_percpu __percpu *allcpus;
5080 	void *scribble;
5081 	int err;
5082 
5083 	allcpus = alloc_percpu(struct raid5_percpu);
5084 	if (!allcpus)
5085 		return -ENOMEM;
5086 	conf->percpu = allcpus;
5087 
5088 	get_online_cpus();
5089 	err = 0;
5090 	for_each_present_cpu(cpu) {
5091 		if (conf->level == 6) {
5092 			spare_page = alloc_page(GFP_KERNEL);
5093 			if (!spare_page) {
5094 				err = -ENOMEM;
5095 				break;
5096 			}
5097 			per_cpu_ptr(conf->percpu, cpu)->spare_page = spare_page;
5098 		}
5099 		scribble = kmalloc(conf->scribble_len, GFP_KERNEL);
5100 		if (!scribble) {
5101 			err = -ENOMEM;
5102 			break;
5103 		}
5104 		per_cpu_ptr(conf->percpu, cpu)->scribble = scribble;
5105 	}
5106 #ifdef CONFIG_HOTPLUG_CPU
5107 	conf->cpu_notify.notifier_call = raid456_cpu_notify;
5108 	conf->cpu_notify.priority = 0;
5109 	if (err == 0)
5110 		err = register_cpu_notifier(&conf->cpu_notify);
5111 #endif
5112 	put_online_cpus();
5113 
5114 	return err;
5115 }
5116 
5117 static struct r5conf *setup_conf(struct mddev *mddev)
5118 {
5119 	struct r5conf *conf;
5120 	int raid_disk, memory, max_disks;
5121 	struct md_rdev *rdev;
5122 	struct disk_info *disk;
5123 	char pers_name[6];
5124 
5125 	if (mddev->new_level != 5
5126 	    && mddev->new_level != 4
5127 	    && mddev->new_level != 6) {
5128 		printk(KERN_ERR "md/raid:%s: raid level not set to 4/5/6 (%d)\n",
5129 		       mdname(mddev), mddev->new_level);
5130 		return ERR_PTR(-EIO);
5131 	}
5132 	if ((mddev->new_level == 5
5133 	     && !algorithm_valid_raid5(mddev->new_layout)) ||
5134 	    (mddev->new_level == 6
5135 	     && !algorithm_valid_raid6(mddev->new_layout))) {
5136 		printk(KERN_ERR "md/raid:%s: layout %d not supported\n",
5137 		       mdname(mddev), mddev->new_layout);
5138 		return ERR_PTR(-EIO);
5139 	}
5140 	if (mddev->new_level == 6 && mddev->raid_disks < 4) {
5141 		printk(KERN_ERR "md/raid:%s: not enough configured devices (%d, minimum 4)\n",
5142 		       mdname(mddev), mddev->raid_disks);
5143 		return ERR_PTR(-EINVAL);
5144 	}
5145 
5146 	if (!mddev->new_chunk_sectors ||
5147 	    (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
5148 	    !is_power_of_2(mddev->new_chunk_sectors)) {
5149 		printk(KERN_ERR "md/raid:%s: invalid chunk size %d\n",
5150 		       mdname(mddev), mddev->new_chunk_sectors << 9);
5151 		return ERR_PTR(-EINVAL);
5152 	}
5153 
5154 	conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
5155 	if (conf == NULL)
5156 		goto abort;
5157 	spin_lock_init(&conf->device_lock);
5158 	init_waitqueue_head(&conf->wait_for_stripe);
5159 	init_waitqueue_head(&conf->wait_for_overlap);
5160 	INIT_LIST_HEAD(&conf->handle_list);
5161 	INIT_LIST_HEAD(&conf->hold_list);
5162 	INIT_LIST_HEAD(&conf->delayed_list);
5163 	INIT_LIST_HEAD(&conf->bitmap_list);
5164 	INIT_LIST_HEAD(&conf->inactive_list);
5165 	atomic_set(&conf->active_stripes, 0);
5166 	atomic_set(&conf->preread_active_stripes, 0);
5167 	atomic_set(&conf->active_aligned_reads, 0);
5168 	conf->bypass_threshold = BYPASS_THRESHOLD;
5169 	conf->recovery_disabled = mddev->recovery_disabled - 1;
5170 
5171 	conf->raid_disks = mddev->raid_disks;
5172 	if (mddev->reshape_position == MaxSector)
5173 		conf->previous_raid_disks = mddev->raid_disks;
5174 	else
5175 		conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
5176 	max_disks = max(conf->raid_disks, conf->previous_raid_disks);
5177 	conf->scribble_len = scribble_len(max_disks);
5178 
5179 	conf->disks = kzalloc(max_disks * sizeof(struct disk_info),
5180 			      GFP_KERNEL);
5181 	if (!conf->disks)
5182 		goto abort;
5183 
5184 	conf->mddev = mddev;
5185 
5186 	if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
5187 		goto abort;
5188 
5189 	conf->level = mddev->new_level;
5190 	if (raid5_alloc_percpu(conf) != 0)
5191 		goto abort;
5192 
5193 	pr_debug("raid456: run(%s) called.\n", mdname(mddev));
5194 
5195 	rdev_for_each(rdev, mddev) {
5196 		raid_disk = rdev->raid_disk;
5197 		if (raid_disk >= max_disks
5198 		    || raid_disk < 0)
5199 			continue;
5200 		disk = conf->disks + raid_disk;
5201 
5202 		if (test_bit(Replacement, &rdev->flags)) {
5203 			if (disk->replacement)
5204 				goto abort;
5205 			disk->replacement = rdev;
5206 		} else {
5207 			if (disk->rdev)
5208 				goto abort;
5209 			disk->rdev = rdev;
5210 		}
5211 
5212 		if (test_bit(In_sync, &rdev->flags)) {
5213 			char b[BDEVNAME_SIZE];
5214 			printk(KERN_INFO "md/raid:%s: device %s operational as raid"
5215 			       " disk %d\n",
5216 			       mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
5217 		} else if (rdev->saved_raid_disk != raid_disk)
5218 			/* Cannot rely on bitmap to complete recovery */
5219 			conf->fullsync = 1;
5220 	}
5221 
5222 	conf->chunk_sectors = mddev->new_chunk_sectors;
5223 	conf->level = mddev->new_level;
5224 	if (conf->level == 6)
5225 		conf->max_degraded = 2;
5226 	else
5227 		conf->max_degraded = 1;
5228 	conf->algorithm = mddev->new_layout;
5229 	conf->max_nr_stripes = NR_STRIPES;
5230 	conf->reshape_progress = mddev->reshape_position;
5231 	if (conf->reshape_progress != MaxSector) {
5232 		conf->prev_chunk_sectors = mddev->chunk_sectors;
5233 		conf->prev_algo = mddev->layout;
5234 	}
5235 
5236 	memory = conf->max_nr_stripes * (sizeof(struct stripe_head) +
5237 		 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
5238 	if (grow_stripes(conf, conf->max_nr_stripes)) {
5239 		printk(KERN_ERR
5240 		       "md/raid:%s: couldn't allocate %dkB for buffers\n",
5241 		       mdname(mddev), memory);
5242 		goto abort;
5243 	} else
5244 		printk(KERN_INFO "md/raid:%s: allocated %dkB\n",
5245 		       mdname(mddev), memory);
5246 
5247 	sprintf(pers_name, "raid%d", mddev->new_level);
5248 	conf->thread = md_register_thread(raid5d, mddev, pers_name);
5249 	if (!conf->thread) {
5250 		printk(KERN_ERR
5251 		       "md/raid:%s: couldn't allocate thread.\n",
5252 		       mdname(mddev));
5253 		goto abort;
5254 	}
5255 
5256 	return conf;
5257 
5258  abort:
5259 	if (conf) {
5260 		free_conf(conf);
5261 		return ERR_PTR(-EIO);
5262 	} else
5263 		return ERR_PTR(-ENOMEM);
5264 }
5265 
5266 
5267 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
5268 {
5269 	switch (algo) {
5270 	case ALGORITHM_PARITY_0:
5271 		if (raid_disk < max_degraded)
5272 			return 1;
5273 		break;
5274 	case ALGORITHM_PARITY_N:
5275 		if (raid_disk >= raid_disks - max_degraded)
5276 			return 1;
5277 		break;
5278 	case ALGORITHM_PARITY_0_6:
5279 		if (raid_disk == 0 ||
5280 		    raid_disk == raid_disks - 1)
5281 			return 1;
5282 		break;
5283 	case ALGORITHM_LEFT_ASYMMETRIC_6:
5284 	case ALGORITHM_RIGHT_ASYMMETRIC_6:
5285 	case ALGORITHM_LEFT_SYMMETRIC_6:
5286 	case ALGORITHM_RIGHT_SYMMETRIC_6:
5287 		if (raid_disk == raid_disks - 1)
5288 			return 1;
5289 	}
5290 	return 0;
5291 }
5292 
5293 static int run(struct mddev *mddev)
5294 {
5295 	struct r5conf *conf;
5296 	int working_disks = 0;
5297 	int dirty_parity_disks = 0;
5298 	struct md_rdev *rdev;
5299 	sector_t reshape_offset = 0;
5300 	int i;
5301 	long long min_offset_diff = 0;
5302 	int first = 1;
5303 
5304 	if (mddev->recovery_cp != MaxSector)
5305 		printk(KERN_NOTICE "md/raid:%s: not clean"
5306 		       " -- starting background reconstruction\n",
5307 		       mdname(mddev));
5308 
5309 	rdev_for_each(rdev, mddev) {
5310 		long long diff;
5311 		if (rdev->raid_disk < 0)
5312 			continue;
5313 		diff = (rdev->new_data_offset - rdev->data_offset);
5314 		if (first) {
5315 			min_offset_diff = diff;
5316 			first = 0;
5317 		} else if (mddev->reshape_backwards &&
5318 			 diff < min_offset_diff)
5319 			min_offset_diff = diff;
5320 		else if (!mddev->reshape_backwards &&
5321 			 diff > min_offset_diff)
5322 			min_offset_diff = diff;
5323 	}
5324 
5325 	if (mddev->reshape_position != MaxSector) {
5326 		/* Check that we can continue the reshape.
5327 		 * Difficulties arise if the stripe we would write to
5328 		 * next is at or after the stripe we would read from next.
5329 		 * For a reshape that changes the number of devices, this
5330 		 * is only possible for a very short time, and mdadm makes
5331 		 * sure that time appears to have past before assembling
5332 		 * the array.  So we fail if that time hasn't passed.
5333 		 * For a reshape that keeps the number of devices the same
5334 		 * mdadm must be monitoring the reshape can keeping the
5335 		 * critical areas read-only and backed up.  It will start
5336 		 * the array in read-only mode, so we check for that.
5337 		 */
5338 		sector_t here_new, here_old;
5339 		int old_disks;
5340 		int max_degraded = (mddev->level == 6 ? 2 : 1);
5341 
5342 		if (mddev->new_level != mddev->level) {
5343 			printk(KERN_ERR "md/raid:%s: unsupported reshape "
5344 			       "required - aborting.\n",
5345 			       mdname(mddev));
5346 			return -EINVAL;
5347 		}
5348 		old_disks = mddev->raid_disks - mddev->delta_disks;
5349 		/* reshape_position must be on a new-stripe boundary, and one
5350 		 * further up in new geometry must map after here in old
5351 		 * geometry.
5352 		 */
5353 		here_new = mddev->reshape_position;
5354 		if (sector_div(here_new, mddev->new_chunk_sectors *
5355 			       (mddev->raid_disks - max_degraded))) {
5356 			printk(KERN_ERR "md/raid:%s: reshape_position not "
5357 			       "on a stripe boundary\n", mdname(mddev));
5358 			return -EINVAL;
5359 		}
5360 		reshape_offset = here_new * mddev->new_chunk_sectors;
5361 		/* here_new is the stripe we will write to */
5362 		here_old = mddev->reshape_position;
5363 		sector_div(here_old, mddev->chunk_sectors *
5364 			   (old_disks-max_degraded));
5365 		/* here_old is the first stripe that we might need to read
5366 		 * from */
5367 		if (mddev->delta_disks == 0) {
5368 			if ((here_new * mddev->new_chunk_sectors !=
5369 			     here_old * mddev->chunk_sectors)) {
5370 				printk(KERN_ERR "md/raid:%s: reshape position is"
5371 				       " confused - aborting\n", mdname(mddev));
5372 				return -EINVAL;
5373 			}
5374 			/* We cannot be sure it is safe to start an in-place
5375 			 * reshape.  It is only safe if user-space is monitoring
5376 			 * and taking constant backups.
5377 			 * mdadm always starts a situation like this in
5378 			 * readonly mode so it can take control before
5379 			 * allowing any writes.  So just check for that.
5380 			 */
5381 			if (abs(min_offset_diff) >= mddev->chunk_sectors &&
5382 			    abs(min_offset_diff) >= mddev->new_chunk_sectors)
5383 				/* not really in-place - so OK */;
5384 			else if (mddev->ro == 0) {
5385 				printk(KERN_ERR "md/raid:%s: in-place reshape "
5386 				       "must be started in read-only mode "
5387 				       "- aborting\n",
5388 				       mdname(mddev));
5389 				return -EINVAL;
5390 			}
5391 		} else if (mddev->reshape_backwards
5392 		    ? (here_new * mddev->new_chunk_sectors + min_offset_diff <=
5393 		       here_old * mddev->chunk_sectors)
5394 		    : (here_new * mddev->new_chunk_sectors >=
5395 		       here_old * mddev->chunk_sectors + (-min_offset_diff))) {
5396 			/* Reading from the same stripe as writing to - bad */
5397 			printk(KERN_ERR "md/raid:%s: reshape_position too early for "
5398 			       "auto-recovery - aborting.\n",
5399 			       mdname(mddev));
5400 			return -EINVAL;
5401 		}
5402 		printk(KERN_INFO "md/raid:%s: reshape will continue\n",
5403 		       mdname(mddev));
5404 		/* OK, we should be able to continue; */
5405 	} else {
5406 		BUG_ON(mddev->level != mddev->new_level);
5407 		BUG_ON(mddev->layout != mddev->new_layout);
5408 		BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
5409 		BUG_ON(mddev->delta_disks != 0);
5410 	}
5411 
5412 	if (mddev->private == NULL)
5413 		conf = setup_conf(mddev);
5414 	else
5415 		conf = mddev->private;
5416 
5417 	if (IS_ERR(conf))
5418 		return PTR_ERR(conf);
5419 
5420 	conf->min_offset_diff = min_offset_diff;
5421 	mddev->thread = conf->thread;
5422 	conf->thread = NULL;
5423 	mddev->private = conf;
5424 
5425 	for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
5426 	     i++) {
5427 		rdev = conf->disks[i].rdev;
5428 		if (!rdev && conf->disks[i].replacement) {
5429 			/* The replacement is all we have yet */
5430 			rdev = conf->disks[i].replacement;
5431 			conf->disks[i].replacement = NULL;
5432 			clear_bit(Replacement, &rdev->flags);
5433 			conf->disks[i].rdev = rdev;
5434 		}
5435 		if (!rdev)
5436 			continue;
5437 		if (conf->disks[i].replacement &&
5438 		    conf->reshape_progress != MaxSector) {
5439 			/* replacements and reshape simply do not mix. */
5440 			printk(KERN_ERR "md: cannot handle concurrent "
5441 			       "replacement and reshape.\n");
5442 			goto abort;
5443 		}
5444 		if (test_bit(In_sync, &rdev->flags)) {
5445 			working_disks++;
5446 			continue;
5447 		}
5448 		/* This disc is not fully in-sync.  However if it
5449 		 * just stored parity (beyond the recovery_offset),
5450 		 * when we don't need to be concerned about the
5451 		 * array being dirty.
5452 		 * When reshape goes 'backwards', we never have
5453 		 * partially completed devices, so we only need
5454 		 * to worry about reshape going forwards.
5455 		 */
5456 		/* Hack because v0.91 doesn't store recovery_offset properly. */
5457 		if (mddev->major_version == 0 &&
5458 		    mddev->minor_version > 90)
5459 			rdev->recovery_offset = reshape_offset;
5460 
5461 		if (rdev->recovery_offset < reshape_offset) {
5462 			/* We need to check old and new layout */
5463 			if (!only_parity(rdev->raid_disk,
5464 					 conf->algorithm,
5465 					 conf->raid_disks,
5466 					 conf->max_degraded))
5467 				continue;
5468 		}
5469 		if (!only_parity(rdev->raid_disk,
5470 				 conf->prev_algo,
5471 				 conf->previous_raid_disks,
5472 				 conf->max_degraded))
5473 			continue;
5474 		dirty_parity_disks++;
5475 	}
5476 
5477 	/*
5478 	 * 0 for a fully functional array, 1 or 2 for a degraded array.
5479 	 */
5480 	mddev->degraded = calc_degraded(conf);
5481 
5482 	if (has_failed(conf)) {
5483 		printk(KERN_ERR "md/raid:%s: not enough operational devices"
5484 			" (%d/%d failed)\n",
5485 			mdname(mddev), mddev->degraded, conf->raid_disks);
5486 		goto abort;
5487 	}
5488 
5489 	/* device size must be a multiple of chunk size */
5490 	mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
5491 	mddev->resync_max_sectors = mddev->dev_sectors;
5492 
5493 	if (mddev->degraded > dirty_parity_disks &&
5494 	    mddev->recovery_cp != MaxSector) {
5495 		if (mddev->ok_start_degraded)
5496 			printk(KERN_WARNING
5497 			       "md/raid:%s: starting dirty degraded array"
5498 			       " - data corruption possible.\n",
5499 			       mdname(mddev));
5500 		else {
5501 			printk(KERN_ERR
5502 			       "md/raid:%s: cannot start dirty degraded array.\n",
5503 			       mdname(mddev));
5504 			goto abort;
5505 		}
5506 	}
5507 
5508 	if (mddev->degraded == 0)
5509 		printk(KERN_INFO "md/raid:%s: raid level %d active with %d out of %d"
5510 		       " devices, algorithm %d\n", mdname(mddev), conf->level,
5511 		       mddev->raid_disks-mddev->degraded, mddev->raid_disks,
5512 		       mddev->new_layout);
5513 	else
5514 		printk(KERN_ALERT "md/raid:%s: raid level %d active with %d"
5515 		       " out of %d devices, algorithm %d\n",
5516 		       mdname(mddev), conf->level,
5517 		       mddev->raid_disks - mddev->degraded,
5518 		       mddev->raid_disks, mddev->new_layout);
5519 
5520 	print_raid5_conf(conf);
5521 
5522 	if (conf->reshape_progress != MaxSector) {
5523 		conf->reshape_safe = conf->reshape_progress;
5524 		atomic_set(&conf->reshape_stripes, 0);
5525 		clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
5526 		clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
5527 		set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
5528 		set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
5529 		mddev->sync_thread = md_register_thread(md_do_sync, mddev,
5530 							"reshape");
5531 	}
5532 
5533 
5534 	/* Ok, everything is just fine now */
5535 	if (mddev->to_remove == &raid5_attrs_group)
5536 		mddev->to_remove = NULL;
5537 	else if (mddev->kobj.sd &&
5538 	    sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
5539 		printk(KERN_WARNING
5540 		       "raid5: failed to create sysfs attributes for %s\n",
5541 		       mdname(mddev));
5542 	md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
5543 
5544 	if (mddev->queue) {
5545 		int chunk_size;
5546 		bool discard_supported = true;
5547 		/* read-ahead size must cover two whole stripes, which
5548 		 * is 2 * (datadisks) * chunksize where 'n' is the
5549 		 * number of raid devices
5550 		 */
5551 		int data_disks = conf->previous_raid_disks - conf->max_degraded;
5552 		int stripe = data_disks *
5553 			((mddev->chunk_sectors << 9) / PAGE_SIZE);
5554 		if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
5555 			mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
5556 
5557 		blk_queue_merge_bvec(mddev->queue, raid5_mergeable_bvec);
5558 
5559 		mddev->queue->backing_dev_info.congested_data = mddev;
5560 		mddev->queue->backing_dev_info.congested_fn = raid5_congested;
5561 
5562 		chunk_size = mddev->chunk_sectors << 9;
5563 		blk_queue_io_min(mddev->queue, chunk_size);
5564 		blk_queue_io_opt(mddev->queue, chunk_size *
5565 				 (conf->raid_disks - conf->max_degraded));
5566 		/*
5567 		 * We can only discard a whole stripe. It doesn't make sense to
5568 		 * discard data disk but write parity disk
5569 		 */
5570 		stripe = stripe * PAGE_SIZE;
5571 		/* Round up to power of 2, as discard handling
5572 		 * currently assumes that */
5573 		while ((stripe-1) & stripe)
5574 			stripe = (stripe | (stripe-1)) + 1;
5575 		mddev->queue->limits.discard_alignment = stripe;
5576 		mddev->queue->limits.discard_granularity = stripe;
5577 		/*
5578 		 * unaligned part of discard request will be ignored, so can't
5579 		 * guarantee discard_zerors_data
5580 		 */
5581 		mddev->queue->limits.discard_zeroes_data = 0;
5582 
5583 		rdev_for_each(rdev, mddev) {
5584 			disk_stack_limits(mddev->gendisk, rdev->bdev,
5585 					  rdev->data_offset << 9);
5586 			disk_stack_limits(mddev->gendisk, rdev->bdev,
5587 					  rdev->new_data_offset << 9);
5588 			/*
5589 			 * discard_zeroes_data is required, otherwise data
5590 			 * could be lost. Consider a scenario: discard a stripe
5591 			 * (the stripe could be inconsistent if
5592 			 * discard_zeroes_data is 0); write one disk of the
5593 			 * stripe (the stripe could be inconsistent again
5594 			 * depending on which disks are used to calculate
5595 			 * parity); the disk is broken; The stripe data of this
5596 			 * disk is lost.
5597 			 */
5598 			if (!blk_queue_discard(bdev_get_queue(rdev->bdev)) ||
5599 			    !bdev_get_queue(rdev->bdev)->
5600 						limits.discard_zeroes_data)
5601 				discard_supported = false;
5602 		}
5603 
5604 		if (discard_supported &&
5605 		   mddev->queue->limits.max_discard_sectors >= stripe &&
5606 		   mddev->queue->limits.discard_granularity >= stripe)
5607 			queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
5608 						mddev->queue);
5609 		else
5610 			queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
5611 						mddev->queue);
5612 	}
5613 
5614 	return 0;
5615 abort:
5616 	md_unregister_thread(&mddev->thread);
5617 	print_raid5_conf(conf);
5618 	free_conf(conf);
5619 	mddev->private = NULL;
5620 	printk(KERN_ALERT "md/raid:%s: failed to run raid set.\n", mdname(mddev));
5621 	return -EIO;
5622 }
5623 
5624 static int stop(struct mddev *mddev)
5625 {
5626 	struct r5conf *conf = mddev->private;
5627 
5628 	md_unregister_thread(&mddev->thread);
5629 	if (mddev->queue)
5630 		mddev->queue->backing_dev_info.congested_fn = NULL;
5631 	free_conf(conf);
5632 	mddev->private = NULL;
5633 	mddev->to_remove = &raid5_attrs_group;
5634 	return 0;
5635 }
5636 
5637 static void status(struct seq_file *seq, struct mddev *mddev)
5638 {
5639 	struct r5conf *conf = mddev->private;
5640 	int i;
5641 
5642 	seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
5643 		mddev->chunk_sectors / 2, mddev->layout);
5644 	seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
5645 	for (i = 0; i < conf->raid_disks; i++)
5646 		seq_printf (seq, "%s",
5647 			       conf->disks[i].rdev &&
5648 			       test_bit(In_sync, &conf->disks[i].rdev->flags) ? "U" : "_");
5649 	seq_printf (seq, "]");
5650 }
5651 
5652 static void print_raid5_conf (struct r5conf *conf)
5653 {
5654 	int i;
5655 	struct disk_info *tmp;
5656 
5657 	printk(KERN_DEBUG "RAID conf printout:\n");
5658 	if (!conf) {
5659 		printk("(conf==NULL)\n");
5660 		return;
5661 	}
5662 	printk(KERN_DEBUG " --- level:%d rd:%d wd:%d\n", conf->level,
5663 	       conf->raid_disks,
5664 	       conf->raid_disks - conf->mddev->degraded);
5665 
5666 	for (i = 0; i < conf->raid_disks; i++) {
5667 		char b[BDEVNAME_SIZE];
5668 		tmp = conf->disks + i;
5669 		if (tmp->rdev)
5670 			printk(KERN_DEBUG " disk %d, o:%d, dev:%s\n",
5671 			       i, !test_bit(Faulty, &tmp->rdev->flags),
5672 			       bdevname(tmp->rdev->bdev, b));
5673 	}
5674 }
5675 
5676 static int raid5_spare_active(struct mddev *mddev)
5677 {
5678 	int i;
5679 	struct r5conf *conf = mddev->private;
5680 	struct disk_info *tmp;
5681 	int count = 0;
5682 	unsigned long flags;
5683 
5684 	for (i = 0; i < conf->raid_disks; i++) {
5685 		tmp = conf->disks + i;
5686 		if (tmp->replacement
5687 		    && tmp->replacement->recovery_offset == MaxSector
5688 		    && !test_bit(Faulty, &tmp->replacement->flags)
5689 		    && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
5690 			/* Replacement has just become active. */
5691 			if (!tmp->rdev
5692 			    || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
5693 				count++;
5694 			if (tmp->rdev) {
5695 				/* Replaced device not technically faulty,
5696 				 * but we need to be sure it gets removed
5697 				 * and never re-added.
5698 				 */
5699 				set_bit(Faulty, &tmp->rdev->flags);
5700 				sysfs_notify_dirent_safe(
5701 					tmp->rdev->sysfs_state);
5702 			}
5703 			sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
5704 		} else if (tmp->rdev
5705 		    && tmp->rdev->recovery_offset == MaxSector
5706 		    && !test_bit(Faulty, &tmp->rdev->flags)
5707 		    && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
5708 			count++;
5709 			sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
5710 		}
5711 	}
5712 	spin_lock_irqsave(&conf->device_lock, flags);
5713 	mddev->degraded = calc_degraded(conf);
5714 	spin_unlock_irqrestore(&conf->device_lock, flags);
5715 	print_raid5_conf(conf);
5716 	return count;
5717 }
5718 
5719 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
5720 {
5721 	struct r5conf *conf = mddev->private;
5722 	int err = 0;
5723 	int number = rdev->raid_disk;
5724 	struct md_rdev **rdevp;
5725 	struct disk_info *p = conf->disks + number;
5726 
5727 	print_raid5_conf(conf);
5728 	if (rdev == p->rdev)
5729 		rdevp = &p->rdev;
5730 	else if (rdev == p->replacement)
5731 		rdevp = &p->replacement;
5732 	else
5733 		return 0;
5734 
5735 	if (number >= conf->raid_disks &&
5736 	    conf->reshape_progress == MaxSector)
5737 		clear_bit(In_sync, &rdev->flags);
5738 
5739 	if (test_bit(In_sync, &rdev->flags) ||
5740 	    atomic_read(&rdev->nr_pending)) {
5741 		err = -EBUSY;
5742 		goto abort;
5743 	}
5744 	/* Only remove non-faulty devices if recovery
5745 	 * isn't possible.
5746 	 */
5747 	if (!test_bit(Faulty, &rdev->flags) &&
5748 	    mddev->recovery_disabled != conf->recovery_disabled &&
5749 	    !has_failed(conf) &&
5750 	    (!p->replacement || p->replacement == rdev) &&
5751 	    number < conf->raid_disks) {
5752 		err = -EBUSY;
5753 		goto abort;
5754 	}
5755 	*rdevp = NULL;
5756 	synchronize_rcu();
5757 	if (atomic_read(&rdev->nr_pending)) {
5758 		/* lost the race, try later */
5759 		err = -EBUSY;
5760 		*rdevp = rdev;
5761 	} else if (p->replacement) {
5762 		/* We must have just cleared 'rdev' */
5763 		p->rdev = p->replacement;
5764 		clear_bit(Replacement, &p->replacement->flags);
5765 		smp_mb(); /* Make sure other CPUs may see both as identical
5766 			   * but will never see neither - if they are careful
5767 			   */
5768 		p->replacement = NULL;
5769 		clear_bit(WantReplacement, &rdev->flags);
5770 	} else
5771 		/* We might have just removed the Replacement as faulty-
5772 		 * clear the bit just in case
5773 		 */
5774 		clear_bit(WantReplacement, &rdev->flags);
5775 abort:
5776 
5777 	print_raid5_conf(conf);
5778 	return err;
5779 }
5780 
5781 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
5782 {
5783 	struct r5conf *conf = mddev->private;
5784 	int err = -EEXIST;
5785 	int disk;
5786 	struct disk_info *p;
5787 	int first = 0;
5788 	int last = conf->raid_disks - 1;
5789 
5790 	if (mddev->recovery_disabled == conf->recovery_disabled)
5791 		return -EBUSY;
5792 
5793 	if (rdev->saved_raid_disk < 0 && has_failed(conf))
5794 		/* no point adding a device */
5795 		return -EINVAL;
5796 
5797 	if (rdev->raid_disk >= 0)
5798 		first = last = rdev->raid_disk;
5799 
5800 	/*
5801 	 * find the disk ... but prefer rdev->saved_raid_disk
5802 	 * if possible.
5803 	 */
5804 	if (rdev->saved_raid_disk >= 0 &&
5805 	    rdev->saved_raid_disk >= first &&
5806 	    conf->disks[rdev->saved_raid_disk].rdev == NULL)
5807 		first = rdev->saved_raid_disk;
5808 
5809 	for (disk = first; disk <= last; disk++) {
5810 		p = conf->disks + disk;
5811 		if (p->rdev == NULL) {
5812 			clear_bit(In_sync, &rdev->flags);
5813 			rdev->raid_disk = disk;
5814 			err = 0;
5815 			if (rdev->saved_raid_disk != disk)
5816 				conf->fullsync = 1;
5817 			rcu_assign_pointer(p->rdev, rdev);
5818 			goto out;
5819 		}
5820 	}
5821 	for (disk = first; disk <= last; disk++) {
5822 		p = conf->disks + disk;
5823 		if (test_bit(WantReplacement, &p->rdev->flags) &&
5824 		    p->replacement == NULL) {
5825 			clear_bit(In_sync, &rdev->flags);
5826 			set_bit(Replacement, &rdev->flags);
5827 			rdev->raid_disk = disk;
5828 			err = 0;
5829 			conf->fullsync = 1;
5830 			rcu_assign_pointer(p->replacement, rdev);
5831 			break;
5832 		}
5833 	}
5834 out:
5835 	print_raid5_conf(conf);
5836 	return err;
5837 }
5838 
5839 static int raid5_resize(struct mddev *mddev, sector_t sectors)
5840 {
5841 	/* no resync is happening, and there is enough space
5842 	 * on all devices, so we can resize.
5843 	 * We need to make sure resync covers any new space.
5844 	 * If the array is shrinking we should possibly wait until
5845 	 * any io in the removed space completes, but it hardly seems
5846 	 * worth it.
5847 	 */
5848 	sector_t newsize;
5849 	sectors &= ~((sector_t)mddev->chunk_sectors - 1);
5850 	newsize = raid5_size(mddev, sectors, mddev->raid_disks);
5851 	if (mddev->external_size &&
5852 	    mddev->array_sectors > newsize)
5853 		return -EINVAL;
5854 	if (mddev->bitmap) {
5855 		int ret = bitmap_resize(mddev->bitmap, sectors, 0, 0);
5856 		if (ret)
5857 			return ret;
5858 	}
5859 	md_set_array_sectors(mddev, newsize);
5860 	set_capacity(mddev->gendisk, mddev->array_sectors);
5861 	revalidate_disk(mddev->gendisk);
5862 	if (sectors > mddev->dev_sectors &&
5863 	    mddev->recovery_cp > mddev->dev_sectors) {
5864 		mddev->recovery_cp = mddev->dev_sectors;
5865 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5866 	}
5867 	mddev->dev_sectors = sectors;
5868 	mddev->resync_max_sectors = sectors;
5869 	return 0;
5870 }
5871 
5872 static int check_stripe_cache(struct mddev *mddev)
5873 {
5874 	/* Can only proceed if there are plenty of stripe_heads.
5875 	 * We need a minimum of one full stripe,, and for sensible progress
5876 	 * it is best to have about 4 times that.
5877 	 * If we require 4 times, then the default 256 4K stripe_heads will
5878 	 * allow for chunk sizes up to 256K, which is probably OK.
5879 	 * If the chunk size is greater, user-space should request more
5880 	 * stripe_heads first.
5881 	 */
5882 	struct r5conf *conf = mddev->private;
5883 	if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
5884 	    > conf->max_nr_stripes ||
5885 	    ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
5886 	    > conf->max_nr_stripes) {
5887 		printk(KERN_WARNING "md/raid:%s: reshape: not enough stripes.  Needed %lu\n",
5888 		       mdname(mddev),
5889 		       ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
5890 			/ STRIPE_SIZE)*4);
5891 		return 0;
5892 	}
5893 	return 1;
5894 }
5895 
5896 static int check_reshape(struct mddev *mddev)
5897 {
5898 	struct r5conf *conf = mddev->private;
5899 
5900 	if (mddev->delta_disks == 0 &&
5901 	    mddev->new_layout == mddev->layout &&
5902 	    mddev->new_chunk_sectors == mddev->chunk_sectors)
5903 		return 0; /* nothing to do */
5904 	if (has_failed(conf))
5905 		return -EINVAL;
5906 	if (mddev->delta_disks < 0) {
5907 		/* We might be able to shrink, but the devices must
5908 		 * be made bigger first.
5909 		 * For raid6, 4 is the minimum size.
5910 		 * Otherwise 2 is the minimum
5911 		 */
5912 		int min = 2;
5913 		if (mddev->level == 6)
5914 			min = 4;
5915 		if (mddev->raid_disks + mddev->delta_disks < min)
5916 			return -EINVAL;
5917 	}
5918 
5919 	if (!check_stripe_cache(mddev))
5920 		return -ENOSPC;
5921 
5922 	return resize_stripes(conf, (conf->previous_raid_disks
5923 				     + mddev->delta_disks));
5924 }
5925 
5926 static int raid5_start_reshape(struct mddev *mddev)
5927 {
5928 	struct r5conf *conf = mddev->private;
5929 	struct md_rdev *rdev;
5930 	int spares = 0;
5931 	unsigned long flags;
5932 
5933 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5934 		return -EBUSY;
5935 
5936 	if (!check_stripe_cache(mddev))
5937 		return -ENOSPC;
5938 
5939 	if (has_failed(conf))
5940 		return -EINVAL;
5941 
5942 	rdev_for_each(rdev, mddev) {
5943 		if (!test_bit(In_sync, &rdev->flags)
5944 		    && !test_bit(Faulty, &rdev->flags))
5945 			spares++;
5946 	}
5947 
5948 	if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
5949 		/* Not enough devices even to make a degraded array
5950 		 * of that size
5951 		 */
5952 		return -EINVAL;
5953 
5954 	/* Refuse to reduce size of the array.  Any reductions in
5955 	 * array size must be through explicit setting of array_size
5956 	 * attribute.
5957 	 */
5958 	if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
5959 	    < mddev->array_sectors) {
5960 		printk(KERN_ERR "md/raid:%s: array size must be reduced "
5961 		       "before number of disks\n", mdname(mddev));
5962 		return -EINVAL;
5963 	}
5964 
5965 	atomic_set(&conf->reshape_stripes, 0);
5966 	spin_lock_irq(&conf->device_lock);
5967 	conf->previous_raid_disks = conf->raid_disks;
5968 	conf->raid_disks += mddev->delta_disks;
5969 	conf->prev_chunk_sectors = conf->chunk_sectors;
5970 	conf->chunk_sectors = mddev->new_chunk_sectors;
5971 	conf->prev_algo = conf->algorithm;
5972 	conf->algorithm = mddev->new_layout;
5973 	conf->generation++;
5974 	/* Code that selects data_offset needs to see the generation update
5975 	 * if reshape_progress has been set - so a memory barrier needed.
5976 	 */
5977 	smp_mb();
5978 	if (mddev->reshape_backwards)
5979 		conf->reshape_progress = raid5_size(mddev, 0, 0);
5980 	else
5981 		conf->reshape_progress = 0;
5982 	conf->reshape_safe = conf->reshape_progress;
5983 	spin_unlock_irq(&conf->device_lock);
5984 
5985 	/* Add some new drives, as many as will fit.
5986 	 * We know there are enough to make the newly sized array work.
5987 	 * Don't add devices if we are reducing the number of
5988 	 * devices in the array.  This is because it is not possible
5989 	 * to correctly record the "partially reconstructed" state of
5990 	 * such devices during the reshape and confusion could result.
5991 	 */
5992 	if (mddev->delta_disks >= 0) {
5993 		rdev_for_each(rdev, mddev)
5994 			if (rdev->raid_disk < 0 &&
5995 			    !test_bit(Faulty, &rdev->flags)) {
5996 				if (raid5_add_disk(mddev, rdev) == 0) {
5997 					if (rdev->raid_disk
5998 					    >= conf->previous_raid_disks)
5999 						set_bit(In_sync, &rdev->flags);
6000 					else
6001 						rdev->recovery_offset = 0;
6002 
6003 					if (sysfs_link_rdev(mddev, rdev))
6004 						/* Failure here is OK */;
6005 				}
6006 			} else if (rdev->raid_disk >= conf->previous_raid_disks
6007 				   && !test_bit(Faulty, &rdev->flags)) {
6008 				/* This is a spare that was manually added */
6009 				set_bit(In_sync, &rdev->flags);
6010 			}
6011 
6012 		/* When a reshape changes the number of devices,
6013 		 * ->degraded is measured against the larger of the
6014 		 * pre and post number of devices.
6015 		 */
6016 		spin_lock_irqsave(&conf->device_lock, flags);
6017 		mddev->degraded = calc_degraded(conf);
6018 		spin_unlock_irqrestore(&conf->device_lock, flags);
6019 	}
6020 	mddev->raid_disks = conf->raid_disks;
6021 	mddev->reshape_position = conf->reshape_progress;
6022 	set_bit(MD_CHANGE_DEVS, &mddev->flags);
6023 
6024 	clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
6025 	clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
6026 	set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
6027 	set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
6028 	mddev->sync_thread = md_register_thread(md_do_sync, mddev,
6029 						"reshape");
6030 	if (!mddev->sync_thread) {
6031 		mddev->recovery = 0;
6032 		spin_lock_irq(&conf->device_lock);
6033 		mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
6034 		rdev_for_each(rdev, mddev)
6035 			rdev->new_data_offset = rdev->data_offset;
6036 		smp_wmb();
6037 		conf->reshape_progress = MaxSector;
6038 		mddev->reshape_position = MaxSector;
6039 		spin_unlock_irq(&conf->device_lock);
6040 		return -EAGAIN;
6041 	}
6042 	conf->reshape_checkpoint = jiffies;
6043 	md_wakeup_thread(mddev->sync_thread);
6044 	md_new_event(mddev);
6045 	return 0;
6046 }
6047 
6048 /* This is called from the reshape thread and should make any
6049  * changes needed in 'conf'
6050  */
6051 static void end_reshape(struct r5conf *conf)
6052 {
6053 
6054 	if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
6055 		struct md_rdev *rdev;
6056 
6057 		spin_lock_irq(&conf->device_lock);
6058 		conf->previous_raid_disks = conf->raid_disks;
6059 		rdev_for_each(rdev, conf->mddev)
6060 			rdev->data_offset = rdev->new_data_offset;
6061 		smp_wmb();
6062 		conf->reshape_progress = MaxSector;
6063 		spin_unlock_irq(&conf->device_lock);
6064 		wake_up(&conf->wait_for_overlap);
6065 
6066 		/* read-ahead size must cover two whole stripes, which is
6067 		 * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
6068 		 */
6069 		if (conf->mddev->queue) {
6070 			int data_disks = conf->raid_disks - conf->max_degraded;
6071 			int stripe = data_disks * ((conf->chunk_sectors << 9)
6072 						   / PAGE_SIZE);
6073 			if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
6074 				conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
6075 		}
6076 	}
6077 }
6078 
6079 /* This is called from the raid5d thread with mddev_lock held.
6080  * It makes config changes to the device.
6081  */
6082 static void raid5_finish_reshape(struct mddev *mddev)
6083 {
6084 	struct r5conf *conf = mddev->private;
6085 
6086 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
6087 
6088 		if (mddev->delta_disks > 0) {
6089 			md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
6090 			set_capacity(mddev->gendisk, mddev->array_sectors);
6091 			revalidate_disk(mddev->gendisk);
6092 		} else {
6093 			int d;
6094 			spin_lock_irq(&conf->device_lock);
6095 			mddev->degraded = calc_degraded(conf);
6096 			spin_unlock_irq(&conf->device_lock);
6097 			for (d = conf->raid_disks ;
6098 			     d < conf->raid_disks - mddev->delta_disks;
6099 			     d++) {
6100 				struct md_rdev *rdev = conf->disks[d].rdev;
6101 				if (rdev)
6102 					clear_bit(In_sync, &rdev->flags);
6103 				rdev = conf->disks[d].replacement;
6104 				if (rdev)
6105 					clear_bit(In_sync, &rdev->flags);
6106 			}
6107 		}
6108 		mddev->layout = conf->algorithm;
6109 		mddev->chunk_sectors = conf->chunk_sectors;
6110 		mddev->reshape_position = MaxSector;
6111 		mddev->delta_disks = 0;
6112 		mddev->reshape_backwards = 0;
6113 	}
6114 }
6115 
6116 static void raid5_quiesce(struct mddev *mddev, int state)
6117 {
6118 	struct r5conf *conf = mddev->private;
6119 
6120 	switch(state) {
6121 	case 2: /* resume for a suspend */
6122 		wake_up(&conf->wait_for_overlap);
6123 		break;
6124 
6125 	case 1: /* stop all writes */
6126 		spin_lock_irq(&conf->device_lock);
6127 		/* '2' tells resync/reshape to pause so that all
6128 		 * active stripes can drain
6129 		 */
6130 		conf->quiesce = 2;
6131 		wait_event_lock_irq(conf->wait_for_stripe,
6132 				    atomic_read(&conf->active_stripes) == 0 &&
6133 				    atomic_read(&conf->active_aligned_reads) == 0,
6134 				    conf->device_lock);
6135 		conf->quiesce = 1;
6136 		spin_unlock_irq(&conf->device_lock);
6137 		/* allow reshape to continue */
6138 		wake_up(&conf->wait_for_overlap);
6139 		break;
6140 
6141 	case 0: /* re-enable writes */
6142 		spin_lock_irq(&conf->device_lock);
6143 		conf->quiesce = 0;
6144 		wake_up(&conf->wait_for_stripe);
6145 		wake_up(&conf->wait_for_overlap);
6146 		spin_unlock_irq(&conf->device_lock);
6147 		break;
6148 	}
6149 }
6150 
6151 
6152 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
6153 {
6154 	struct r0conf *raid0_conf = mddev->private;
6155 	sector_t sectors;
6156 
6157 	/* for raid0 takeover only one zone is supported */
6158 	if (raid0_conf->nr_strip_zones > 1) {
6159 		printk(KERN_ERR "md/raid:%s: cannot takeover raid0 with more than one zone.\n",
6160 		       mdname(mddev));
6161 		return ERR_PTR(-EINVAL);
6162 	}
6163 
6164 	sectors = raid0_conf->strip_zone[0].zone_end;
6165 	sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
6166 	mddev->dev_sectors = sectors;
6167 	mddev->new_level = level;
6168 	mddev->new_layout = ALGORITHM_PARITY_N;
6169 	mddev->new_chunk_sectors = mddev->chunk_sectors;
6170 	mddev->raid_disks += 1;
6171 	mddev->delta_disks = 1;
6172 	/* make sure it will be not marked as dirty */
6173 	mddev->recovery_cp = MaxSector;
6174 
6175 	return setup_conf(mddev);
6176 }
6177 
6178 
6179 static void *raid5_takeover_raid1(struct mddev *mddev)
6180 {
6181 	int chunksect;
6182 
6183 	if (mddev->raid_disks != 2 ||
6184 	    mddev->degraded > 1)
6185 		return ERR_PTR(-EINVAL);
6186 
6187 	/* Should check if there are write-behind devices? */
6188 
6189 	chunksect = 64*2; /* 64K by default */
6190 
6191 	/* The array must be an exact multiple of chunksize */
6192 	while (chunksect && (mddev->array_sectors & (chunksect-1)))
6193 		chunksect >>= 1;
6194 
6195 	if ((chunksect<<9) < STRIPE_SIZE)
6196 		/* array size does not allow a suitable chunk size */
6197 		return ERR_PTR(-EINVAL);
6198 
6199 	mddev->new_level = 5;
6200 	mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
6201 	mddev->new_chunk_sectors = chunksect;
6202 
6203 	return setup_conf(mddev);
6204 }
6205 
6206 static void *raid5_takeover_raid6(struct mddev *mddev)
6207 {
6208 	int new_layout;
6209 
6210 	switch (mddev->layout) {
6211 	case ALGORITHM_LEFT_ASYMMETRIC_6:
6212 		new_layout = ALGORITHM_LEFT_ASYMMETRIC;
6213 		break;
6214 	case ALGORITHM_RIGHT_ASYMMETRIC_6:
6215 		new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
6216 		break;
6217 	case ALGORITHM_LEFT_SYMMETRIC_6:
6218 		new_layout = ALGORITHM_LEFT_SYMMETRIC;
6219 		break;
6220 	case ALGORITHM_RIGHT_SYMMETRIC_6:
6221 		new_layout = ALGORITHM_RIGHT_SYMMETRIC;
6222 		break;
6223 	case ALGORITHM_PARITY_0_6:
6224 		new_layout = ALGORITHM_PARITY_0;
6225 		break;
6226 	case ALGORITHM_PARITY_N:
6227 		new_layout = ALGORITHM_PARITY_N;
6228 		break;
6229 	default:
6230 		return ERR_PTR(-EINVAL);
6231 	}
6232 	mddev->new_level = 5;
6233 	mddev->new_layout = new_layout;
6234 	mddev->delta_disks = -1;
6235 	mddev->raid_disks -= 1;
6236 	return setup_conf(mddev);
6237 }
6238 
6239 
6240 static int raid5_check_reshape(struct mddev *mddev)
6241 {
6242 	/* For a 2-drive array, the layout and chunk size can be changed
6243 	 * immediately as not restriping is needed.
6244 	 * For larger arrays we record the new value - after validation
6245 	 * to be used by a reshape pass.
6246 	 */
6247 	struct r5conf *conf = mddev->private;
6248 	int new_chunk = mddev->new_chunk_sectors;
6249 
6250 	if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
6251 		return -EINVAL;
6252 	if (new_chunk > 0) {
6253 		if (!is_power_of_2(new_chunk))
6254 			return -EINVAL;
6255 		if (new_chunk < (PAGE_SIZE>>9))
6256 			return -EINVAL;
6257 		if (mddev->array_sectors & (new_chunk-1))
6258 			/* not factor of array size */
6259 			return -EINVAL;
6260 	}
6261 
6262 	/* They look valid */
6263 
6264 	if (mddev->raid_disks == 2) {
6265 		/* can make the change immediately */
6266 		if (mddev->new_layout >= 0) {
6267 			conf->algorithm = mddev->new_layout;
6268 			mddev->layout = mddev->new_layout;
6269 		}
6270 		if (new_chunk > 0) {
6271 			conf->chunk_sectors = new_chunk ;
6272 			mddev->chunk_sectors = new_chunk;
6273 		}
6274 		set_bit(MD_CHANGE_DEVS, &mddev->flags);
6275 		md_wakeup_thread(mddev->thread);
6276 	}
6277 	return check_reshape(mddev);
6278 }
6279 
6280 static int raid6_check_reshape(struct mddev *mddev)
6281 {
6282 	int new_chunk = mddev->new_chunk_sectors;
6283 
6284 	if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
6285 		return -EINVAL;
6286 	if (new_chunk > 0) {
6287 		if (!is_power_of_2(new_chunk))
6288 			return -EINVAL;
6289 		if (new_chunk < (PAGE_SIZE >> 9))
6290 			return -EINVAL;
6291 		if (mddev->array_sectors & (new_chunk-1))
6292 			/* not factor of array size */
6293 			return -EINVAL;
6294 	}
6295 
6296 	/* They look valid */
6297 	return check_reshape(mddev);
6298 }
6299 
6300 static void *raid5_takeover(struct mddev *mddev)
6301 {
6302 	/* raid5 can take over:
6303 	 *  raid0 - if there is only one strip zone - make it a raid4 layout
6304 	 *  raid1 - if there are two drives.  We need to know the chunk size
6305 	 *  raid4 - trivial - just use a raid4 layout.
6306 	 *  raid6 - Providing it is a *_6 layout
6307 	 */
6308 	if (mddev->level == 0)
6309 		return raid45_takeover_raid0(mddev, 5);
6310 	if (mddev->level == 1)
6311 		return raid5_takeover_raid1(mddev);
6312 	if (mddev->level == 4) {
6313 		mddev->new_layout = ALGORITHM_PARITY_N;
6314 		mddev->new_level = 5;
6315 		return setup_conf(mddev);
6316 	}
6317 	if (mddev->level == 6)
6318 		return raid5_takeover_raid6(mddev);
6319 
6320 	return ERR_PTR(-EINVAL);
6321 }
6322 
6323 static void *raid4_takeover(struct mddev *mddev)
6324 {
6325 	/* raid4 can take over:
6326 	 *  raid0 - if there is only one strip zone
6327 	 *  raid5 - if layout is right
6328 	 */
6329 	if (mddev->level == 0)
6330 		return raid45_takeover_raid0(mddev, 4);
6331 	if (mddev->level == 5 &&
6332 	    mddev->layout == ALGORITHM_PARITY_N) {
6333 		mddev->new_layout = 0;
6334 		mddev->new_level = 4;
6335 		return setup_conf(mddev);
6336 	}
6337 	return ERR_PTR(-EINVAL);
6338 }
6339 
6340 static struct md_personality raid5_personality;
6341 
6342 static void *raid6_takeover(struct mddev *mddev)
6343 {
6344 	/* Currently can only take over a raid5.  We map the
6345 	 * personality to an equivalent raid6 personality
6346 	 * with the Q block at the end.
6347 	 */
6348 	int new_layout;
6349 
6350 	if (mddev->pers != &raid5_personality)
6351 		return ERR_PTR(-EINVAL);
6352 	if (mddev->degraded > 1)
6353 		return ERR_PTR(-EINVAL);
6354 	if (mddev->raid_disks > 253)
6355 		return ERR_PTR(-EINVAL);
6356 	if (mddev->raid_disks < 3)
6357 		return ERR_PTR(-EINVAL);
6358 
6359 	switch (mddev->layout) {
6360 	case ALGORITHM_LEFT_ASYMMETRIC:
6361 		new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
6362 		break;
6363 	case ALGORITHM_RIGHT_ASYMMETRIC:
6364 		new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
6365 		break;
6366 	case ALGORITHM_LEFT_SYMMETRIC:
6367 		new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
6368 		break;
6369 	case ALGORITHM_RIGHT_SYMMETRIC:
6370 		new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
6371 		break;
6372 	case ALGORITHM_PARITY_0:
6373 		new_layout = ALGORITHM_PARITY_0_6;
6374 		break;
6375 	case ALGORITHM_PARITY_N:
6376 		new_layout = ALGORITHM_PARITY_N;
6377 		break;
6378 	default:
6379 		return ERR_PTR(-EINVAL);
6380 	}
6381 	mddev->new_level = 6;
6382 	mddev->new_layout = new_layout;
6383 	mddev->delta_disks = 1;
6384 	mddev->raid_disks += 1;
6385 	return setup_conf(mddev);
6386 }
6387 
6388 
6389 static struct md_personality raid6_personality =
6390 {
6391 	.name		= "raid6",
6392 	.level		= 6,
6393 	.owner		= THIS_MODULE,
6394 	.make_request	= make_request,
6395 	.run		= run,
6396 	.stop		= stop,
6397 	.status		= status,
6398 	.error_handler	= error,
6399 	.hot_add_disk	= raid5_add_disk,
6400 	.hot_remove_disk= raid5_remove_disk,
6401 	.spare_active	= raid5_spare_active,
6402 	.sync_request	= sync_request,
6403 	.resize		= raid5_resize,
6404 	.size		= raid5_size,
6405 	.check_reshape	= raid6_check_reshape,
6406 	.start_reshape  = raid5_start_reshape,
6407 	.finish_reshape = raid5_finish_reshape,
6408 	.quiesce	= raid5_quiesce,
6409 	.takeover	= raid6_takeover,
6410 };
6411 static struct md_personality raid5_personality =
6412 {
6413 	.name		= "raid5",
6414 	.level		= 5,
6415 	.owner		= THIS_MODULE,
6416 	.make_request	= make_request,
6417 	.run		= run,
6418 	.stop		= stop,
6419 	.status		= status,
6420 	.error_handler	= error,
6421 	.hot_add_disk	= raid5_add_disk,
6422 	.hot_remove_disk= raid5_remove_disk,
6423 	.spare_active	= raid5_spare_active,
6424 	.sync_request	= sync_request,
6425 	.resize		= raid5_resize,
6426 	.size		= raid5_size,
6427 	.check_reshape	= raid5_check_reshape,
6428 	.start_reshape  = raid5_start_reshape,
6429 	.finish_reshape = raid5_finish_reshape,
6430 	.quiesce	= raid5_quiesce,
6431 	.takeover	= raid5_takeover,
6432 };
6433 
6434 static struct md_personality raid4_personality =
6435 {
6436 	.name		= "raid4",
6437 	.level		= 4,
6438 	.owner		= THIS_MODULE,
6439 	.make_request	= make_request,
6440 	.run		= run,
6441 	.stop		= stop,
6442 	.status		= status,
6443 	.error_handler	= error,
6444 	.hot_add_disk	= raid5_add_disk,
6445 	.hot_remove_disk= raid5_remove_disk,
6446 	.spare_active	= raid5_spare_active,
6447 	.sync_request	= sync_request,
6448 	.resize		= raid5_resize,
6449 	.size		= raid5_size,
6450 	.check_reshape	= raid5_check_reshape,
6451 	.start_reshape  = raid5_start_reshape,
6452 	.finish_reshape = raid5_finish_reshape,
6453 	.quiesce	= raid5_quiesce,
6454 	.takeover	= raid4_takeover,
6455 };
6456 
6457 static int __init raid5_init(void)
6458 {
6459 	register_md_personality(&raid6_personality);
6460 	register_md_personality(&raid5_personality);
6461 	register_md_personality(&raid4_personality);
6462 	return 0;
6463 }
6464 
6465 static void raid5_exit(void)
6466 {
6467 	unregister_md_personality(&raid6_personality);
6468 	unregister_md_personality(&raid5_personality);
6469 	unregister_md_personality(&raid4_personality);
6470 }
6471 
6472 module_init(raid5_init);
6473 module_exit(raid5_exit);
6474 MODULE_LICENSE("GPL");
6475 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
6476 MODULE_ALIAS("md-personality-4"); /* RAID5 */
6477 MODULE_ALIAS("md-raid5");
6478 MODULE_ALIAS("md-raid4");
6479 MODULE_ALIAS("md-level-5");
6480 MODULE_ALIAS("md-level-4");
6481 MODULE_ALIAS("md-personality-8"); /* RAID6 */
6482 MODULE_ALIAS("md-raid6");
6483 MODULE_ALIAS("md-level-6");
6484 
6485 /* This used to be two separate modules, they were: */
6486 MODULE_ALIAS("raid5");
6487 MODULE_ALIAS("raid6");
6488