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