xref: /openbmc/linux/drivers/md/raid5.c (revision e3211e41)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * raid5.c : Multiple Devices driver for Linux
4  *	   Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
5  *	   Copyright (C) 1999, 2000 Ingo Molnar
6  *	   Copyright (C) 2002, 2003 H. Peter Anvin
7  *
8  * RAID-4/5/6 management functions.
9  * Thanks to Penguin Computing for making the RAID-6 development possible
10  * by donating a test server!
11  */
12 
13 /*
14  * BITMAP UNPLUGGING:
15  *
16  * The sequencing for updating the bitmap reliably is a little
17  * subtle (and I got it wrong the first time) so it deserves some
18  * explanation.
19  *
20  * We group bitmap updates into batches.  Each batch has a number.
21  * We may write out several batches at once, but that isn't very important.
22  * conf->seq_write is the number of the last batch successfully written.
23  * conf->seq_flush is the number of the last batch that was closed to
24  *    new additions.
25  * When we discover that we will need to write to any block in a stripe
26  * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
27  * the number of the batch it will be in. This is seq_flush+1.
28  * When we are ready to do a write, if that batch hasn't been written yet,
29  *   we plug the array and queue the stripe for later.
30  * When an unplug happens, we increment bm_flush, thus closing the current
31  *   batch.
32  * When we notice that bm_flush > bm_write, we write out all pending updates
33  * to the bitmap, and advance bm_write to where bm_flush was.
34  * This may occasionally write a bit out twice, but is sure never to
35  * miss any bits.
36  */
37 
38 #include <linux/blkdev.h>
39 #include <linux/kthread.h>
40 #include <linux/raid/pq.h>
41 #include <linux/async_tx.h>
42 #include <linux/module.h>
43 #include <linux/async.h>
44 #include <linux/seq_file.h>
45 #include <linux/cpu.h>
46 #include <linux/slab.h>
47 #include <linux/ratelimit.h>
48 #include <linux/nodemask.h>
49 
50 #include <trace/events/block.h>
51 #include <linux/list_sort.h>
52 
53 #include "md.h"
54 #include "raid5.h"
55 #include "raid0.h"
56 #include "md-bitmap.h"
57 #include "raid5-log.h"
58 
59 #define UNSUPPORTED_MDDEV_FLAGS	(1L << MD_FAILFAST_SUPPORTED)
60 
61 #define cpu_to_group(cpu) cpu_to_node(cpu)
62 #define ANY_GROUP NUMA_NO_NODE
63 
64 static bool devices_handle_discard_safely = false;
65 module_param(devices_handle_discard_safely, bool, 0644);
66 MODULE_PARM_DESC(devices_handle_discard_safely,
67 		 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
68 static struct workqueue_struct *raid5_wq;
69 
70 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
71 {
72 	int hash = (sect >> RAID5_STRIPE_SHIFT(conf)) & HASH_MASK;
73 	return &conf->stripe_hashtbl[hash];
74 }
75 
76 static inline int stripe_hash_locks_hash(struct r5conf *conf, sector_t sect)
77 {
78 	return (sect >> RAID5_STRIPE_SHIFT(conf)) & STRIPE_HASH_LOCKS_MASK;
79 }
80 
81 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
82 {
83 	spin_lock_irq(conf->hash_locks + hash);
84 	spin_lock(&conf->device_lock);
85 }
86 
87 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
88 {
89 	spin_unlock(&conf->device_lock);
90 	spin_unlock_irq(conf->hash_locks + hash);
91 }
92 
93 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
94 {
95 	int i;
96 	spin_lock_irq(conf->hash_locks);
97 	for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
98 		spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
99 	spin_lock(&conf->device_lock);
100 }
101 
102 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
103 {
104 	int i;
105 	spin_unlock(&conf->device_lock);
106 	for (i = NR_STRIPE_HASH_LOCKS - 1; i; i--)
107 		spin_unlock(conf->hash_locks + i);
108 	spin_unlock_irq(conf->hash_locks);
109 }
110 
111 /* Find first data disk in a raid6 stripe */
112 static inline int raid6_d0(struct stripe_head *sh)
113 {
114 	if (sh->ddf_layout)
115 		/* ddf always start from first device */
116 		return 0;
117 	/* md starts just after Q block */
118 	if (sh->qd_idx == sh->disks - 1)
119 		return 0;
120 	else
121 		return sh->qd_idx + 1;
122 }
123 static inline int raid6_next_disk(int disk, int raid_disks)
124 {
125 	disk++;
126 	return (disk < raid_disks) ? disk : 0;
127 }
128 
129 /* When walking through the disks in a raid5, starting at raid6_d0,
130  * We need to map each disk to a 'slot', where the data disks are slot
131  * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
132  * is raid_disks-1.  This help does that mapping.
133  */
134 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
135 			     int *count, int syndrome_disks)
136 {
137 	int slot = *count;
138 
139 	if (sh->ddf_layout)
140 		(*count)++;
141 	if (idx == sh->pd_idx)
142 		return syndrome_disks;
143 	if (idx == sh->qd_idx)
144 		return syndrome_disks + 1;
145 	if (!sh->ddf_layout)
146 		(*count)++;
147 	return slot;
148 }
149 
150 static void print_raid5_conf (struct r5conf *conf);
151 
152 static int stripe_operations_active(struct stripe_head *sh)
153 {
154 	return sh->check_state || sh->reconstruct_state ||
155 	       test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
156 	       test_bit(STRIPE_COMPUTE_RUN, &sh->state);
157 }
158 
159 static bool stripe_is_lowprio(struct stripe_head *sh)
160 {
161 	return (test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) ||
162 		test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state)) &&
163 	       !test_bit(STRIPE_R5C_CACHING, &sh->state);
164 }
165 
166 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
167 {
168 	struct r5conf *conf = sh->raid_conf;
169 	struct r5worker_group *group;
170 	int thread_cnt;
171 	int i, cpu = sh->cpu;
172 
173 	if (!cpu_online(cpu)) {
174 		cpu = cpumask_any(cpu_online_mask);
175 		sh->cpu = cpu;
176 	}
177 
178 	if (list_empty(&sh->lru)) {
179 		struct r5worker_group *group;
180 		group = conf->worker_groups + cpu_to_group(cpu);
181 		if (stripe_is_lowprio(sh))
182 			list_add_tail(&sh->lru, &group->loprio_list);
183 		else
184 			list_add_tail(&sh->lru, &group->handle_list);
185 		group->stripes_cnt++;
186 		sh->group = group;
187 	}
188 
189 	if (conf->worker_cnt_per_group == 0) {
190 		md_wakeup_thread(conf->mddev->thread);
191 		return;
192 	}
193 
194 	group = conf->worker_groups + cpu_to_group(sh->cpu);
195 
196 	group->workers[0].working = true;
197 	/* at least one worker should run to avoid race */
198 	queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
199 
200 	thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
201 	/* wakeup more workers */
202 	for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
203 		if (group->workers[i].working == false) {
204 			group->workers[i].working = true;
205 			queue_work_on(sh->cpu, raid5_wq,
206 				      &group->workers[i].work);
207 			thread_cnt--;
208 		}
209 	}
210 }
211 
212 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
213 			      struct list_head *temp_inactive_list)
214 {
215 	int i;
216 	int injournal = 0;	/* number of date pages with R5_InJournal */
217 
218 	BUG_ON(!list_empty(&sh->lru));
219 	BUG_ON(atomic_read(&conf->active_stripes)==0);
220 
221 	if (r5c_is_writeback(conf->log))
222 		for (i = sh->disks; i--; )
223 			if (test_bit(R5_InJournal, &sh->dev[i].flags))
224 				injournal++;
225 	/*
226 	 * In the following cases, the stripe cannot be released to cached
227 	 * lists. Therefore, we make the stripe write out and set
228 	 * STRIPE_HANDLE:
229 	 *   1. when quiesce in r5c write back;
230 	 *   2. when resync is requested fot the stripe.
231 	 */
232 	if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) ||
233 	    (conf->quiesce && r5c_is_writeback(conf->log) &&
234 	     !test_bit(STRIPE_HANDLE, &sh->state) && injournal != 0)) {
235 		if (test_bit(STRIPE_R5C_CACHING, &sh->state))
236 			r5c_make_stripe_write_out(sh);
237 		set_bit(STRIPE_HANDLE, &sh->state);
238 	}
239 
240 	if (test_bit(STRIPE_HANDLE, &sh->state)) {
241 		if (test_bit(STRIPE_DELAYED, &sh->state) &&
242 		    !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
243 			list_add_tail(&sh->lru, &conf->delayed_list);
244 		else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
245 			   sh->bm_seq - conf->seq_write > 0)
246 			list_add_tail(&sh->lru, &conf->bitmap_list);
247 		else {
248 			clear_bit(STRIPE_DELAYED, &sh->state);
249 			clear_bit(STRIPE_BIT_DELAY, &sh->state);
250 			if (conf->worker_cnt_per_group == 0) {
251 				if (stripe_is_lowprio(sh))
252 					list_add_tail(&sh->lru,
253 							&conf->loprio_list);
254 				else
255 					list_add_tail(&sh->lru,
256 							&conf->handle_list);
257 			} else {
258 				raid5_wakeup_stripe_thread(sh);
259 				return;
260 			}
261 		}
262 		md_wakeup_thread(conf->mddev->thread);
263 	} else {
264 		BUG_ON(stripe_operations_active(sh));
265 		if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
266 			if (atomic_dec_return(&conf->preread_active_stripes)
267 			    < IO_THRESHOLD)
268 				md_wakeup_thread(conf->mddev->thread);
269 		atomic_dec(&conf->active_stripes);
270 		if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
271 			if (!r5c_is_writeback(conf->log))
272 				list_add_tail(&sh->lru, temp_inactive_list);
273 			else {
274 				WARN_ON(test_bit(R5_InJournal, &sh->dev[sh->pd_idx].flags));
275 				if (injournal == 0)
276 					list_add_tail(&sh->lru, temp_inactive_list);
277 				else if (injournal == conf->raid_disks - conf->max_degraded) {
278 					/* full stripe */
279 					if (!test_and_set_bit(STRIPE_R5C_FULL_STRIPE, &sh->state))
280 						atomic_inc(&conf->r5c_cached_full_stripes);
281 					if (test_and_clear_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state))
282 						atomic_dec(&conf->r5c_cached_partial_stripes);
283 					list_add_tail(&sh->lru, &conf->r5c_full_stripe_list);
284 					r5c_check_cached_full_stripe(conf);
285 				} else
286 					/*
287 					 * STRIPE_R5C_PARTIAL_STRIPE is set in
288 					 * r5c_try_caching_write(). No need to
289 					 * set it again.
290 					 */
291 					list_add_tail(&sh->lru, &conf->r5c_partial_stripe_list);
292 			}
293 		}
294 	}
295 }
296 
297 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
298 			     struct list_head *temp_inactive_list)
299 {
300 	if (atomic_dec_and_test(&sh->count))
301 		do_release_stripe(conf, sh, temp_inactive_list);
302 }
303 
304 /*
305  * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
306  *
307  * Be careful: Only one task can add/delete stripes from temp_inactive_list at
308  * given time. Adding stripes only takes device lock, while deleting stripes
309  * only takes hash lock.
310  */
311 static void release_inactive_stripe_list(struct r5conf *conf,
312 					 struct list_head *temp_inactive_list,
313 					 int hash)
314 {
315 	int size;
316 	bool do_wakeup = false;
317 	unsigned long flags;
318 
319 	if (hash == NR_STRIPE_HASH_LOCKS) {
320 		size = NR_STRIPE_HASH_LOCKS;
321 		hash = NR_STRIPE_HASH_LOCKS - 1;
322 	} else
323 		size = 1;
324 	while (size) {
325 		struct list_head *list = &temp_inactive_list[size - 1];
326 
327 		/*
328 		 * We don't hold any lock here yet, raid5_get_active_stripe() might
329 		 * remove stripes from the list
330 		 */
331 		if (!list_empty_careful(list)) {
332 			spin_lock_irqsave(conf->hash_locks + hash, flags);
333 			if (list_empty(conf->inactive_list + hash) &&
334 			    !list_empty(list))
335 				atomic_dec(&conf->empty_inactive_list_nr);
336 			list_splice_tail_init(list, conf->inactive_list + hash);
337 			do_wakeup = true;
338 			spin_unlock_irqrestore(conf->hash_locks + hash, flags);
339 		}
340 		size--;
341 		hash--;
342 	}
343 
344 	if (do_wakeup) {
345 		wake_up(&conf->wait_for_stripe);
346 		if (atomic_read(&conf->active_stripes) == 0)
347 			wake_up(&conf->wait_for_quiescent);
348 		if (conf->retry_read_aligned)
349 			md_wakeup_thread(conf->mddev->thread);
350 	}
351 }
352 
353 /* should hold conf->device_lock already */
354 static int release_stripe_list(struct r5conf *conf,
355 			       struct list_head *temp_inactive_list)
356 {
357 	struct stripe_head *sh, *t;
358 	int count = 0;
359 	struct llist_node *head;
360 
361 	head = llist_del_all(&conf->released_stripes);
362 	head = llist_reverse_order(head);
363 	llist_for_each_entry_safe(sh, t, head, release_list) {
364 		int hash;
365 
366 		/* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
367 		smp_mb();
368 		clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
369 		/*
370 		 * Don't worry the bit is set here, because if the bit is set
371 		 * again, the count is always > 1. This is true for
372 		 * STRIPE_ON_UNPLUG_LIST bit too.
373 		 */
374 		hash = sh->hash_lock_index;
375 		__release_stripe(conf, sh, &temp_inactive_list[hash]);
376 		count++;
377 	}
378 
379 	return count;
380 }
381 
382 void raid5_release_stripe(struct stripe_head *sh)
383 {
384 	struct r5conf *conf = sh->raid_conf;
385 	unsigned long flags;
386 	struct list_head list;
387 	int hash;
388 	bool wakeup;
389 
390 	/* Avoid release_list until the last reference.
391 	 */
392 	if (atomic_add_unless(&sh->count, -1, 1))
393 		return;
394 
395 	if (unlikely(!conf->mddev->thread) ||
396 		test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
397 		goto slow_path;
398 	wakeup = llist_add(&sh->release_list, &conf->released_stripes);
399 	if (wakeup)
400 		md_wakeup_thread(conf->mddev->thread);
401 	return;
402 slow_path:
403 	/* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
404 	if (atomic_dec_and_lock_irqsave(&sh->count, &conf->device_lock, flags)) {
405 		INIT_LIST_HEAD(&list);
406 		hash = sh->hash_lock_index;
407 		do_release_stripe(conf, sh, &list);
408 		spin_unlock_irqrestore(&conf->device_lock, flags);
409 		release_inactive_stripe_list(conf, &list, hash);
410 	}
411 }
412 
413 static inline void remove_hash(struct stripe_head *sh)
414 {
415 	pr_debug("remove_hash(), stripe %llu\n",
416 		(unsigned long long)sh->sector);
417 
418 	hlist_del_init(&sh->hash);
419 }
420 
421 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
422 {
423 	struct hlist_head *hp = stripe_hash(conf, sh->sector);
424 
425 	pr_debug("insert_hash(), stripe %llu\n",
426 		(unsigned long long)sh->sector);
427 
428 	hlist_add_head(&sh->hash, hp);
429 }
430 
431 /* find an idle stripe, make sure it is unhashed, and return it. */
432 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
433 {
434 	struct stripe_head *sh = NULL;
435 	struct list_head *first;
436 
437 	if (list_empty(conf->inactive_list + hash))
438 		goto out;
439 	first = (conf->inactive_list + hash)->next;
440 	sh = list_entry(first, struct stripe_head, lru);
441 	list_del_init(first);
442 	remove_hash(sh);
443 	atomic_inc(&conf->active_stripes);
444 	BUG_ON(hash != sh->hash_lock_index);
445 	if (list_empty(conf->inactive_list + hash))
446 		atomic_inc(&conf->empty_inactive_list_nr);
447 out:
448 	return sh;
449 }
450 
451 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
452 static void free_stripe_pages(struct stripe_head *sh)
453 {
454 	int i;
455 	struct page *p;
456 
457 	/* Have not allocate page pool */
458 	if (!sh->pages)
459 		return;
460 
461 	for (i = 0; i < sh->nr_pages; i++) {
462 		p = sh->pages[i];
463 		if (p)
464 			put_page(p);
465 		sh->pages[i] = NULL;
466 	}
467 }
468 
469 static int alloc_stripe_pages(struct stripe_head *sh, gfp_t gfp)
470 {
471 	int i;
472 	struct page *p;
473 
474 	for (i = 0; i < sh->nr_pages; i++) {
475 		/* The page have allocated. */
476 		if (sh->pages[i])
477 			continue;
478 
479 		p = alloc_page(gfp);
480 		if (!p) {
481 			free_stripe_pages(sh);
482 			return -ENOMEM;
483 		}
484 		sh->pages[i] = p;
485 	}
486 	return 0;
487 }
488 
489 static int
490 init_stripe_shared_pages(struct stripe_head *sh, struct r5conf *conf, int disks)
491 {
492 	int nr_pages, cnt;
493 
494 	if (sh->pages)
495 		return 0;
496 
497 	/* Each of the sh->dev[i] need one conf->stripe_size */
498 	cnt = PAGE_SIZE / conf->stripe_size;
499 	nr_pages = (disks + cnt - 1) / cnt;
500 
501 	sh->pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
502 	if (!sh->pages)
503 		return -ENOMEM;
504 	sh->nr_pages = nr_pages;
505 	sh->stripes_per_page = cnt;
506 	return 0;
507 }
508 #endif
509 
510 static void shrink_buffers(struct stripe_head *sh)
511 {
512 	int i;
513 	int num = sh->raid_conf->pool_size;
514 
515 #if PAGE_SIZE == DEFAULT_STRIPE_SIZE
516 	for (i = 0; i < num ; i++) {
517 		struct page *p;
518 
519 		WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
520 		p = sh->dev[i].page;
521 		if (!p)
522 			continue;
523 		sh->dev[i].page = NULL;
524 		put_page(p);
525 	}
526 #else
527 	for (i = 0; i < num; i++)
528 		sh->dev[i].page = NULL;
529 	free_stripe_pages(sh); /* Free pages */
530 #endif
531 }
532 
533 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
534 {
535 	int i;
536 	int num = sh->raid_conf->pool_size;
537 
538 #if PAGE_SIZE == DEFAULT_STRIPE_SIZE
539 	for (i = 0; i < num; i++) {
540 		struct page *page;
541 
542 		if (!(page = alloc_page(gfp))) {
543 			return 1;
544 		}
545 		sh->dev[i].page = page;
546 		sh->dev[i].orig_page = page;
547 		sh->dev[i].offset = 0;
548 	}
549 #else
550 	if (alloc_stripe_pages(sh, gfp))
551 		return -ENOMEM;
552 
553 	for (i = 0; i < num; i++) {
554 		sh->dev[i].page = raid5_get_dev_page(sh, i);
555 		sh->dev[i].orig_page = sh->dev[i].page;
556 		sh->dev[i].offset = raid5_get_page_offset(sh, i);
557 	}
558 #endif
559 	return 0;
560 }
561 
562 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
563 			    struct stripe_head *sh);
564 
565 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
566 {
567 	struct r5conf *conf = sh->raid_conf;
568 	int i, seq;
569 
570 	BUG_ON(atomic_read(&sh->count) != 0);
571 	BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
572 	BUG_ON(stripe_operations_active(sh));
573 	BUG_ON(sh->batch_head);
574 
575 	pr_debug("init_stripe called, stripe %llu\n",
576 		(unsigned long long)sector);
577 retry:
578 	seq = read_seqcount_begin(&conf->gen_lock);
579 	sh->generation = conf->generation - previous;
580 	sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
581 	sh->sector = sector;
582 	stripe_set_idx(sector, conf, previous, sh);
583 	sh->state = 0;
584 
585 	for (i = sh->disks; i--; ) {
586 		struct r5dev *dev = &sh->dev[i];
587 
588 		if (dev->toread || dev->read || dev->towrite || dev->written ||
589 		    test_bit(R5_LOCKED, &dev->flags)) {
590 			pr_err("sector=%llx i=%d %p %p %p %p %d\n",
591 			       (unsigned long long)sh->sector, i, dev->toread,
592 			       dev->read, dev->towrite, dev->written,
593 			       test_bit(R5_LOCKED, &dev->flags));
594 			WARN_ON(1);
595 		}
596 		dev->flags = 0;
597 		dev->sector = raid5_compute_blocknr(sh, i, previous);
598 	}
599 	if (read_seqcount_retry(&conf->gen_lock, seq))
600 		goto retry;
601 	sh->overwrite_disks = 0;
602 	insert_hash(conf, sh);
603 	sh->cpu = smp_processor_id();
604 	set_bit(STRIPE_BATCH_READY, &sh->state);
605 }
606 
607 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
608 					 short generation)
609 {
610 	struct stripe_head *sh;
611 
612 	pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
613 	hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
614 		if (sh->sector == sector && sh->generation == generation)
615 			return sh;
616 	pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
617 	return NULL;
618 }
619 
620 /*
621  * Need to check if array has failed when deciding whether to:
622  *  - start an array
623  *  - remove non-faulty devices
624  *  - add a spare
625  *  - allow a reshape
626  * This determination is simple when no reshape is happening.
627  * However if there is a reshape, we need to carefully check
628  * both the before and after sections.
629  * This is because some failed devices may only affect one
630  * of the two sections, and some non-in_sync devices may
631  * be insync in the section most affected by failed devices.
632  */
633 int raid5_calc_degraded(struct r5conf *conf)
634 {
635 	int degraded, degraded2;
636 	int i;
637 
638 	rcu_read_lock();
639 	degraded = 0;
640 	for (i = 0; i < conf->previous_raid_disks; i++) {
641 		struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
642 		if (rdev && test_bit(Faulty, &rdev->flags))
643 			rdev = rcu_dereference(conf->disks[i].replacement);
644 		if (!rdev || test_bit(Faulty, &rdev->flags))
645 			degraded++;
646 		else if (test_bit(In_sync, &rdev->flags))
647 			;
648 		else
649 			/* not in-sync or faulty.
650 			 * If the reshape increases the number of devices,
651 			 * this is being recovered by the reshape, so
652 			 * this 'previous' section is not in_sync.
653 			 * If the number of devices is being reduced however,
654 			 * the device can only be part of the array if
655 			 * we are reverting a reshape, so this section will
656 			 * be in-sync.
657 			 */
658 			if (conf->raid_disks >= conf->previous_raid_disks)
659 				degraded++;
660 	}
661 	rcu_read_unlock();
662 	if (conf->raid_disks == conf->previous_raid_disks)
663 		return degraded;
664 	rcu_read_lock();
665 	degraded2 = 0;
666 	for (i = 0; i < conf->raid_disks; i++) {
667 		struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
668 		if (rdev && test_bit(Faulty, &rdev->flags))
669 			rdev = rcu_dereference(conf->disks[i].replacement);
670 		if (!rdev || test_bit(Faulty, &rdev->flags))
671 			degraded2++;
672 		else if (test_bit(In_sync, &rdev->flags))
673 			;
674 		else
675 			/* not in-sync or faulty.
676 			 * If reshape increases the number of devices, this
677 			 * section has already been recovered, else it
678 			 * almost certainly hasn't.
679 			 */
680 			if (conf->raid_disks <= conf->previous_raid_disks)
681 				degraded2++;
682 	}
683 	rcu_read_unlock();
684 	if (degraded2 > degraded)
685 		return degraded2;
686 	return degraded;
687 }
688 
689 static int has_failed(struct r5conf *conf)
690 {
691 	int degraded;
692 
693 	if (conf->mddev->reshape_position == MaxSector)
694 		return conf->mddev->degraded > conf->max_degraded;
695 
696 	degraded = raid5_calc_degraded(conf);
697 	if (degraded > conf->max_degraded)
698 		return 1;
699 	return 0;
700 }
701 
702 struct stripe_head *
703 raid5_get_active_stripe(struct r5conf *conf, sector_t sector,
704 			int previous, int noblock, int noquiesce)
705 {
706 	struct stripe_head *sh;
707 	int hash = stripe_hash_locks_hash(conf, sector);
708 	int inc_empty_inactive_list_flag;
709 
710 	pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
711 
712 	spin_lock_irq(conf->hash_locks + hash);
713 
714 	do {
715 		wait_event_lock_irq(conf->wait_for_quiescent,
716 				    conf->quiesce == 0 || noquiesce,
717 				    *(conf->hash_locks + hash));
718 		sh = __find_stripe(conf, sector, conf->generation - previous);
719 		if (!sh) {
720 			if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
721 				sh = get_free_stripe(conf, hash);
722 				if (!sh && !test_bit(R5_DID_ALLOC,
723 						     &conf->cache_state))
724 					set_bit(R5_ALLOC_MORE,
725 						&conf->cache_state);
726 			}
727 			if (noblock && sh == NULL)
728 				break;
729 
730 			r5c_check_stripe_cache_usage(conf);
731 			if (!sh) {
732 				set_bit(R5_INACTIVE_BLOCKED,
733 					&conf->cache_state);
734 				r5l_wake_reclaim(conf->log, 0);
735 				wait_event_lock_irq(
736 					conf->wait_for_stripe,
737 					!list_empty(conf->inactive_list + hash) &&
738 					(atomic_read(&conf->active_stripes)
739 					 < (conf->max_nr_stripes * 3 / 4)
740 					 || !test_bit(R5_INACTIVE_BLOCKED,
741 						      &conf->cache_state)),
742 					*(conf->hash_locks + hash));
743 				clear_bit(R5_INACTIVE_BLOCKED,
744 					  &conf->cache_state);
745 			} else {
746 				init_stripe(sh, sector, previous);
747 				atomic_inc(&sh->count);
748 			}
749 		} else if (!atomic_inc_not_zero(&sh->count)) {
750 			spin_lock(&conf->device_lock);
751 			if (!atomic_read(&sh->count)) {
752 				if (!test_bit(STRIPE_HANDLE, &sh->state))
753 					atomic_inc(&conf->active_stripes);
754 				BUG_ON(list_empty(&sh->lru) &&
755 				       !test_bit(STRIPE_EXPANDING, &sh->state));
756 				inc_empty_inactive_list_flag = 0;
757 				if (!list_empty(conf->inactive_list + hash))
758 					inc_empty_inactive_list_flag = 1;
759 				list_del_init(&sh->lru);
760 				if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
761 					atomic_inc(&conf->empty_inactive_list_nr);
762 				if (sh->group) {
763 					sh->group->stripes_cnt--;
764 					sh->group = NULL;
765 				}
766 			}
767 			atomic_inc(&sh->count);
768 			spin_unlock(&conf->device_lock);
769 		}
770 	} while (sh == NULL);
771 
772 	spin_unlock_irq(conf->hash_locks + hash);
773 	return sh;
774 }
775 
776 static bool is_full_stripe_write(struct stripe_head *sh)
777 {
778 	BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
779 	return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
780 }
781 
782 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
783 		__acquires(&sh1->stripe_lock)
784 		__acquires(&sh2->stripe_lock)
785 {
786 	if (sh1 > sh2) {
787 		spin_lock_irq(&sh2->stripe_lock);
788 		spin_lock_nested(&sh1->stripe_lock, 1);
789 	} else {
790 		spin_lock_irq(&sh1->stripe_lock);
791 		spin_lock_nested(&sh2->stripe_lock, 1);
792 	}
793 }
794 
795 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
796 		__releases(&sh1->stripe_lock)
797 		__releases(&sh2->stripe_lock)
798 {
799 	spin_unlock(&sh1->stripe_lock);
800 	spin_unlock_irq(&sh2->stripe_lock);
801 }
802 
803 /* Only freshly new full stripe normal write stripe can be added to a batch list */
804 static bool stripe_can_batch(struct stripe_head *sh)
805 {
806 	struct r5conf *conf = sh->raid_conf;
807 
808 	if (raid5_has_log(conf) || raid5_has_ppl(conf))
809 		return false;
810 	return test_bit(STRIPE_BATCH_READY, &sh->state) &&
811 		!test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
812 		is_full_stripe_write(sh);
813 }
814 
815 /* we only do back search */
816 static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
817 {
818 	struct stripe_head *head;
819 	sector_t head_sector, tmp_sec;
820 	int hash;
821 	int dd_idx;
822 	int inc_empty_inactive_list_flag;
823 
824 	/* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
825 	tmp_sec = sh->sector;
826 	if (!sector_div(tmp_sec, conf->chunk_sectors))
827 		return;
828 	head_sector = sh->sector - RAID5_STRIPE_SECTORS(conf);
829 
830 	hash = stripe_hash_locks_hash(conf, head_sector);
831 	spin_lock_irq(conf->hash_locks + hash);
832 	head = __find_stripe(conf, head_sector, conf->generation);
833 	if (head && !atomic_inc_not_zero(&head->count)) {
834 		spin_lock(&conf->device_lock);
835 		if (!atomic_read(&head->count)) {
836 			if (!test_bit(STRIPE_HANDLE, &head->state))
837 				atomic_inc(&conf->active_stripes);
838 			BUG_ON(list_empty(&head->lru) &&
839 			       !test_bit(STRIPE_EXPANDING, &head->state));
840 			inc_empty_inactive_list_flag = 0;
841 			if (!list_empty(conf->inactive_list + hash))
842 				inc_empty_inactive_list_flag = 1;
843 			list_del_init(&head->lru);
844 			if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
845 				atomic_inc(&conf->empty_inactive_list_nr);
846 			if (head->group) {
847 				head->group->stripes_cnt--;
848 				head->group = NULL;
849 			}
850 		}
851 		atomic_inc(&head->count);
852 		spin_unlock(&conf->device_lock);
853 	}
854 	spin_unlock_irq(conf->hash_locks + hash);
855 
856 	if (!head)
857 		return;
858 	if (!stripe_can_batch(head))
859 		goto out;
860 
861 	lock_two_stripes(head, sh);
862 	/* clear_batch_ready clear the flag */
863 	if (!stripe_can_batch(head) || !stripe_can_batch(sh))
864 		goto unlock_out;
865 
866 	if (sh->batch_head)
867 		goto unlock_out;
868 
869 	dd_idx = 0;
870 	while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
871 		dd_idx++;
872 	if (head->dev[dd_idx].towrite->bi_opf != sh->dev[dd_idx].towrite->bi_opf ||
873 	    bio_op(head->dev[dd_idx].towrite) != bio_op(sh->dev[dd_idx].towrite))
874 		goto unlock_out;
875 
876 	if (head->batch_head) {
877 		spin_lock(&head->batch_head->batch_lock);
878 		/* This batch list is already running */
879 		if (!stripe_can_batch(head)) {
880 			spin_unlock(&head->batch_head->batch_lock);
881 			goto unlock_out;
882 		}
883 		/*
884 		 * We must assign batch_head of this stripe within the
885 		 * batch_lock, otherwise clear_batch_ready of batch head
886 		 * stripe could clear BATCH_READY bit of this stripe and
887 		 * this stripe->batch_head doesn't get assigned, which
888 		 * could confuse clear_batch_ready for this stripe
889 		 */
890 		sh->batch_head = head->batch_head;
891 
892 		/*
893 		 * at this point, head's BATCH_READY could be cleared, but we
894 		 * can still add the stripe to batch list
895 		 */
896 		list_add(&sh->batch_list, &head->batch_list);
897 		spin_unlock(&head->batch_head->batch_lock);
898 	} else {
899 		head->batch_head = head;
900 		sh->batch_head = head->batch_head;
901 		spin_lock(&head->batch_lock);
902 		list_add_tail(&sh->batch_list, &head->batch_list);
903 		spin_unlock(&head->batch_lock);
904 	}
905 
906 	if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
907 		if (atomic_dec_return(&conf->preread_active_stripes)
908 		    < IO_THRESHOLD)
909 			md_wakeup_thread(conf->mddev->thread);
910 
911 	if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
912 		int seq = sh->bm_seq;
913 		if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
914 		    sh->batch_head->bm_seq > seq)
915 			seq = sh->batch_head->bm_seq;
916 		set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
917 		sh->batch_head->bm_seq = seq;
918 	}
919 
920 	atomic_inc(&sh->count);
921 unlock_out:
922 	unlock_two_stripes(head, sh);
923 out:
924 	raid5_release_stripe(head);
925 }
926 
927 /* Determine if 'data_offset' or 'new_data_offset' should be used
928  * in this stripe_head.
929  */
930 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
931 {
932 	sector_t progress = conf->reshape_progress;
933 	/* Need a memory barrier to make sure we see the value
934 	 * of conf->generation, or ->data_offset that was set before
935 	 * reshape_progress was updated.
936 	 */
937 	smp_rmb();
938 	if (progress == MaxSector)
939 		return 0;
940 	if (sh->generation == conf->generation - 1)
941 		return 0;
942 	/* We are in a reshape, and this is a new-generation stripe,
943 	 * so use new_data_offset.
944 	 */
945 	return 1;
946 }
947 
948 static void dispatch_bio_list(struct bio_list *tmp)
949 {
950 	struct bio *bio;
951 
952 	while ((bio = bio_list_pop(tmp)))
953 		submit_bio_noacct(bio);
954 }
955 
956 static int cmp_stripe(void *priv, const struct list_head *a,
957 		      const struct list_head *b)
958 {
959 	const struct r5pending_data *da = list_entry(a,
960 				struct r5pending_data, sibling);
961 	const struct r5pending_data *db = list_entry(b,
962 				struct r5pending_data, sibling);
963 	if (da->sector > db->sector)
964 		return 1;
965 	if (da->sector < db->sector)
966 		return -1;
967 	return 0;
968 }
969 
970 static void dispatch_defer_bios(struct r5conf *conf, int target,
971 				struct bio_list *list)
972 {
973 	struct r5pending_data *data;
974 	struct list_head *first, *next = NULL;
975 	int cnt = 0;
976 
977 	if (conf->pending_data_cnt == 0)
978 		return;
979 
980 	list_sort(NULL, &conf->pending_list, cmp_stripe);
981 
982 	first = conf->pending_list.next;
983 
984 	/* temporarily move the head */
985 	if (conf->next_pending_data)
986 		list_move_tail(&conf->pending_list,
987 				&conf->next_pending_data->sibling);
988 
989 	while (!list_empty(&conf->pending_list)) {
990 		data = list_first_entry(&conf->pending_list,
991 			struct r5pending_data, sibling);
992 		if (&data->sibling == first)
993 			first = data->sibling.next;
994 		next = data->sibling.next;
995 
996 		bio_list_merge(list, &data->bios);
997 		list_move(&data->sibling, &conf->free_list);
998 		cnt++;
999 		if (cnt >= target)
1000 			break;
1001 	}
1002 	conf->pending_data_cnt -= cnt;
1003 	BUG_ON(conf->pending_data_cnt < 0 || cnt < target);
1004 
1005 	if (next != &conf->pending_list)
1006 		conf->next_pending_data = list_entry(next,
1007 				struct r5pending_data, sibling);
1008 	else
1009 		conf->next_pending_data = NULL;
1010 	/* list isn't empty */
1011 	if (first != &conf->pending_list)
1012 		list_move_tail(&conf->pending_list, first);
1013 }
1014 
1015 static void flush_deferred_bios(struct r5conf *conf)
1016 {
1017 	struct bio_list tmp = BIO_EMPTY_LIST;
1018 
1019 	if (conf->pending_data_cnt == 0)
1020 		return;
1021 
1022 	spin_lock(&conf->pending_bios_lock);
1023 	dispatch_defer_bios(conf, conf->pending_data_cnt, &tmp);
1024 	BUG_ON(conf->pending_data_cnt != 0);
1025 	spin_unlock(&conf->pending_bios_lock);
1026 
1027 	dispatch_bio_list(&tmp);
1028 }
1029 
1030 static void defer_issue_bios(struct r5conf *conf, sector_t sector,
1031 				struct bio_list *bios)
1032 {
1033 	struct bio_list tmp = BIO_EMPTY_LIST;
1034 	struct r5pending_data *ent;
1035 
1036 	spin_lock(&conf->pending_bios_lock);
1037 	ent = list_first_entry(&conf->free_list, struct r5pending_data,
1038 							sibling);
1039 	list_move_tail(&ent->sibling, &conf->pending_list);
1040 	ent->sector = sector;
1041 	bio_list_init(&ent->bios);
1042 	bio_list_merge(&ent->bios, bios);
1043 	conf->pending_data_cnt++;
1044 	if (conf->pending_data_cnt >= PENDING_IO_MAX)
1045 		dispatch_defer_bios(conf, PENDING_IO_ONE_FLUSH, &tmp);
1046 
1047 	spin_unlock(&conf->pending_bios_lock);
1048 
1049 	dispatch_bio_list(&tmp);
1050 }
1051 
1052 static void
1053 raid5_end_read_request(struct bio *bi);
1054 static void
1055 raid5_end_write_request(struct bio *bi);
1056 
1057 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
1058 {
1059 	struct r5conf *conf = sh->raid_conf;
1060 	int i, disks = sh->disks;
1061 	struct stripe_head *head_sh = sh;
1062 	struct bio_list pending_bios = BIO_EMPTY_LIST;
1063 	bool should_defer;
1064 
1065 	might_sleep();
1066 
1067 	if (log_stripe(sh, s) == 0)
1068 		return;
1069 
1070 	should_defer = conf->batch_bio_dispatch && conf->group_cnt;
1071 
1072 	for (i = disks; i--; ) {
1073 		int op, op_flags = 0;
1074 		int replace_only = 0;
1075 		struct bio *bi, *rbi;
1076 		struct md_rdev *rdev, *rrdev = NULL;
1077 
1078 		sh = head_sh;
1079 		if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
1080 			op = REQ_OP_WRITE;
1081 			if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
1082 				op_flags = REQ_FUA;
1083 			if (test_bit(R5_Discard, &sh->dev[i].flags))
1084 				op = REQ_OP_DISCARD;
1085 		} else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
1086 			op = REQ_OP_READ;
1087 		else if (test_and_clear_bit(R5_WantReplace,
1088 					    &sh->dev[i].flags)) {
1089 			op = REQ_OP_WRITE;
1090 			replace_only = 1;
1091 		} else
1092 			continue;
1093 		if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
1094 			op_flags |= REQ_SYNC;
1095 
1096 again:
1097 		bi = &sh->dev[i].req;
1098 		rbi = &sh->dev[i].rreq; /* For writing to replacement */
1099 
1100 		rcu_read_lock();
1101 		rrdev = rcu_dereference(conf->disks[i].replacement);
1102 		smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
1103 		rdev = rcu_dereference(conf->disks[i].rdev);
1104 		if (!rdev) {
1105 			rdev = rrdev;
1106 			rrdev = NULL;
1107 		}
1108 		if (op_is_write(op)) {
1109 			if (replace_only)
1110 				rdev = NULL;
1111 			if (rdev == rrdev)
1112 				/* We raced and saw duplicates */
1113 				rrdev = NULL;
1114 		} else {
1115 			if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
1116 				rdev = rrdev;
1117 			rrdev = NULL;
1118 		}
1119 
1120 		if (rdev && test_bit(Faulty, &rdev->flags))
1121 			rdev = NULL;
1122 		if (rdev)
1123 			atomic_inc(&rdev->nr_pending);
1124 		if (rrdev && test_bit(Faulty, &rrdev->flags))
1125 			rrdev = NULL;
1126 		if (rrdev)
1127 			atomic_inc(&rrdev->nr_pending);
1128 		rcu_read_unlock();
1129 
1130 		/* We have already checked bad blocks for reads.  Now
1131 		 * need to check for writes.  We never accept write errors
1132 		 * on the replacement, so we don't to check rrdev.
1133 		 */
1134 		while (op_is_write(op) && rdev &&
1135 		       test_bit(WriteErrorSeen, &rdev->flags)) {
1136 			sector_t first_bad;
1137 			int bad_sectors;
1138 			int bad = is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
1139 					      &first_bad, &bad_sectors);
1140 			if (!bad)
1141 				break;
1142 
1143 			if (bad < 0) {
1144 				set_bit(BlockedBadBlocks, &rdev->flags);
1145 				if (!conf->mddev->external &&
1146 				    conf->mddev->sb_flags) {
1147 					/* It is very unlikely, but we might
1148 					 * still need to write out the
1149 					 * bad block log - better give it
1150 					 * a chance*/
1151 					md_check_recovery(conf->mddev);
1152 				}
1153 				/*
1154 				 * Because md_wait_for_blocked_rdev
1155 				 * will dec nr_pending, we must
1156 				 * increment it first.
1157 				 */
1158 				atomic_inc(&rdev->nr_pending);
1159 				md_wait_for_blocked_rdev(rdev, conf->mddev);
1160 			} else {
1161 				/* Acknowledged bad block - skip the write */
1162 				rdev_dec_pending(rdev, conf->mddev);
1163 				rdev = NULL;
1164 			}
1165 		}
1166 
1167 		if (rdev) {
1168 			if (s->syncing || s->expanding || s->expanded
1169 			    || s->replacing)
1170 				md_sync_acct(rdev->bdev, RAID5_STRIPE_SECTORS(conf));
1171 
1172 			set_bit(STRIPE_IO_STARTED, &sh->state);
1173 
1174 			bio_set_dev(bi, rdev->bdev);
1175 			bio_set_op_attrs(bi, op, op_flags);
1176 			bi->bi_end_io = op_is_write(op)
1177 				? raid5_end_write_request
1178 				: raid5_end_read_request;
1179 			bi->bi_private = sh;
1180 
1181 			pr_debug("%s: for %llu schedule op %d on disc %d\n",
1182 				__func__, (unsigned long long)sh->sector,
1183 				bi->bi_opf, i);
1184 			atomic_inc(&sh->count);
1185 			if (sh != head_sh)
1186 				atomic_inc(&head_sh->count);
1187 			if (use_new_offset(conf, sh))
1188 				bi->bi_iter.bi_sector = (sh->sector
1189 						 + rdev->new_data_offset);
1190 			else
1191 				bi->bi_iter.bi_sector = (sh->sector
1192 						 + rdev->data_offset);
1193 			if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1194 				bi->bi_opf |= REQ_NOMERGE;
1195 
1196 			if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1197 				WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1198 
1199 			if (!op_is_write(op) &&
1200 			    test_bit(R5_InJournal, &sh->dev[i].flags))
1201 				/*
1202 				 * issuing read for a page in journal, this
1203 				 * must be preparing for prexor in rmw; read
1204 				 * the data into orig_page
1205 				 */
1206 				sh->dev[i].vec.bv_page = sh->dev[i].orig_page;
1207 			else
1208 				sh->dev[i].vec.bv_page = sh->dev[i].page;
1209 			bi->bi_vcnt = 1;
1210 			bi->bi_io_vec[0].bv_len = RAID5_STRIPE_SIZE(conf);
1211 			bi->bi_io_vec[0].bv_offset = sh->dev[i].offset;
1212 			bi->bi_iter.bi_size = RAID5_STRIPE_SIZE(conf);
1213 			bi->bi_write_hint = sh->dev[i].write_hint;
1214 			if (!rrdev)
1215 				sh->dev[i].write_hint = RWH_WRITE_LIFE_NOT_SET;
1216 			/*
1217 			 * If this is discard request, set bi_vcnt 0. We don't
1218 			 * want to confuse SCSI because SCSI will replace payload
1219 			 */
1220 			if (op == REQ_OP_DISCARD)
1221 				bi->bi_vcnt = 0;
1222 			if (rrdev)
1223 				set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1224 
1225 			if (conf->mddev->gendisk)
1226 				trace_block_bio_remap(bi,
1227 						disk_devt(conf->mddev->gendisk),
1228 						sh->dev[i].sector);
1229 			if (should_defer && op_is_write(op))
1230 				bio_list_add(&pending_bios, bi);
1231 			else
1232 				submit_bio_noacct(bi);
1233 		}
1234 		if (rrdev) {
1235 			if (s->syncing || s->expanding || s->expanded
1236 			    || s->replacing)
1237 				md_sync_acct(rrdev->bdev, RAID5_STRIPE_SECTORS(conf));
1238 
1239 			set_bit(STRIPE_IO_STARTED, &sh->state);
1240 
1241 			bio_set_dev(rbi, rrdev->bdev);
1242 			bio_set_op_attrs(rbi, op, op_flags);
1243 			BUG_ON(!op_is_write(op));
1244 			rbi->bi_end_io = raid5_end_write_request;
1245 			rbi->bi_private = sh;
1246 
1247 			pr_debug("%s: for %llu schedule op %d on "
1248 				 "replacement disc %d\n",
1249 				__func__, (unsigned long long)sh->sector,
1250 				rbi->bi_opf, i);
1251 			atomic_inc(&sh->count);
1252 			if (sh != head_sh)
1253 				atomic_inc(&head_sh->count);
1254 			if (use_new_offset(conf, sh))
1255 				rbi->bi_iter.bi_sector = (sh->sector
1256 						  + rrdev->new_data_offset);
1257 			else
1258 				rbi->bi_iter.bi_sector = (sh->sector
1259 						  + rrdev->data_offset);
1260 			if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1261 				WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1262 			sh->dev[i].rvec.bv_page = sh->dev[i].page;
1263 			rbi->bi_vcnt = 1;
1264 			rbi->bi_io_vec[0].bv_len = RAID5_STRIPE_SIZE(conf);
1265 			rbi->bi_io_vec[0].bv_offset = sh->dev[i].offset;
1266 			rbi->bi_iter.bi_size = RAID5_STRIPE_SIZE(conf);
1267 			rbi->bi_write_hint = sh->dev[i].write_hint;
1268 			sh->dev[i].write_hint = RWH_WRITE_LIFE_NOT_SET;
1269 			/*
1270 			 * If this is discard request, set bi_vcnt 0. We don't
1271 			 * want to confuse SCSI because SCSI will replace payload
1272 			 */
1273 			if (op == REQ_OP_DISCARD)
1274 				rbi->bi_vcnt = 0;
1275 			if (conf->mddev->gendisk)
1276 				trace_block_bio_remap(rbi,
1277 						disk_devt(conf->mddev->gendisk),
1278 						sh->dev[i].sector);
1279 			if (should_defer && op_is_write(op))
1280 				bio_list_add(&pending_bios, rbi);
1281 			else
1282 				submit_bio_noacct(rbi);
1283 		}
1284 		if (!rdev && !rrdev) {
1285 			if (op_is_write(op))
1286 				set_bit(STRIPE_DEGRADED, &sh->state);
1287 			pr_debug("skip op %d on disc %d for sector %llu\n",
1288 				bi->bi_opf, i, (unsigned long long)sh->sector);
1289 			clear_bit(R5_LOCKED, &sh->dev[i].flags);
1290 			set_bit(STRIPE_HANDLE, &sh->state);
1291 		}
1292 
1293 		if (!head_sh->batch_head)
1294 			continue;
1295 		sh = list_first_entry(&sh->batch_list, struct stripe_head,
1296 				      batch_list);
1297 		if (sh != head_sh)
1298 			goto again;
1299 	}
1300 
1301 	if (should_defer && !bio_list_empty(&pending_bios))
1302 		defer_issue_bios(conf, head_sh->sector, &pending_bios);
1303 }
1304 
1305 static struct dma_async_tx_descriptor *
1306 async_copy_data(int frombio, struct bio *bio, struct page **page,
1307 	unsigned int poff, sector_t sector, struct dma_async_tx_descriptor *tx,
1308 	struct stripe_head *sh, int no_skipcopy)
1309 {
1310 	struct bio_vec bvl;
1311 	struct bvec_iter iter;
1312 	struct page *bio_page;
1313 	int page_offset;
1314 	struct async_submit_ctl submit;
1315 	enum async_tx_flags flags = 0;
1316 	struct r5conf *conf = sh->raid_conf;
1317 
1318 	if (bio->bi_iter.bi_sector >= sector)
1319 		page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1320 	else
1321 		page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1322 
1323 	if (frombio)
1324 		flags |= ASYNC_TX_FENCE;
1325 	init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1326 
1327 	bio_for_each_segment(bvl, bio, iter) {
1328 		int len = bvl.bv_len;
1329 		int clen;
1330 		int b_offset = 0;
1331 
1332 		if (page_offset < 0) {
1333 			b_offset = -page_offset;
1334 			page_offset += b_offset;
1335 			len -= b_offset;
1336 		}
1337 
1338 		if (len > 0 && page_offset + len > RAID5_STRIPE_SIZE(conf))
1339 			clen = RAID5_STRIPE_SIZE(conf) - page_offset;
1340 		else
1341 			clen = len;
1342 
1343 		if (clen > 0) {
1344 			b_offset += bvl.bv_offset;
1345 			bio_page = bvl.bv_page;
1346 			if (frombio) {
1347 				if (conf->skip_copy &&
1348 				    b_offset == 0 && page_offset == 0 &&
1349 				    clen == RAID5_STRIPE_SIZE(conf) &&
1350 				    !no_skipcopy)
1351 					*page = bio_page;
1352 				else
1353 					tx = async_memcpy(*page, bio_page, page_offset + poff,
1354 						  b_offset, clen, &submit);
1355 			} else
1356 				tx = async_memcpy(bio_page, *page, b_offset,
1357 						  page_offset + poff, clen, &submit);
1358 		}
1359 		/* chain the operations */
1360 		submit.depend_tx = tx;
1361 
1362 		if (clen < len) /* hit end of page */
1363 			break;
1364 		page_offset +=  len;
1365 	}
1366 
1367 	return tx;
1368 }
1369 
1370 static void ops_complete_biofill(void *stripe_head_ref)
1371 {
1372 	struct stripe_head *sh = stripe_head_ref;
1373 	int i;
1374 	struct r5conf *conf = sh->raid_conf;
1375 
1376 	pr_debug("%s: stripe %llu\n", __func__,
1377 		(unsigned long long)sh->sector);
1378 
1379 	/* clear completed biofills */
1380 	for (i = sh->disks; i--; ) {
1381 		struct r5dev *dev = &sh->dev[i];
1382 
1383 		/* acknowledge completion of a biofill operation */
1384 		/* and check if we need to reply to a read request,
1385 		 * new R5_Wantfill requests are held off until
1386 		 * !STRIPE_BIOFILL_RUN
1387 		 */
1388 		if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1389 			struct bio *rbi, *rbi2;
1390 
1391 			BUG_ON(!dev->read);
1392 			rbi = dev->read;
1393 			dev->read = NULL;
1394 			while (rbi && rbi->bi_iter.bi_sector <
1395 				dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1396 				rbi2 = r5_next_bio(conf, rbi, dev->sector);
1397 				bio_endio(rbi);
1398 				rbi = rbi2;
1399 			}
1400 		}
1401 	}
1402 	clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1403 
1404 	set_bit(STRIPE_HANDLE, &sh->state);
1405 	raid5_release_stripe(sh);
1406 }
1407 
1408 static void ops_run_biofill(struct stripe_head *sh)
1409 {
1410 	struct dma_async_tx_descriptor *tx = NULL;
1411 	struct async_submit_ctl submit;
1412 	int i;
1413 	struct r5conf *conf = sh->raid_conf;
1414 
1415 	BUG_ON(sh->batch_head);
1416 	pr_debug("%s: stripe %llu\n", __func__,
1417 		(unsigned long long)sh->sector);
1418 
1419 	for (i = sh->disks; i--; ) {
1420 		struct r5dev *dev = &sh->dev[i];
1421 		if (test_bit(R5_Wantfill, &dev->flags)) {
1422 			struct bio *rbi;
1423 			spin_lock_irq(&sh->stripe_lock);
1424 			dev->read = rbi = dev->toread;
1425 			dev->toread = NULL;
1426 			spin_unlock_irq(&sh->stripe_lock);
1427 			while (rbi && rbi->bi_iter.bi_sector <
1428 				dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1429 				tx = async_copy_data(0, rbi, &dev->page,
1430 						     dev->offset,
1431 						     dev->sector, tx, sh, 0);
1432 				rbi = r5_next_bio(conf, rbi, dev->sector);
1433 			}
1434 		}
1435 	}
1436 
1437 	atomic_inc(&sh->count);
1438 	init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1439 	async_trigger_callback(&submit);
1440 }
1441 
1442 static void mark_target_uptodate(struct stripe_head *sh, int target)
1443 {
1444 	struct r5dev *tgt;
1445 
1446 	if (target < 0)
1447 		return;
1448 
1449 	tgt = &sh->dev[target];
1450 	set_bit(R5_UPTODATE, &tgt->flags);
1451 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1452 	clear_bit(R5_Wantcompute, &tgt->flags);
1453 }
1454 
1455 static void ops_complete_compute(void *stripe_head_ref)
1456 {
1457 	struct stripe_head *sh = stripe_head_ref;
1458 
1459 	pr_debug("%s: stripe %llu\n", __func__,
1460 		(unsigned long long)sh->sector);
1461 
1462 	/* mark the computed target(s) as uptodate */
1463 	mark_target_uptodate(sh, sh->ops.target);
1464 	mark_target_uptodate(sh, sh->ops.target2);
1465 
1466 	clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1467 	if (sh->check_state == check_state_compute_run)
1468 		sh->check_state = check_state_compute_result;
1469 	set_bit(STRIPE_HANDLE, &sh->state);
1470 	raid5_release_stripe(sh);
1471 }
1472 
1473 /* return a pointer to the address conversion region of the scribble buffer */
1474 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1475 {
1476 	return percpu->scribble + i * percpu->scribble_obj_size;
1477 }
1478 
1479 /* return a pointer to the address conversion region of the scribble buffer */
1480 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1481 				 struct raid5_percpu *percpu, int i)
1482 {
1483 	return (void *) (to_addr_page(percpu, i) + sh->disks + 2);
1484 }
1485 
1486 /*
1487  * Return a pointer to record offset address.
1488  */
1489 static unsigned int *
1490 to_addr_offs(struct stripe_head *sh, struct raid5_percpu *percpu)
1491 {
1492 	return (unsigned int *) (to_addr_conv(sh, percpu, 0) + sh->disks + 2);
1493 }
1494 
1495 static struct dma_async_tx_descriptor *
1496 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1497 {
1498 	int disks = sh->disks;
1499 	struct page **xor_srcs = to_addr_page(percpu, 0);
1500 	unsigned int *off_srcs = to_addr_offs(sh, percpu);
1501 	int target = sh->ops.target;
1502 	struct r5dev *tgt = &sh->dev[target];
1503 	struct page *xor_dest = tgt->page;
1504 	unsigned int off_dest = tgt->offset;
1505 	int count = 0;
1506 	struct dma_async_tx_descriptor *tx;
1507 	struct async_submit_ctl submit;
1508 	int i;
1509 
1510 	BUG_ON(sh->batch_head);
1511 
1512 	pr_debug("%s: stripe %llu block: %d\n",
1513 		__func__, (unsigned long long)sh->sector, target);
1514 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1515 
1516 	for (i = disks; i--; ) {
1517 		if (i != target) {
1518 			off_srcs[count] = sh->dev[i].offset;
1519 			xor_srcs[count++] = sh->dev[i].page;
1520 		}
1521 	}
1522 
1523 	atomic_inc(&sh->count);
1524 
1525 	init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1526 			  ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1527 	if (unlikely(count == 1))
1528 		tx = async_memcpy(xor_dest, xor_srcs[0], off_dest, off_srcs[0],
1529 				RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1530 	else
1531 		tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
1532 				RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1533 
1534 	return tx;
1535 }
1536 
1537 /* set_syndrome_sources - populate source buffers for gen_syndrome
1538  * @srcs - (struct page *) array of size sh->disks
1539  * @offs - (unsigned int) array of offset for each page
1540  * @sh - stripe_head to parse
1541  *
1542  * Populates srcs in proper layout order for the stripe and returns the
1543  * 'count' of sources to be used in a call to async_gen_syndrome.  The P
1544  * destination buffer is recorded in srcs[count] and the Q destination
1545  * is recorded in srcs[count+1]].
1546  */
1547 static int set_syndrome_sources(struct page **srcs,
1548 				unsigned int *offs,
1549 				struct stripe_head *sh,
1550 				int srctype)
1551 {
1552 	int disks = sh->disks;
1553 	int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1554 	int d0_idx = raid6_d0(sh);
1555 	int count;
1556 	int i;
1557 
1558 	for (i = 0; i < disks; i++)
1559 		srcs[i] = NULL;
1560 
1561 	count = 0;
1562 	i = d0_idx;
1563 	do {
1564 		int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1565 		struct r5dev *dev = &sh->dev[i];
1566 
1567 		if (i == sh->qd_idx || i == sh->pd_idx ||
1568 		    (srctype == SYNDROME_SRC_ALL) ||
1569 		    (srctype == SYNDROME_SRC_WANT_DRAIN &&
1570 		     (test_bit(R5_Wantdrain, &dev->flags) ||
1571 		      test_bit(R5_InJournal, &dev->flags))) ||
1572 		    (srctype == SYNDROME_SRC_WRITTEN &&
1573 		     (dev->written ||
1574 		      test_bit(R5_InJournal, &dev->flags)))) {
1575 			if (test_bit(R5_InJournal, &dev->flags))
1576 				srcs[slot] = sh->dev[i].orig_page;
1577 			else
1578 				srcs[slot] = sh->dev[i].page;
1579 			/*
1580 			 * For R5_InJournal, PAGE_SIZE must be 4KB and will
1581 			 * not shared page. In that case, dev[i].offset
1582 			 * is 0.
1583 			 */
1584 			offs[slot] = sh->dev[i].offset;
1585 		}
1586 		i = raid6_next_disk(i, disks);
1587 	} while (i != d0_idx);
1588 
1589 	return syndrome_disks;
1590 }
1591 
1592 static struct dma_async_tx_descriptor *
1593 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1594 {
1595 	int disks = sh->disks;
1596 	struct page **blocks = to_addr_page(percpu, 0);
1597 	unsigned int *offs = to_addr_offs(sh, percpu);
1598 	int target;
1599 	int qd_idx = sh->qd_idx;
1600 	struct dma_async_tx_descriptor *tx;
1601 	struct async_submit_ctl submit;
1602 	struct r5dev *tgt;
1603 	struct page *dest;
1604 	unsigned int dest_off;
1605 	int i;
1606 	int count;
1607 
1608 	BUG_ON(sh->batch_head);
1609 	if (sh->ops.target < 0)
1610 		target = sh->ops.target2;
1611 	else if (sh->ops.target2 < 0)
1612 		target = sh->ops.target;
1613 	else
1614 		/* we should only have one valid target */
1615 		BUG();
1616 	BUG_ON(target < 0);
1617 	pr_debug("%s: stripe %llu block: %d\n",
1618 		__func__, (unsigned long long)sh->sector, target);
1619 
1620 	tgt = &sh->dev[target];
1621 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1622 	dest = tgt->page;
1623 	dest_off = tgt->offset;
1624 
1625 	atomic_inc(&sh->count);
1626 
1627 	if (target == qd_idx) {
1628 		count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_ALL);
1629 		blocks[count] = NULL; /* regenerating p is not necessary */
1630 		BUG_ON(blocks[count+1] != dest); /* q should already be set */
1631 		init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1632 				  ops_complete_compute, sh,
1633 				  to_addr_conv(sh, percpu, 0));
1634 		tx = async_gen_syndrome(blocks, offs, count+2,
1635 				RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1636 	} else {
1637 		/* Compute any data- or p-drive using XOR */
1638 		count = 0;
1639 		for (i = disks; i-- ; ) {
1640 			if (i == target || i == qd_idx)
1641 				continue;
1642 			offs[count] = sh->dev[i].offset;
1643 			blocks[count++] = sh->dev[i].page;
1644 		}
1645 
1646 		init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1647 				  NULL, ops_complete_compute, sh,
1648 				  to_addr_conv(sh, percpu, 0));
1649 		tx = async_xor_offs(dest, dest_off, blocks, offs, count,
1650 				RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1651 	}
1652 
1653 	return tx;
1654 }
1655 
1656 static struct dma_async_tx_descriptor *
1657 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1658 {
1659 	int i, count, disks = sh->disks;
1660 	int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1661 	int d0_idx = raid6_d0(sh);
1662 	int faila = -1, failb = -1;
1663 	int target = sh->ops.target;
1664 	int target2 = sh->ops.target2;
1665 	struct r5dev *tgt = &sh->dev[target];
1666 	struct r5dev *tgt2 = &sh->dev[target2];
1667 	struct dma_async_tx_descriptor *tx;
1668 	struct page **blocks = to_addr_page(percpu, 0);
1669 	unsigned int *offs = to_addr_offs(sh, percpu);
1670 	struct async_submit_ctl submit;
1671 
1672 	BUG_ON(sh->batch_head);
1673 	pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1674 		 __func__, (unsigned long long)sh->sector, target, target2);
1675 	BUG_ON(target < 0 || target2 < 0);
1676 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1677 	BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1678 
1679 	/* we need to open-code set_syndrome_sources to handle the
1680 	 * slot number conversion for 'faila' and 'failb'
1681 	 */
1682 	for (i = 0; i < disks ; i++) {
1683 		offs[i] = 0;
1684 		blocks[i] = NULL;
1685 	}
1686 	count = 0;
1687 	i = d0_idx;
1688 	do {
1689 		int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1690 
1691 		offs[slot] = sh->dev[i].offset;
1692 		blocks[slot] = sh->dev[i].page;
1693 
1694 		if (i == target)
1695 			faila = slot;
1696 		if (i == target2)
1697 			failb = slot;
1698 		i = raid6_next_disk(i, disks);
1699 	} while (i != d0_idx);
1700 
1701 	BUG_ON(faila == failb);
1702 	if (failb < faila)
1703 		swap(faila, failb);
1704 	pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1705 		 __func__, (unsigned long long)sh->sector, faila, failb);
1706 
1707 	atomic_inc(&sh->count);
1708 
1709 	if (failb == syndrome_disks+1) {
1710 		/* Q disk is one of the missing disks */
1711 		if (faila == syndrome_disks) {
1712 			/* Missing P+Q, just recompute */
1713 			init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1714 					  ops_complete_compute, sh,
1715 					  to_addr_conv(sh, percpu, 0));
1716 			return async_gen_syndrome(blocks, offs, syndrome_disks+2,
1717 						  RAID5_STRIPE_SIZE(sh->raid_conf),
1718 						  &submit);
1719 		} else {
1720 			struct page *dest;
1721 			unsigned int dest_off;
1722 			int data_target;
1723 			int qd_idx = sh->qd_idx;
1724 
1725 			/* Missing D+Q: recompute D from P, then recompute Q */
1726 			if (target == qd_idx)
1727 				data_target = target2;
1728 			else
1729 				data_target = target;
1730 
1731 			count = 0;
1732 			for (i = disks; i-- ; ) {
1733 				if (i == data_target || i == qd_idx)
1734 					continue;
1735 				offs[count] = sh->dev[i].offset;
1736 				blocks[count++] = sh->dev[i].page;
1737 			}
1738 			dest = sh->dev[data_target].page;
1739 			dest_off = sh->dev[data_target].offset;
1740 			init_async_submit(&submit,
1741 					  ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1742 					  NULL, NULL, NULL,
1743 					  to_addr_conv(sh, percpu, 0));
1744 			tx = async_xor_offs(dest, dest_off, blocks, offs, count,
1745 				       RAID5_STRIPE_SIZE(sh->raid_conf),
1746 				       &submit);
1747 
1748 			count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_ALL);
1749 			init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1750 					  ops_complete_compute, sh,
1751 					  to_addr_conv(sh, percpu, 0));
1752 			return async_gen_syndrome(blocks, offs, count+2,
1753 						  RAID5_STRIPE_SIZE(sh->raid_conf),
1754 						  &submit);
1755 		}
1756 	} else {
1757 		init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1758 				  ops_complete_compute, sh,
1759 				  to_addr_conv(sh, percpu, 0));
1760 		if (failb == syndrome_disks) {
1761 			/* We're missing D+P. */
1762 			return async_raid6_datap_recov(syndrome_disks+2,
1763 						RAID5_STRIPE_SIZE(sh->raid_conf),
1764 						faila,
1765 						blocks, offs, &submit);
1766 		} else {
1767 			/* We're missing D+D. */
1768 			return async_raid6_2data_recov(syndrome_disks+2,
1769 						RAID5_STRIPE_SIZE(sh->raid_conf),
1770 						faila, failb,
1771 						blocks, offs, &submit);
1772 		}
1773 	}
1774 }
1775 
1776 static void ops_complete_prexor(void *stripe_head_ref)
1777 {
1778 	struct stripe_head *sh = stripe_head_ref;
1779 
1780 	pr_debug("%s: stripe %llu\n", __func__,
1781 		(unsigned long long)sh->sector);
1782 
1783 	if (r5c_is_writeback(sh->raid_conf->log))
1784 		/*
1785 		 * raid5-cache write back uses orig_page during prexor.
1786 		 * After prexor, it is time to free orig_page
1787 		 */
1788 		r5c_release_extra_page(sh);
1789 }
1790 
1791 static struct dma_async_tx_descriptor *
1792 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1793 		struct dma_async_tx_descriptor *tx)
1794 {
1795 	int disks = sh->disks;
1796 	struct page **xor_srcs = to_addr_page(percpu, 0);
1797 	unsigned int *off_srcs = to_addr_offs(sh, percpu);
1798 	int count = 0, pd_idx = sh->pd_idx, i;
1799 	struct async_submit_ctl submit;
1800 
1801 	/* existing parity data subtracted */
1802 	unsigned int off_dest = off_srcs[count] = sh->dev[pd_idx].offset;
1803 	struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1804 
1805 	BUG_ON(sh->batch_head);
1806 	pr_debug("%s: stripe %llu\n", __func__,
1807 		(unsigned long long)sh->sector);
1808 
1809 	for (i = disks; i--; ) {
1810 		struct r5dev *dev = &sh->dev[i];
1811 		/* Only process blocks that are known to be uptodate */
1812 		if (test_bit(R5_InJournal, &dev->flags)) {
1813 			/*
1814 			 * For this case, PAGE_SIZE must be equal to 4KB and
1815 			 * page offset is zero.
1816 			 */
1817 			off_srcs[count] = dev->offset;
1818 			xor_srcs[count++] = dev->orig_page;
1819 		} else if (test_bit(R5_Wantdrain, &dev->flags)) {
1820 			off_srcs[count] = dev->offset;
1821 			xor_srcs[count++] = dev->page;
1822 		}
1823 	}
1824 
1825 	init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1826 			  ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1827 	tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
1828 			RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1829 
1830 	return tx;
1831 }
1832 
1833 static struct dma_async_tx_descriptor *
1834 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1835 		struct dma_async_tx_descriptor *tx)
1836 {
1837 	struct page **blocks = to_addr_page(percpu, 0);
1838 	unsigned int *offs = to_addr_offs(sh, percpu);
1839 	int count;
1840 	struct async_submit_ctl submit;
1841 
1842 	pr_debug("%s: stripe %llu\n", __func__,
1843 		(unsigned long long)sh->sector);
1844 
1845 	count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_WANT_DRAIN);
1846 
1847 	init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1848 			  ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1849 	tx = async_gen_syndrome(blocks, offs, count+2,
1850 			RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1851 
1852 	return tx;
1853 }
1854 
1855 static struct dma_async_tx_descriptor *
1856 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1857 {
1858 	struct r5conf *conf = sh->raid_conf;
1859 	int disks = sh->disks;
1860 	int i;
1861 	struct stripe_head *head_sh = sh;
1862 
1863 	pr_debug("%s: stripe %llu\n", __func__,
1864 		(unsigned long long)sh->sector);
1865 
1866 	for (i = disks; i--; ) {
1867 		struct r5dev *dev;
1868 		struct bio *chosen;
1869 
1870 		sh = head_sh;
1871 		if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1872 			struct bio *wbi;
1873 
1874 again:
1875 			dev = &sh->dev[i];
1876 			/*
1877 			 * clear R5_InJournal, so when rewriting a page in
1878 			 * journal, it is not skipped by r5l_log_stripe()
1879 			 */
1880 			clear_bit(R5_InJournal, &dev->flags);
1881 			spin_lock_irq(&sh->stripe_lock);
1882 			chosen = dev->towrite;
1883 			dev->towrite = NULL;
1884 			sh->overwrite_disks = 0;
1885 			BUG_ON(dev->written);
1886 			wbi = dev->written = chosen;
1887 			spin_unlock_irq(&sh->stripe_lock);
1888 			WARN_ON(dev->page != dev->orig_page);
1889 
1890 			while (wbi && wbi->bi_iter.bi_sector <
1891 				dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1892 				if (wbi->bi_opf & REQ_FUA)
1893 					set_bit(R5_WantFUA, &dev->flags);
1894 				if (wbi->bi_opf & REQ_SYNC)
1895 					set_bit(R5_SyncIO, &dev->flags);
1896 				if (bio_op(wbi) == REQ_OP_DISCARD)
1897 					set_bit(R5_Discard, &dev->flags);
1898 				else {
1899 					tx = async_copy_data(1, wbi, &dev->page,
1900 							     dev->offset,
1901 							     dev->sector, tx, sh,
1902 							     r5c_is_writeback(conf->log));
1903 					if (dev->page != dev->orig_page &&
1904 					    !r5c_is_writeback(conf->log)) {
1905 						set_bit(R5_SkipCopy, &dev->flags);
1906 						clear_bit(R5_UPTODATE, &dev->flags);
1907 						clear_bit(R5_OVERWRITE, &dev->flags);
1908 					}
1909 				}
1910 				wbi = r5_next_bio(conf, wbi, dev->sector);
1911 			}
1912 
1913 			if (head_sh->batch_head) {
1914 				sh = list_first_entry(&sh->batch_list,
1915 						      struct stripe_head,
1916 						      batch_list);
1917 				if (sh == head_sh)
1918 					continue;
1919 				goto again;
1920 			}
1921 		}
1922 	}
1923 
1924 	return tx;
1925 }
1926 
1927 static void ops_complete_reconstruct(void *stripe_head_ref)
1928 {
1929 	struct stripe_head *sh = stripe_head_ref;
1930 	int disks = sh->disks;
1931 	int pd_idx = sh->pd_idx;
1932 	int qd_idx = sh->qd_idx;
1933 	int i;
1934 	bool fua = false, sync = false, discard = false;
1935 
1936 	pr_debug("%s: stripe %llu\n", __func__,
1937 		(unsigned long long)sh->sector);
1938 
1939 	for (i = disks; i--; ) {
1940 		fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1941 		sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1942 		discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1943 	}
1944 
1945 	for (i = disks; i--; ) {
1946 		struct r5dev *dev = &sh->dev[i];
1947 
1948 		if (dev->written || i == pd_idx || i == qd_idx) {
1949 			if (!discard && !test_bit(R5_SkipCopy, &dev->flags)) {
1950 				set_bit(R5_UPTODATE, &dev->flags);
1951 				if (test_bit(STRIPE_EXPAND_READY, &sh->state))
1952 					set_bit(R5_Expanded, &dev->flags);
1953 			}
1954 			if (fua)
1955 				set_bit(R5_WantFUA, &dev->flags);
1956 			if (sync)
1957 				set_bit(R5_SyncIO, &dev->flags);
1958 		}
1959 	}
1960 
1961 	if (sh->reconstruct_state == reconstruct_state_drain_run)
1962 		sh->reconstruct_state = reconstruct_state_drain_result;
1963 	else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1964 		sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1965 	else {
1966 		BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1967 		sh->reconstruct_state = reconstruct_state_result;
1968 	}
1969 
1970 	set_bit(STRIPE_HANDLE, &sh->state);
1971 	raid5_release_stripe(sh);
1972 }
1973 
1974 static void
1975 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1976 		     struct dma_async_tx_descriptor *tx)
1977 {
1978 	int disks = sh->disks;
1979 	struct page **xor_srcs;
1980 	unsigned int *off_srcs;
1981 	struct async_submit_ctl submit;
1982 	int count, pd_idx = sh->pd_idx, i;
1983 	struct page *xor_dest;
1984 	unsigned int off_dest;
1985 	int prexor = 0;
1986 	unsigned long flags;
1987 	int j = 0;
1988 	struct stripe_head *head_sh = sh;
1989 	int last_stripe;
1990 
1991 	pr_debug("%s: stripe %llu\n", __func__,
1992 		(unsigned long long)sh->sector);
1993 
1994 	for (i = 0; i < sh->disks; i++) {
1995 		if (pd_idx == i)
1996 			continue;
1997 		if (!test_bit(R5_Discard, &sh->dev[i].flags))
1998 			break;
1999 	}
2000 	if (i >= sh->disks) {
2001 		atomic_inc(&sh->count);
2002 		set_bit(R5_Discard, &sh->dev[pd_idx].flags);
2003 		ops_complete_reconstruct(sh);
2004 		return;
2005 	}
2006 again:
2007 	count = 0;
2008 	xor_srcs = to_addr_page(percpu, j);
2009 	off_srcs = to_addr_offs(sh, percpu);
2010 	/* check if prexor is active which means only process blocks
2011 	 * that are part of a read-modify-write (written)
2012 	 */
2013 	if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
2014 		prexor = 1;
2015 		off_dest = off_srcs[count] = sh->dev[pd_idx].offset;
2016 		xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
2017 		for (i = disks; i--; ) {
2018 			struct r5dev *dev = &sh->dev[i];
2019 			if (head_sh->dev[i].written ||
2020 			    test_bit(R5_InJournal, &head_sh->dev[i].flags)) {
2021 				off_srcs[count] = dev->offset;
2022 				xor_srcs[count++] = dev->page;
2023 			}
2024 		}
2025 	} else {
2026 		xor_dest = sh->dev[pd_idx].page;
2027 		off_dest = sh->dev[pd_idx].offset;
2028 		for (i = disks; i--; ) {
2029 			struct r5dev *dev = &sh->dev[i];
2030 			if (i != pd_idx) {
2031 				off_srcs[count] = dev->offset;
2032 				xor_srcs[count++] = dev->page;
2033 			}
2034 		}
2035 	}
2036 
2037 	/* 1/ if we prexor'd then the dest is reused as a source
2038 	 * 2/ if we did not prexor then we are redoing the parity
2039 	 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
2040 	 * for the synchronous xor case
2041 	 */
2042 	last_stripe = !head_sh->batch_head ||
2043 		list_first_entry(&sh->batch_list,
2044 				 struct stripe_head, batch_list) == head_sh;
2045 	if (last_stripe) {
2046 		flags = ASYNC_TX_ACK |
2047 			(prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
2048 
2049 		atomic_inc(&head_sh->count);
2050 		init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
2051 				  to_addr_conv(sh, percpu, j));
2052 	} else {
2053 		flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
2054 		init_async_submit(&submit, flags, tx, NULL, NULL,
2055 				  to_addr_conv(sh, percpu, j));
2056 	}
2057 
2058 	if (unlikely(count == 1))
2059 		tx = async_memcpy(xor_dest, xor_srcs[0], off_dest, off_srcs[0],
2060 				RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
2061 	else
2062 		tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
2063 				RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
2064 	if (!last_stripe) {
2065 		j++;
2066 		sh = list_first_entry(&sh->batch_list, struct stripe_head,
2067 				      batch_list);
2068 		goto again;
2069 	}
2070 }
2071 
2072 static void
2073 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
2074 		     struct dma_async_tx_descriptor *tx)
2075 {
2076 	struct async_submit_ctl submit;
2077 	struct page **blocks;
2078 	unsigned int *offs;
2079 	int count, i, j = 0;
2080 	struct stripe_head *head_sh = sh;
2081 	int last_stripe;
2082 	int synflags;
2083 	unsigned long txflags;
2084 
2085 	pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
2086 
2087 	for (i = 0; i < sh->disks; i++) {
2088 		if (sh->pd_idx == i || sh->qd_idx == i)
2089 			continue;
2090 		if (!test_bit(R5_Discard, &sh->dev[i].flags))
2091 			break;
2092 	}
2093 	if (i >= sh->disks) {
2094 		atomic_inc(&sh->count);
2095 		set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
2096 		set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
2097 		ops_complete_reconstruct(sh);
2098 		return;
2099 	}
2100 
2101 again:
2102 	blocks = to_addr_page(percpu, j);
2103 	offs = to_addr_offs(sh, percpu);
2104 
2105 	if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
2106 		synflags = SYNDROME_SRC_WRITTEN;
2107 		txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
2108 	} else {
2109 		synflags = SYNDROME_SRC_ALL;
2110 		txflags = ASYNC_TX_ACK;
2111 	}
2112 
2113 	count = set_syndrome_sources(blocks, offs, sh, synflags);
2114 	last_stripe = !head_sh->batch_head ||
2115 		list_first_entry(&sh->batch_list,
2116 				 struct stripe_head, batch_list) == head_sh;
2117 
2118 	if (last_stripe) {
2119 		atomic_inc(&head_sh->count);
2120 		init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
2121 				  head_sh, to_addr_conv(sh, percpu, j));
2122 	} else
2123 		init_async_submit(&submit, 0, tx, NULL, NULL,
2124 				  to_addr_conv(sh, percpu, j));
2125 	tx = async_gen_syndrome(blocks, offs, count+2,
2126 			RAID5_STRIPE_SIZE(sh->raid_conf),  &submit);
2127 	if (!last_stripe) {
2128 		j++;
2129 		sh = list_first_entry(&sh->batch_list, struct stripe_head,
2130 				      batch_list);
2131 		goto again;
2132 	}
2133 }
2134 
2135 static void ops_complete_check(void *stripe_head_ref)
2136 {
2137 	struct stripe_head *sh = stripe_head_ref;
2138 
2139 	pr_debug("%s: stripe %llu\n", __func__,
2140 		(unsigned long long)sh->sector);
2141 
2142 	sh->check_state = check_state_check_result;
2143 	set_bit(STRIPE_HANDLE, &sh->state);
2144 	raid5_release_stripe(sh);
2145 }
2146 
2147 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
2148 {
2149 	int disks = sh->disks;
2150 	int pd_idx = sh->pd_idx;
2151 	int qd_idx = sh->qd_idx;
2152 	struct page *xor_dest;
2153 	unsigned int off_dest;
2154 	struct page **xor_srcs = to_addr_page(percpu, 0);
2155 	unsigned int *off_srcs = to_addr_offs(sh, percpu);
2156 	struct dma_async_tx_descriptor *tx;
2157 	struct async_submit_ctl submit;
2158 	int count;
2159 	int i;
2160 
2161 	pr_debug("%s: stripe %llu\n", __func__,
2162 		(unsigned long long)sh->sector);
2163 
2164 	BUG_ON(sh->batch_head);
2165 	count = 0;
2166 	xor_dest = sh->dev[pd_idx].page;
2167 	off_dest = sh->dev[pd_idx].offset;
2168 	off_srcs[count] = off_dest;
2169 	xor_srcs[count++] = xor_dest;
2170 	for (i = disks; i--; ) {
2171 		if (i == pd_idx || i == qd_idx)
2172 			continue;
2173 		off_srcs[count] = sh->dev[i].offset;
2174 		xor_srcs[count++] = sh->dev[i].page;
2175 	}
2176 
2177 	init_async_submit(&submit, 0, NULL, NULL, NULL,
2178 			  to_addr_conv(sh, percpu, 0));
2179 	tx = async_xor_val_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
2180 			   RAID5_STRIPE_SIZE(sh->raid_conf),
2181 			   &sh->ops.zero_sum_result, &submit);
2182 
2183 	atomic_inc(&sh->count);
2184 	init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
2185 	tx = async_trigger_callback(&submit);
2186 }
2187 
2188 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
2189 {
2190 	struct page **srcs = to_addr_page(percpu, 0);
2191 	unsigned int *offs = to_addr_offs(sh, percpu);
2192 	struct async_submit_ctl submit;
2193 	int count;
2194 
2195 	pr_debug("%s: stripe %llu checkp: %d\n", __func__,
2196 		(unsigned long long)sh->sector, checkp);
2197 
2198 	BUG_ON(sh->batch_head);
2199 	count = set_syndrome_sources(srcs, offs, sh, SYNDROME_SRC_ALL);
2200 	if (!checkp)
2201 		srcs[count] = NULL;
2202 
2203 	atomic_inc(&sh->count);
2204 	init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
2205 			  sh, to_addr_conv(sh, percpu, 0));
2206 	async_syndrome_val(srcs, offs, count+2,
2207 			   RAID5_STRIPE_SIZE(sh->raid_conf),
2208 			   &sh->ops.zero_sum_result, percpu->spare_page, 0, &submit);
2209 }
2210 
2211 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
2212 {
2213 	int overlap_clear = 0, i, disks = sh->disks;
2214 	struct dma_async_tx_descriptor *tx = NULL;
2215 	struct r5conf *conf = sh->raid_conf;
2216 	int level = conf->level;
2217 	struct raid5_percpu *percpu;
2218 	unsigned long cpu;
2219 
2220 	cpu = get_cpu();
2221 	percpu = per_cpu_ptr(conf->percpu, cpu);
2222 	if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
2223 		ops_run_biofill(sh);
2224 		overlap_clear++;
2225 	}
2226 
2227 	if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
2228 		if (level < 6)
2229 			tx = ops_run_compute5(sh, percpu);
2230 		else {
2231 			if (sh->ops.target2 < 0 || sh->ops.target < 0)
2232 				tx = ops_run_compute6_1(sh, percpu);
2233 			else
2234 				tx = ops_run_compute6_2(sh, percpu);
2235 		}
2236 		/* terminate the chain if reconstruct is not set to be run */
2237 		if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
2238 			async_tx_ack(tx);
2239 	}
2240 
2241 	if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
2242 		if (level < 6)
2243 			tx = ops_run_prexor5(sh, percpu, tx);
2244 		else
2245 			tx = ops_run_prexor6(sh, percpu, tx);
2246 	}
2247 
2248 	if (test_bit(STRIPE_OP_PARTIAL_PARITY, &ops_request))
2249 		tx = ops_run_partial_parity(sh, percpu, tx);
2250 
2251 	if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
2252 		tx = ops_run_biodrain(sh, tx);
2253 		overlap_clear++;
2254 	}
2255 
2256 	if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
2257 		if (level < 6)
2258 			ops_run_reconstruct5(sh, percpu, tx);
2259 		else
2260 			ops_run_reconstruct6(sh, percpu, tx);
2261 	}
2262 
2263 	if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
2264 		if (sh->check_state == check_state_run)
2265 			ops_run_check_p(sh, percpu);
2266 		else if (sh->check_state == check_state_run_q)
2267 			ops_run_check_pq(sh, percpu, 0);
2268 		else if (sh->check_state == check_state_run_pq)
2269 			ops_run_check_pq(sh, percpu, 1);
2270 		else
2271 			BUG();
2272 	}
2273 
2274 	if (overlap_clear && !sh->batch_head)
2275 		for (i = disks; i--; ) {
2276 			struct r5dev *dev = &sh->dev[i];
2277 			if (test_and_clear_bit(R5_Overlap, &dev->flags))
2278 				wake_up(&sh->raid_conf->wait_for_overlap);
2279 		}
2280 	put_cpu();
2281 }
2282 
2283 static void free_stripe(struct kmem_cache *sc, struct stripe_head *sh)
2284 {
2285 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2286 	kfree(sh->pages);
2287 #endif
2288 	if (sh->ppl_page)
2289 		__free_page(sh->ppl_page);
2290 	kmem_cache_free(sc, sh);
2291 }
2292 
2293 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp,
2294 	int disks, struct r5conf *conf)
2295 {
2296 	struct stripe_head *sh;
2297 	int i;
2298 
2299 	sh = kmem_cache_zalloc(sc, gfp);
2300 	if (sh) {
2301 		spin_lock_init(&sh->stripe_lock);
2302 		spin_lock_init(&sh->batch_lock);
2303 		INIT_LIST_HEAD(&sh->batch_list);
2304 		INIT_LIST_HEAD(&sh->lru);
2305 		INIT_LIST_HEAD(&sh->r5c);
2306 		INIT_LIST_HEAD(&sh->log_list);
2307 		atomic_set(&sh->count, 1);
2308 		sh->raid_conf = conf;
2309 		sh->log_start = MaxSector;
2310 		for (i = 0; i < disks; i++) {
2311 			struct r5dev *dev = &sh->dev[i];
2312 
2313 			bio_init(&dev->req, &dev->vec, 1);
2314 			bio_init(&dev->rreq, &dev->rvec, 1);
2315 		}
2316 
2317 		if (raid5_has_ppl(conf)) {
2318 			sh->ppl_page = alloc_page(gfp);
2319 			if (!sh->ppl_page) {
2320 				free_stripe(sc, sh);
2321 				return NULL;
2322 			}
2323 		}
2324 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2325 		if (init_stripe_shared_pages(sh, conf, disks)) {
2326 			free_stripe(sc, sh);
2327 			return NULL;
2328 		}
2329 #endif
2330 	}
2331 	return sh;
2332 }
2333 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2334 {
2335 	struct stripe_head *sh;
2336 
2337 	sh = alloc_stripe(conf->slab_cache, gfp, conf->pool_size, conf);
2338 	if (!sh)
2339 		return 0;
2340 
2341 	if (grow_buffers(sh, gfp)) {
2342 		shrink_buffers(sh);
2343 		free_stripe(conf->slab_cache, sh);
2344 		return 0;
2345 	}
2346 	sh->hash_lock_index =
2347 		conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2348 	/* we just created an active stripe so... */
2349 	atomic_inc(&conf->active_stripes);
2350 
2351 	raid5_release_stripe(sh);
2352 	conf->max_nr_stripes++;
2353 	return 1;
2354 }
2355 
2356 static int grow_stripes(struct r5conf *conf, int num)
2357 {
2358 	struct kmem_cache *sc;
2359 	size_t namelen = sizeof(conf->cache_name[0]);
2360 	int devs = max(conf->raid_disks, conf->previous_raid_disks);
2361 
2362 	if (conf->mddev->gendisk)
2363 		snprintf(conf->cache_name[0], namelen,
2364 			"raid%d-%s", conf->level, mdname(conf->mddev));
2365 	else
2366 		snprintf(conf->cache_name[0], namelen,
2367 			"raid%d-%p", conf->level, conf->mddev);
2368 	snprintf(conf->cache_name[1], namelen, "%.27s-alt", conf->cache_name[0]);
2369 
2370 	conf->active_name = 0;
2371 	sc = kmem_cache_create(conf->cache_name[conf->active_name],
2372 			       sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2373 			       0, 0, NULL);
2374 	if (!sc)
2375 		return 1;
2376 	conf->slab_cache = sc;
2377 	conf->pool_size = devs;
2378 	while (num--)
2379 		if (!grow_one_stripe(conf, GFP_KERNEL))
2380 			return 1;
2381 
2382 	return 0;
2383 }
2384 
2385 /**
2386  * scribble_alloc - allocate percpu scribble buffer for required size
2387  *		    of the scribble region
2388  * @percpu: from for_each_present_cpu() of the caller
2389  * @num: total number of disks in the array
2390  * @cnt: scribble objs count for required size of the scribble region
2391  *
2392  * The scribble buffer size must be enough to contain:
2393  * 1/ a struct page pointer for each device in the array +2
2394  * 2/ room to convert each entry in (1) to its corresponding dma
2395  *    (dma_map_page()) or page (page_address()) address.
2396  *
2397  * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2398  * calculate over all devices (not just the data blocks), using zeros in place
2399  * of the P and Q blocks.
2400  */
2401 static int scribble_alloc(struct raid5_percpu *percpu,
2402 			  int num, int cnt)
2403 {
2404 	size_t obj_size =
2405 		sizeof(struct page *) * (num + 2) +
2406 		sizeof(addr_conv_t) * (num + 2) +
2407 		sizeof(unsigned int) * (num + 2);
2408 	void *scribble;
2409 
2410 	/*
2411 	 * If here is in raid array suspend context, it is in memalloc noio
2412 	 * context as well, there is no potential recursive memory reclaim
2413 	 * I/Os with the GFP_KERNEL flag.
2414 	 */
2415 	scribble = kvmalloc_array(cnt, obj_size, GFP_KERNEL);
2416 	if (!scribble)
2417 		return -ENOMEM;
2418 
2419 	kvfree(percpu->scribble);
2420 
2421 	percpu->scribble = scribble;
2422 	percpu->scribble_obj_size = obj_size;
2423 	return 0;
2424 }
2425 
2426 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2427 {
2428 	unsigned long cpu;
2429 	int err = 0;
2430 
2431 	/*
2432 	 * Never shrink. And mddev_suspend() could deadlock if this is called
2433 	 * from raid5d. In that case, scribble_disks and scribble_sectors
2434 	 * should equal to new_disks and new_sectors
2435 	 */
2436 	if (conf->scribble_disks >= new_disks &&
2437 	    conf->scribble_sectors >= new_sectors)
2438 		return 0;
2439 	mddev_suspend(conf->mddev);
2440 	get_online_cpus();
2441 
2442 	for_each_present_cpu(cpu) {
2443 		struct raid5_percpu *percpu;
2444 
2445 		percpu = per_cpu_ptr(conf->percpu, cpu);
2446 		err = scribble_alloc(percpu, new_disks,
2447 				     new_sectors / RAID5_STRIPE_SECTORS(conf));
2448 		if (err)
2449 			break;
2450 	}
2451 
2452 	put_online_cpus();
2453 	mddev_resume(conf->mddev);
2454 	if (!err) {
2455 		conf->scribble_disks = new_disks;
2456 		conf->scribble_sectors = new_sectors;
2457 	}
2458 	return err;
2459 }
2460 
2461 static int resize_stripes(struct r5conf *conf, int newsize)
2462 {
2463 	/* Make all the stripes able to hold 'newsize' devices.
2464 	 * New slots in each stripe get 'page' set to a new page.
2465 	 *
2466 	 * This happens in stages:
2467 	 * 1/ create a new kmem_cache and allocate the required number of
2468 	 *    stripe_heads.
2469 	 * 2/ gather all the old stripe_heads and transfer the pages across
2470 	 *    to the new stripe_heads.  This will have the side effect of
2471 	 *    freezing the array as once all stripe_heads have been collected,
2472 	 *    no IO will be possible.  Old stripe heads are freed once their
2473 	 *    pages have been transferred over, and the old kmem_cache is
2474 	 *    freed when all stripes are done.
2475 	 * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
2476 	 *    we simple return a failure status - no need to clean anything up.
2477 	 * 4/ allocate new pages for the new slots in the new stripe_heads.
2478 	 *    If this fails, we don't bother trying the shrink the
2479 	 *    stripe_heads down again, we just leave them as they are.
2480 	 *    As each stripe_head is processed the new one is released into
2481 	 *    active service.
2482 	 *
2483 	 * Once step2 is started, we cannot afford to wait for a write,
2484 	 * so we use GFP_NOIO allocations.
2485 	 */
2486 	struct stripe_head *osh, *nsh;
2487 	LIST_HEAD(newstripes);
2488 	struct disk_info *ndisks;
2489 	int err = 0;
2490 	struct kmem_cache *sc;
2491 	int i;
2492 	int hash, cnt;
2493 
2494 	md_allow_write(conf->mddev);
2495 
2496 	/* Step 1 */
2497 	sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2498 			       sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2499 			       0, 0, NULL);
2500 	if (!sc)
2501 		return -ENOMEM;
2502 
2503 	/* Need to ensure auto-resizing doesn't interfere */
2504 	mutex_lock(&conf->cache_size_mutex);
2505 
2506 	for (i = conf->max_nr_stripes; i; i--) {
2507 		nsh = alloc_stripe(sc, GFP_KERNEL, newsize, conf);
2508 		if (!nsh)
2509 			break;
2510 
2511 		list_add(&nsh->lru, &newstripes);
2512 	}
2513 	if (i) {
2514 		/* didn't get enough, give up */
2515 		while (!list_empty(&newstripes)) {
2516 			nsh = list_entry(newstripes.next, struct stripe_head, lru);
2517 			list_del(&nsh->lru);
2518 			free_stripe(sc, nsh);
2519 		}
2520 		kmem_cache_destroy(sc);
2521 		mutex_unlock(&conf->cache_size_mutex);
2522 		return -ENOMEM;
2523 	}
2524 	/* Step 2 - Must use GFP_NOIO now.
2525 	 * OK, we have enough stripes, start collecting inactive
2526 	 * stripes and copying them over
2527 	 */
2528 	hash = 0;
2529 	cnt = 0;
2530 	list_for_each_entry(nsh, &newstripes, lru) {
2531 		lock_device_hash_lock(conf, hash);
2532 		wait_event_cmd(conf->wait_for_stripe,
2533 				    !list_empty(conf->inactive_list + hash),
2534 				    unlock_device_hash_lock(conf, hash),
2535 				    lock_device_hash_lock(conf, hash));
2536 		osh = get_free_stripe(conf, hash);
2537 		unlock_device_hash_lock(conf, hash);
2538 
2539 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2540 	for (i = 0; i < osh->nr_pages; i++) {
2541 		nsh->pages[i] = osh->pages[i];
2542 		osh->pages[i] = NULL;
2543 	}
2544 #endif
2545 		for(i=0; i<conf->pool_size; i++) {
2546 			nsh->dev[i].page = osh->dev[i].page;
2547 			nsh->dev[i].orig_page = osh->dev[i].page;
2548 			nsh->dev[i].offset = osh->dev[i].offset;
2549 		}
2550 		nsh->hash_lock_index = hash;
2551 		free_stripe(conf->slab_cache, osh);
2552 		cnt++;
2553 		if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2554 		    !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2555 			hash++;
2556 			cnt = 0;
2557 		}
2558 	}
2559 	kmem_cache_destroy(conf->slab_cache);
2560 
2561 	/* Step 3.
2562 	 * At this point, we are holding all the stripes so the array
2563 	 * is completely stalled, so now is a good time to resize
2564 	 * conf->disks and the scribble region
2565 	 */
2566 	ndisks = kcalloc(newsize, sizeof(struct disk_info), GFP_NOIO);
2567 	if (ndisks) {
2568 		for (i = 0; i < conf->pool_size; i++)
2569 			ndisks[i] = conf->disks[i];
2570 
2571 		for (i = conf->pool_size; i < newsize; i++) {
2572 			ndisks[i].extra_page = alloc_page(GFP_NOIO);
2573 			if (!ndisks[i].extra_page)
2574 				err = -ENOMEM;
2575 		}
2576 
2577 		if (err) {
2578 			for (i = conf->pool_size; i < newsize; i++)
2579 				if (ndisks[i].extra_page)
2580 					put_page(ndisks[i].extra_page);
2581 			kfree(ndisks);
2582 		} else {
2583 			kfree(conf->disks);
2584 			conf->disks = ndisks;
2585 		}
2586 	} else
2587 		err = -ENOMEM;
2588 
2589 	conf->slab_cache = sc;
2590 	conf->active_name = 1-conf->active_name;
2591 
2592 	/* Step 4, return new stripes to service */
2593 	while(!list_empty(&newstripes)) {
2594 		nsh = list_entry(newstripes.next, struct stripe_head, lru);
2595 		list_del_init(&nsh->lru);
2596 
2597 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2598 		for (i = 0; i < nsh->nr_pages; i++) {
2599 			if (nsh->pages[i])
2600 				continue;
2601 			nsh->pages[i] = alloc_page(GFP_NOIO);
2602 			if (!nsh->pages[i])
2603 				err = -ENOMEM;
2604 		}
2605 
2606 		for (i = conf->raid_disks; i < newsize; i++) {
2607 			if (nsh->dev[i].page)
2608 				continue;
2609 			nsh->dev[i].page = raid5_get_dev_page(nsh, i);
2610 			nsh->dev[i].orig_page = nsh->dev[i].page;
2611 			nsh->dev[i].offset = raid5_get_page_offset(nsh, i);
2612 		}
2613 #else
2614 		for (i=conf->raid_disks; i < newsize; i++)
2615 			if (nsh->dev[i].page == NULL) {
2616 				struct page *p = alloc_page(GFP_NOIO);
2617 				nsh->dev[i].page = p;
2618 				nsh->dev[i].orig_page = p;
2619 				nsh->dev[i].offset = 0;
2620 				if (!p)
2621 					err = -ENOMEM;
2622 			}
2623 #endif
2624 		raid5_release_stripe(nsh);
2625 	}
2626 	/* critical section pass, GFP_NOIO no longer needed */
2627 
2628 	if (!err)
2629 		conf->pool_size = newsize;
2630 	mutex_unlock(&conf->cache_size_mutex);
2631 
2632 	return err;
2633 }
2634 
2635 static int drop_one_stripe(struct r5conf *conf)
2636 {
2637 	struct stripe_head *sh;
2638 	int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2639 
2640 	spin_lock_irq(conf->hash_locks + hash);
2641 	sh = get_free_stripe(conf, hash);
2642 	spin_unlock_irq(conf->hash_locks + hash);
2643 	if (!sh)
2644 		return 0;
2645 	BUG_ON(atomic_read(&sh->count));
2646 	shrink_buffers(sh);
2647 	free_stripe(conf->slab_cache, sh);
2648 	atomic_dec(&conf->active_stripes);
2649 	conf->max_nr_stripes--;
2650 	return 1;
2651 }
2652 
2653 static void shrink_stripes(struct r5conf *conf)
2654 {
2655 	while (conf->max_nr_stripes &&
2656 	       drop_one_stripe(conf))
2657 		;
2658 
2659 	kmem_cache_destroy(conf->slab_cache);
2660 	conf->slab_cache = NULL;
2661 }
2662 
2663 static void raid5_end_read_request(struct bio * bi)
2664 {
2665 	struct stripe_head *sh = bi->bi_private;
2666 	struct r5conf *conf = sh->raid_conf;
2667 	int disks = sh->disks, i;
2668 	char b[BDEVNAME_SIZE];
2669 	struct md_rdev *rdev = NULL;
2670 	sector_t s;
2671 
2672 	for (i=0 ; i<disks; i++)
2673 		if (bi == &sh->dev[i].req)
2674 			break;
2675 
2676 	pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2677 		(unsigned long long)sh->sector, i, atomic_read(&sh->count),
2678 		bi->bi_status);
2679 	if (i == disks) {
2680 		bio_reset(bi);
2681 		BUG();
2682 		return;
2683 	}
2684 	if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2685 		/* If replacement finished while this request was outstanding,
2686 		 * 'replacement' might be NULL already.
2687 		 * In that case it moved down to 'rdev'.
2688 		 * rdev is not removed until all requests are finished.
2689 		 */
2690 		rdev = conf->disks[i].replacement;
2691 	if (!rdev)
2692 		rdev = conf->disks[i].rdev;
2693 
2694 	if (use_new_offset(conf, sh))
2695 		s = sh->sector + rdev->new_data_offset;
2696 	else
2697 		s = sh->sector + rdev->data_offset;
2698 	if (!bi->bi_status) {
2699 		set_bit(R5_UPTODATE, &sh->dev[i].flags);
2700 		if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2701 			/* Note that this cannot happen on a
2702 			 * replacement device.  We just fail those on
2703 			 * any error
2704 			 */
2705 			pr_info_ratelimited(
2706 				"md/raid:%s: read error corrected (%lu sectors at %llu on %s)\n",
2707 				mdname(conf->mddev), RAID5_STRIPE_SECTORS(conf),
2708 				(unsigned long long)s,
2709 				bdevname(rdev->bdev, b));
2710 			atomic_add(RAID5_STRIPE_SECTORS(conf), &rdev->corrected_errors);
2711 			clear_bit(R5_ReadError, &sh->dev[i].flags);
2712 			clear_bit(R5_ReWrite, &sh->dev[i].flags);
2713 		} else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2714 			clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2715 
2716 		if (test_bit(R5_InJournal, &sh->dev[i].flags))
2717 			/*
2718 			 * end read for a page in journal, this
2719 			 * must be preparing for prexor in rmw
2720 			 */
2721 			set_bit(R5_OrigPageUPTDODATE, &sh->dev[i].flags);
2722 
2723 		if (atomic_read(&rdev->read_errors))
2724 			atomic_set(&rdev->read_errors, 0);
2725 	} else {
2726 		const char *bdn = bdevname(rdev->bdev, b);
2727 		int retry = 0;
2728 		int set_bad = 0;
2729 
2730 		clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2731 		if (!(bi->bi_status == BLK_STS_PROTECTION))
2732 			atomic_inc(&rdev->read_errors);
2733 		if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2734 			pr_warn_ratelimited(
2735 				"md/raid:%s: read error on replacement device (sector %llu on %s).\n",
2736 				mdname(conf->mddev),
2737 				(unsigned long long)s,
2738 				bdn);
2739 		else if (conf->mddev->degraded >= conf->max_degraded) {
2740 			set_bad = 1;
2741 			pr_warn_ratelimited(
2742 				"md/raid:%s: read error not correctable (sector %llu on %s).\n",
2743 				mdname(conf->mddev),
2744 				(unsigned long long)s,
2745 				bdn);
2746 		} else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2747 			/* Oh, no!!! */
2748 			set_bad = 1;
2749 			pr_warn_ratelimited(
2750 				"md/raid:%s: read error NOT corrected!! (sector %llu on %s).\n",
2751 				mdname(conf->mddev),
2752 				(unsigned long long)s,
2753 				bdn);
2754 		} else if (atomic_read(&rdev->read_errors)
2755 			 > conf->max_nr_stripes) {
2756 			if (!test_bit(Faulty, &rdev->flags)) {
2757 				pr_warn("md/raid:%s: %d read_errors > %d stripes\n",
2758 				    mdname(conf->mddev),
2759 				    atomic_read(&rdev->read_errors),
2760 				    conf->max_nr_stripes);
2761 				pr_warn("md/raid:%s: Too many read errors, failing device %s.\n",
2762 				    mdname(conf->mddev), bdn);
2763 			}
2764 		} else
2765 			retry = 1;
2766 		if (set_bad && test_bit(In_sync, &rdev->flags)
2767 		    && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2768 			retry = 1;
2769 		if (retry)
2770 			if (sh->qd_idx >= 0 && sh->pd_idx == i)
2771 				set_bit(R5_ReadError, &sh->dev[i].flags);
2772 			else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2773 				set_bit(R5_ReadError, &sh->dev[i].flags);
2774 				clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2775 			} else
2776 				set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2777 		else {
2778 			clear_bit(R5_ReadError, &sh->dev[i].flags);
2779 			clear_bit(R5_ReWrite, &sh->dev[i].flags);
2780 			if (!(set_bad
2781 			      && test_bit(In_sync, &rdev->flags)
2782 			      && rdev_set_badblocks(
2783 				      rdev, sh->sector, RAID5_STRIPE_SECTORS(conf), 0)))
2784 				md_error(conf->mddev, rdev);
2785 		}
2786 	}
2787 	rdev_dec_pending(rdev, conf->mddev);
2788 	bio_reset(bi);
2789 	clear_bit(R5_LOCKED, &sh->dev[i].flags);
2790 	set_bit(STRIPE_HANDLE, &sh->state);
2791 	raid5_release_stripe(sh);
2792 }
2793 
2794 static void raid5_end_write_request(struct bio *bi)
2795 {
2796 	struct stripe_head *sh = bi->bi_private;
2797 	struct r5conf *conf = sh->raid_conf;
2798 	int disks = sh->disks, i;
2799 	struct md_rdev *rdev;
2800 	sector_t first_bad;
2801 	int bad_sectors;
2802 	int replacement = 0;
2803 
2804 	for (i = 0 ; i < disks; i++) {
2805 		if (bi == &sh->dev[i].req) {
2806 			rdev = conf->disks[i].rdev;
2807 			break;
2808 		}
2809 		if (bi == &sh->dev[i].rreq) {
2810 			rdev = conf->disks[i].replacement;
2811 			if (rdev)
2812 				replacement = 1;
2813 			else
2814 				/* rdev was removed and 'replacement'
2815 				 * replaced it.  rdev is not removed
2816 				 * until all requests are finished.
2817 				 */
2818 				rdev = conf->disks[i].rdev;
2819 			break;
2820 		}
2821 	}
2822 	pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2823 		(unsigned long long)sh->sector, i, atomic_read(&sh->count),
2824 		bi->bi_status);
2825 	if (i == disks) {
2826 		bio_reset(bi);
2827 		BUG();
2828 		return;
2829 	}
2830 
2831 	if (replacement) {
2832 		if (bi->bi_status)
2833 			md_error(conf->mddev, rdev);
2834 		else if (is_badblock(rdev, sh->sector,
2835 				     RAID5_STRIPE_SECTORS(conf),
2836 				     &first_bad, &bad_sectors))
2837 			set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2838 	} else {
2839 		if (bi->bi_status) {
2840 			set_bit(STRIPE_DEGRADED, &sh->state);
2841 			set_bit(WriteErrorSeen, &rdev->flags);
2842 			set_bit(R5_WriteError, &sh->dev[i].flags);
2843 			if (!test_and_set_bit(WantReplacement, &rdev->flags))
2844 				set_bit(MD_RECOVERY_NEEDED,
2845 					&rdev->mddev->recovery);
2846 		} else if (is_badblock(rdev, sh->sector,
2847 				       RAID5_STRIPE_SECTORS(conf),
2848 				       &first_bad, &bad_sectors)) {
2849 			set_bit(R5_MadeGood, &sh->dev[i].flags);
2850 			if (test_bit(R5_ReadError, &sh->dev[i].flags))
2851 				/* That was a successful write so make
2852 				 * sure it looks like we already did
2853 				 * a re-write.
2854 				 */
2855 				set_bit(R5_ReWrite, &sh->dev[i].flags);
2856 		}
2857 	}
2858 	rdev_dec_pending(rdev, conf->mddev);
2859 
2860 	if (sh->batch_head && bi->bi_status && !replacement)
2861 		set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2862 
2863 	bio_reset(bi);
2864 	if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2865 		clear_bit(R5_LOCKED, &sh->dev[i].flags);
2866 	set_bit(STRIPE_HANDLE, &sh->state);
2867 	raid5_release_stripe(sh);
2868 
2869 	if (sh->batch_head && sh != sh->batch_head)
2870 		raid5_release_stripe(sh->batch_head);
2871 }
2872 
2873 static void raid5_error(struct mddev *mddev, struct md_rdev *rdev)
2874 {
2875 	char b[BDEVNAME_SIZE];
2876 	struct r5conf *conf = mddev->private;
2877 	unsigned long flags;
2878 	pr_debug("raid456: error called\n");
2879 
2880 	spin_lock_irqsave(&conf->device_lock, flags);
2881 
2882 	if (test_bit(In_sync, &rdev->flags) &&
2883 	    mddev->degraded == conf->max_degraded) {
2884 		/*
2885 		 * Don't allow to achieve failed state
2886 		 * Don't try to recover this device
2887 		 */
2888 		conf->recovery_disabled = mddev->recovery_disabled;
2889 		spin_unlock_irqrestore(&conf->device_lock, flags);
2890 		return;
2891 	}
2892 
2893 	set_bit(Faulty, &rdev->flags);
2894 	clear_bit(In_sync, &rdev->flags);
2895 	mddev->degraded = raid5_calc_degraded(conf);
2896 	spin_unlock_irqrestore(&conf->device_lock, flags);
2897 	set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2898 
2899 	set_bit(Blocked, &rdev->flags);
2900 	set_mask_bits(&mddev->sb_flags, 0,
2901 		      BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
2902 	pr_crit("md/raid:%s: Disk failure on %s, disabling device.\n"
2903 		"md/raid:%s: Operation continuing on %d devices.\n",
2904 		mdname(mddev),
2905 		bdevname(rdev->bdev, b),
2906 		mdname(mddev),
2907 		conf->raid_disks - mddev->degraded);
2908 	r5c_update_on_rdev_error(mddev, rdev);
2909 }
2910 
2911 /*
2912  * Input: a 'big' sector number,
2913  * Output: index of the data and parity disk, and the sector # in them.
2914  */
2915 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2916 			      int previous, int *dd_idx,
2917 			      struct stripe_head *sh)
2918 {
2919 	sector_t stripe, stripe2;
2920 	sector_t chunk_number;
2921 	unsigned int chunk_offset;
2922 	int pd_idx, qd_idx;
2923 	int ddf_layout = 0;
2924 	sector_t new_sector;
2925 	int algorithm = previous ? conf->prev_algo
2926 				 : conf->algorithm;
2927 	int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2928 					 : conf->chunk_sectors;
2929 	int raid_disks = previous ? conf->previous_raid_disks
2930 				  : conf->raid_disks;
2931 	int data_disks = raid_disks - conf->max_degraded;
2932 
2933 	/* First compute the information on this sector */
2934 
2935 	/*
2936 	 * Compute the chunk number and the sector offset inside the chunk
2937 	 */
2938 	chunk_offset = sector_div(r_sector, sectors_per_chunk);
2939 	chunk_number = r_sector;
2940 
2941 	/*
2942 	 * Compute the stripe number
2943 	 */
2944 	stripe = chunk_number;
2945 	*dd_idx = sector_div(stripe, data_disks);
2946 	stripe2 = stripe;
2947 	/*
2948 	 * Select the parity disk based on the user selected algorithm.
2949 	 */
2950 	pd_idx = qd_idx = -1;
2951 	switch(conf->level) {
2952 	case 4:
2953 		pd_idx = data_disks;
2954 		break;
2955 	case 5:
2956 		switch (algorithm) {
2957 		case ALGORITHM_LEFT_ASYMMETRIC:
2958 			pd_idx = data_disks - sector_div(stripe2, raid_disks);
2959 			if (*dd_idx >= pd_idx)
2960 				(*dd_idx)++;
2961 			break;
2962 		case ALGORITHM_RIGHT_ASYMMETRIC:
2963 			pd_idx = sector_div(stripe2, raid_disks);
2964 			if (*dd_idx >= pd_idx)
2965 				(*dd_idx)++;
2966 			break;
2967 		case ALGORITHM_LEFT_SYMMETRIC:
2968 			pd_idx = data_disks - sector_div(stripe2, raid_disks);
2969 			*dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2970 			break;
2971 		case ALGORITHM_RIGHT_SYMMETRIC:
2972 			pd_idx = sector_div(stripe2, raid_disks);
2973 			*dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2974 			break;
2975 		case ALGORITHM_PARITY_0:
2976 			pd_idx = 0;
2977 			(*dd_idx)++;
2978 			break;
2979 		case ALGORITHM_PARITY_N:
2980 			pd_idx = data_disks;
2981 			break;
2982 		default:
2983 			BUG();
2984 		}
2985 		break;
2986 	case 6:
2987 
2988 		switch (algorithm) {
2989 		case ALGORITHM_LEFT_ASYMMETRIC:
2990 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2991 			qd_idx = pd_idx + 1;
2992 			if (pd_idx == raid_disks-1) {
2993 				(*dd_idx)++;	/* Q D D D P */
2994 				qd_idx = 0;
2995 			} else if (*dd_idx >= pd_idx)
2996 				(*dd_idx) += 2; /* D D P Q D */
2997 			break;
2998 		case ALGORITHM_RIGHT_ASYMMETRIC:
2999 			pd_idx = sector_div(stripe2, raid_disks);
3000 			qd_idx = pd_idx + 1;
3001 			if (pd_idx == raid_disks-1) {
3002 				(*dd_idx)++;	/* Q D D D P */
3003 				qd_idx = 0;
3004 			} else if (*dd_idx >= pd_idx)
3005 				(*dd_idx) += 2; /* D D P Q D */
3006 			break;
3007 		case ALGORITHM_LEFT_SYMMETRIC:
3008 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3009 			qd_idx = (pd_idx + 1) % raid_disks;
3010 			*dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
3011 			break;
3012 		case ALGORITHM_RIGHT_SYMMETRIC:
3013 			pd_idx = sector_div(stripe2, raid_disks);
3014 			qd_idx = (pd_idx + 1) % raid_disks;
3015 			*dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
3016 			break;
3017 
3018 		case ALGORITHM_PARITY_0:
3019 			pd_idx = 0;
3020 			qd_idx = 1;
3021 			(*dd_idx) += 2;
3022 			break;
3023 		case ALGORITHM_PARITY_N:
3024 			pd_idx = data_disks;
3025 			qd_idx = data_disks + 1;
3026 			break;
3027 
3028 		case ALGORITHM_ROTATING_ZERO_RESTART:
3029 			/* Exactly the same as RIGHT_ASYMMETRIC, but or
3030 			 * of blocks for computing Q is different.
3031 			 */
3032 			pd_idx = sector_div(stripe2, raid_disks);
3033 			qd_idx = pd_idx + 1;
3034 			if (pd_idx == raid_disks-1) {
3035 				(*dd_idx)++;	/* Q D D D P */
3036 				qd_idx = 0;
3037 			} else if (*dd_idx >= pd_idx)
3038 				(*dd_idx) += 2; /* D D P Q D */
3039 			ddf_layout = 1;
3040 			break;
3041 
3042 		case ALGORITHM_ROTATING_N_RESTART:
3043 			/* Same a left_asymmetric, by first stripe is
3044 			 * D D D P Q  rather than
3045 			 * Q D D D P
3046 			 */
3047 			stripe2 += 1;
3048 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3049 			qd_idx = pd_idx + 1;
3050 			if (pd_idx == raid_disks-1) {
3051 				(*dd_idx)++;	/* Q D D D P */
3052 				qd_idx = 0;
3053 			} else if (*dd_idx >= pd_idx)
3054 				(*dd_idx) += 2; /* D D P Q D */
3055 			ddf_layout = 1;
3056 			break;
3057 
3058 		case ALGORITHM_ROTATING_N_CONTINUE:
3059 			/* Same as left_symmetric but Q is before P */
3060 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3061 			qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
3062 			*dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
3063 			ddf_layout = 1;
3064 			break;
3065 
3066 		case ALGORITHM_LEFT_ASYMMETRIC_6:
3067 			/* RAID5 left_asymmetric, with Q on last device */
3068 			pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
3069 			if (*dd_idx >= pd_idx)
3070 				(*dd_idx)++;
3071 			qd_idx = raid_disks - 1;
3072 			break;
3073 
3074 		case ALGORITHM_RIGHT_ASYMMETRIC_6:
3075 			pd_idx = sector_div(stripe2, raid_disks-1);
3076 			if (*dd_idx >= pd_idx)
3077 				(*dd_idx)++;
3078 			qd_idx = raid_disks - 1;
3079 			break;
3080 
3081 		case ALGORITHM_LEFT_SYMMETRIC_6:
3082 			pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
3083 			*dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
3084 			qd_idx = raid_disks - 1;
3085 			break;
3086 
3087 		case ALGORITHM_RIGHT_SYMMETRIC_6:
3088 			pd_idx = sector_div(stripe2, raid_disks-1);
3089 			*dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
3090 			qd_idx = raid_disks - 1;
3091 			break;
3092 
3093 		case ALGORITHM_PARITY_0_6:
3094 			pd_idx = 0;
3095 			(*dd_idx)++;
3096 			qd_idx = raid_disks - 1;
3097 			break;
3098 
3099 		default:
3100 			BUG();
3101 		}
3102 		break;
3103 	}
3104 
3105 	if (sh) {
3106 		sh->pd_idx = pd_idx;
3107 		sh->qd_idx = qd_idx;
3108 		sh->ddf_layout = ddf_layout;
3109 	}
3110 	/*
3111 	 * Finally, compute the new sector number
3112 	 */
3113 	new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
3114 	return new_sector;
3115 }
3116 
3117 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
3118 {
3119 	struct r5conf *conf = sh->raid_conf;
3120 	int raid_disks = sh->disks;
3121 	int data_disks = raid_disks - conf->max_degraded;
3122 	sector_t new_sector = sh->sector, check;
3123 	int sectors_per_chunk = previous ? conf->prev_chunk_sectors
3124 					 : conf->chunk_sectors;
3125 	int algorithm = previous ? conf->prev_algo
3126 				 : conf->algorithm;
3127 	sector_t stripe;
3128 	int chunk_offset;
3129 	sector_t chunk_number;
3130 	int dummy1, dd_idx = i;
3131 	sector_t r_sector;
3132 	struct stripe_head sh2;
3133 
3134 	chunk_offset = sector_div(new_sector, sectors_per_chunk);
3135 	stripe = new_sector;
3136 
3137 	if (i == sh->pd_idx)
3138 		return 0;
3139 	switch(conf->level) {
3140 	case 4: break;
3141 	case 5:
3142 		switch (algorithm) {
3143 		case ALGORITHM_LEFT_ASYMMETRIC:
3144 		case ALGORITHM_RIGHT_ASYMMETRIC:
3145 			if (i > sh->pd_idx)
3146 				i--;
3147 			break;
3148 		case ALGORITHM_LEFT_SYMMETRIC:
3149 		case ALGORITHM_RIGHT_SYMMETRIC:
3150 			if (i < sh->pd_idx)
3151 				i += raid_disks;
3152 			i -= (sh->pd_idx + 1);
3153 			break;
3154 		case ALGORITHM_PARITY_0:
3155 			i -= 1;
3156 			break;
3157 		case ALGORITHM_PARITY_N:
3158 			break;
3159 		default:
3160 			BUG();
3161 		}
3162 		break;
3163 	case 6:
3164 		if (i == sh->qd_idx)
3165 			return 0; /* It is the Q disk */
3166 		switch (algorithm) {
3167 		case ALGORITHM_LEFT_ASYMMETRIC:
3168 		case ALGORITHM_RIGHT_ASYMMETRIC:
3169 		case ALGORITHM_ROTATING_ZERO_RESTART:
3170 		case ALGORITHM_ROTATING_N_RESTART:
3171 			if (sh->pd_idx == raid_disks-1)
3172 				i--;	/* Q D D D P */
3173 			else if (i > sh->pd_idx)
3174 				i -= 2; /* D D P Q D */
3175 			break;
3176 		case ALGORITHM_LEFT_SYMMETRIC:
3177 		case ALGORITHM_RIGHT_SYMMETRIC:
3178 			if (sh->pd_idx == raid_disks-1)
3179 				i--; /* Q D D D P */
3180 			else {
3181 				/* D D P Q D */
3182 				if (i < sh->pd_idx)
3183 					i += raid_disks;
3184 				i -= (sh->pd_idx + 2);
3185 			}
3186 			break;
3187 		case ALGORITHM_PARITY_0:
3188 			i -= 2;
3189 			break;
3190 		case ALGORITHM_PARITY_N:
3191 			break;
3192 		case ALGORITHM_ROTATING_N_CONTINUE:
3193 			/* Like left_symmetric, but P is before Q */
3194 			if (sh->pd_idx == 0)
3195 				i--;	/* P D D D Q */
3196 			else {
3197 				/* D D Q P D */
3198 				if (i < sh->pd_idx)
3199 					i += raid_disks;
3200 				i -= (sh->pd_idx + 1);
3201 			}
3202 			break;
3203 		case ALGORITHM_LEFT_ASYMMETRIC_6:
3204 		case ALGORITHM_RIGHT_ASYMMETRIC_6:
3205 			if (i > sh->pd_idx)
3206 				i--;
3207 			break;
3208 		case ALGORITHM_LEFT_SYMMETRIC_6:
3209 		case ALGORITHM_RIGHT_SYMMETRIC_6:
3210 			if (i < sh->pd_idx)
3211 				i += data_disks + 1;
3212 			i -= (sh->pd_idx + 1);
3213 			break;
3214 		case ALGORITHM_PARITY_0_6:
3215 			i -= 1;
3216 			break;
3217 		default:
3218 			BUG();
3219 		}
3220 		break;
3221 	}
3222 
3223 	chunk_number = stripe * data_disks + i;
3224 	r_sector = chunk_number * sectors_per_chunk + chunk_offset;
3225 
3226 	check = raid5_compute_sector(conf, r_sector,
3227 				     previous, &dummy1, &sh2);
3228 	if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
3229 		|| sh2.qd_idx != sh->qd_idx) {
3230 		pr_warn("md/raid:%s: compute_blocknr: map not correct\n",
3231 			mdname(conf->mddev));
3232 		return 0;
3233 	}
3234 	return r_sector;
3235 }
3236 
3237 /*
3238  * There are cases where we want handle_stripe_dirtying() and
3239  * schedule_reconstruction() to delay towrite to some dev of a stripe.
3240  *
3241  * This function checks whether we want to delay the towrite. Specifically,
3242  * we delay the towrite when:
3243  *
3244  *   1. degraded stripe has a non-overwrite to the missing dev, AND this
3245  *      stripe has data in journal (for other devices).
3246  *
3247  *      In this case, when reading data for the non-overwrite dev, it is
3248  *      necessary to handle complex rmw of write back cache (prexor with
3249  *      orig_page, and xor with page). To keep read path simple, we would
3250  *      like to flush data in journal to RAID disks first, so complex rmw
3251  *      is handled in the write patch (handle_stripe_dirtying).
3252  *
3253  *   2. when journal space is critical (R5C_LOG_CRITICAL=1)
3254  *
3255  *      It is important to be able to flush all stripes in raid5-cache.
3256  *      Therefore, we need reserve some space on the journal device for
3257  *      these flushes. If flush operation includes pending writes to the
3258  *      stripe, we need to reserve (conf->raid_disk + 1) pages per stripe
3259  *      for the flush out. If we exclude these pending writes from flush
3260  *      operation, we only need (conf->max_degraded + 1) pages per stripe.
3261  *      Therefore, excluding pending writes in these cases enables more
3262  *      efficient use of the journal device.
3263  *
3264  *      Note: To make sure the stripe makes progress, we only delay
3265  *      towrite for stripes with data already in journal (injournal > 0).
3266  *      When LOG_CRITICAL, stripes with injournal == 0 will be sent to
3267  *      no_space_stripes list.
3268  *
3269  *   3. during journal failure
3270  *      In journal failure, we try to flush all cached data to raid disks
3271  *      based on data in stripe cache. The array is read-only to upper
3272  *      layers, so we would skip all pending writes.
3273  *
3274  */
3275 static inline bool delay_towrite(struct r5conf *conf,
3276 				 struct r5dev *dev,
3277 				 struct stripe_head_state *s)
3278 {
3279 	/* case 1 above */
3280 	if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3281 	    !test_bit(R5_Insync, &dev->flags) && s->injournal)
3282 		return true;
3283 	/* case 2 above */
3284 	if (test_bit(R5C_LOG_CRITICAL, &conf->cache_state) &&
3285 	    s->injournal > 0)
3286 		return true;
3287 	/* case 3 above */
3288 	if (s->log_failed && s->injournal)
3289 		return true;
3290 	return false;
3291 }
3292 
3293 static void
3294 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
3295 			 int rcw, int expand)
3296 {
3297 	int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
3298 	struct r5conf *conf = sh->raid_conf;
3299 	int level = conf->level;
3300 
3301 	if (rcw) {
3302 		/*
3303 		 * In some cases, handle_stripe_dirtying initially decided to
3304 		 * run rmw and allocates extra page for prexor. However, rcw is
3305 		 * cheaper later on. We need to free the extra page now,
3306 		 * because we won't be able to do that in ops_complete_prexor().
3307 		 */
3308 		r5c_release_extra_page(sh);
3309 
3310 		for (i = disks; i--; ) {
3311 			struct r5dev *dev = &sh->dev[i];
3312 
3313 			if (dev->towrite && !delay_towrite(conf, dev, s)) {
3314 				set_bit(R5_LOCKED, &dev->flags);
3315 				set_bit(R5_Wantdrain, &dev->flags);
3316 				if (!expand)
3317 					clear_bit(R5_UPTODATE, &dev->flags);
3318 				s->locked++;
3319 			} else if (test_bit(R5_InJournal, &dev->flags)) {
3320 				set_bit(R5_LOCKED, &dev->flags);
3321 				s->locked++;
3322 			}
3323 		}
3324 		/* if we are not expanding this is a proper write request, and
3325 		 * there will be bios with new data to be drained into the
3326 		 * stripe cache
3327 		 */
3328 		if (!expand) {
3329 			if (!s->locked)
3330 				/* False alarm, nothing to do */
3331 				return;
3332 			sh->reconstruct_state = reconstruct_state_drain_run;
3333 			set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3334 		} else
3335 			sh->reconstruct_state = reconstruct_state_run;
3336 
3337 		set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3338 
3339 		if (s->locked + conf->max_degraded == disks)
3340 			if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
3341 				atomic_inc(&conf->pending_full_writes);
3342 	} else {
3343 		BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
3344 			test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
3345 		BUG_ON(level == 6 &&
3346 			(!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
3347 			   test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
3348 
3349 		for (i = disks; i--; ) {
3350 			struct r5dev *dev = &sh->dev[i];
3351 			if (i == pd_idx || i == qd_idx)
3352 				continue;
3353 
3354 			if (dev->towrite &&
3355 			    (test_bit(R5_UPTODATE, &dev->flags) ||
3356 			     test_bit(R5_Wantcompute, &dev->flags))) {
3357 				set_bit(R5_Wantdrain, &dev->flags);
3358 				set_bit(R5_LOCKED, &dev->flags);
3359 				clear_bit(R5_UPTODATE, &dev->flags);
3360 				s->locked++;
3361 			} else if (test_bit(R5_InJournal, &dev->flags)) {
3362 				set_bit(R5_LOCKED, &dev->flags);
3363 				s->locked++;
3364 			}
3365 		}
3366 		if (!s->locked)
3367 			/* False alarm - nothing to do */
3368 			return;
3369 		sh->reconstruct_state = reconstruct_state_prexor_drain_run;
3370 		set_bit(STRIPE_OP_PREXOR, &s->ops_request);
3371 		set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3372 		set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3373 	}
3374 
3375 	/* keep the parity disk(s) locked while asynchronous operations
3376 	 * are in flight
3377 	 */
3378 	set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
3379 	clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3380 	s->locked++;
3381 
3382 	if (level == 6) {
3383 		int qd_idx = sh->qd_idx;
3384 		struct r5dev *dev = &sh->dev[qd_idx];
3385 
3386 		set_bit(R5_LOCKED, &dev->flags);
3387 		clear_bit(R5_UPTODATE, &dev->flags);
3388 		s->locked++;
3389 	}
3390 
3391 	if (raid5_has_ppl(sh->raid_conf) && sh->ppl_page &&
3392 	    test_bit(STRIPE_OP_BIODRAIN, &s->ops_request) &&
3393 	    !test_bit(STRIPE_FULL_WRITE, &sh->state) &&
3394 	    test_bit(R5_Insync, &sh->dev[pd_idx].flags))
3395 		set_bit(STRIPE_OP_PARTIAL_PARITY, &s->ops_request);
3396 
3397 	pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
3398 		__func__, (unsigned long long)sh->sector,
3399 		s->locked, s->ops_request);
3400 }
3401 
3402 /*
3403  * Each stripe/dev can have one or more bion attached.
3404  * toread/towrite point to the first in a chain.
3405  * The bi_next chain must be in order.
3406  */
3407 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
3408 			  int forwrite, int previous)
3409 {
3410 	struct bio **bip;
3411 	struct r5conf *conf = sh->raid_conf;
3412 	int firstwrite=0;
3413 
3414 	pr_debug("adding bi b#%llu to stripe s#%llu\n",
3415 		(unsigned long long)bi->bi_iter.bi_sector,
3416 		(unsigned long long)sh->sector);
3417 
3418 	spin_lock_irq(&sh->stripe_lock);
3419 	sh->dev[dd_idx].write_hint = bi->bi_write_hint;
3420 	/* Don't allow new IO added to stripes in batch list */
3421 	if (sh->batch_head)
3422 		goto overlap;
3423 	if (forwrite) {
3424 		bip = &sh->dev[dd_idx].towrite;
3425 		if (*bip == NULL)
3426 			firstwrite = 1;
3427 	} else
3428 		bip = &sh->dev[dd_idx].toread;
3429 	while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
3430 		if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
3431 			goto overlap;
3432 		bip = & (*bip)->bi_next;
3433 	}
3434 	if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
3435 		goto overlap;
3436 
3437 	if (forwrite && raid5_has_ppl(conf)) {
3438 		/*
3439 		 * With PPL only writes to consecutive data chunks within a
3440 		 * stripe are allowed because for a single stripe_head we can
3441 		 * only have one PPL entry at a time, which describes one data
3442 		 * range. Not really an overlap, but wait_for_overlap can be
3443 		 * used to handle this.
3444 		 */
3445 		sector_t sector;
3446 		sector_t first = 0;
3447 		sector_t last = 0;
3448 		int count = 0;
3449 		int i;
3450 
3451 		for (i = 0; i < sh->disks; i++) {
3452 			if (i != sh->pd_idx &&
3453 			    (i == dd_idx || sh->dev[i].towrite)) {
3454 				sector = sh->dev[i].sector;
3455 				if (count == 0 || sector < first)
3456 					first = sector;
3457 				if (sector > last)
3458 					last = sector;
3459 				count++;
3460 			}
3461 		}
3462 
3463 		if (first + conf->chunk_sectors * (count - 1) != last)
3464 			goto overlap;
3465 	}
3466 
3467 	if (!forwrite || previous)
3468 		clear_bit(STRIPE_BATCH_READY, &sh->state);
3469 
3470 	BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3471 	if (*bip)
3472 		bi->bi_next = *bip;
3473 	*bip = bi;
3474 	bio_inc_remaining(bi);
3475 	md_write_inc(conf->mddev, bi);
3476 
3477 	if (forwrite) {
3478 		/* check if page is covered */
3479 		sector_t sector = sh->dev[dd_idx].sector;
3480 		for (bi=sh->dev[dd_idx].towrite;
3481 		     sector < sh->dev[dd_idx].sector + RAID5_STRIPE_SECTORS(conf) &&
3482 			     bi && bi->bi_iter.bi_sector <= sector;
3483 		     bi = r5_next_bio(conf, bi, sh->dev[dd_idx].sector)) {
3484 			if (bio_end_sector(bi) >= sector)
3485 				sector = bio_end_sector(bi);
3486 		}
3487 		if (sector >= sh->dev[dd_idx].sector + RAID5_STRIPE_SECTORS(conf))
3488 			if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3489 				sh->overwrite_disks++;
3490 	}
3491 
3492 	pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3493 		(unsigned long long)(*bip)->bi_iter.bi_sector,
3494 		(unsigned long long)sh->sector, dd_idx);
3495 
3496 	if (conf->mddev->bitmap && firstwrite) {
3497 		/* Cannot hold spinlock over bitmap_startwrite,
3498 		 * but must ensure this isn't added to a batch until
3499 		 * we have added to the bitmap and set bm_seq.
3500 		 * So set STRIPE_BITMAP_PENDING to prevent
3501 		 * batching.
3502 		 * If multiple add_stripe_bio() calls race here they
3503 		 * much all set STRIPE_BITMAP_PENDING.  So only the first one
3504 		 * to complete "bitmap_startwrite" gets to set
3505 		 * STRIPE_BIT_DELAY.  This is important as once a stripe
3506 		 * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3507 		 * any more.
3508 		 */
3509 		set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3510 		spin_unlock_irq(&sh->stripe_lock);
3511 		md_bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3512 				     RAID5_STRIPE_SECTORS(conf), 0);
3513 		spin_lock_irq(&sh->stripe_lock);
3514 		clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3515 		if (!sh->batch_head) {
3516 			sh->bm_seq = conf->seq_flush+1;
3517 			set_bit(STRIPE_BIT_DELAY, &sh->state);
3518 		}
3519 	}
3520 	spin_unlock_irq(&sh->stripe_lock);
3521 
3522 	if (stripe_can_batch(sh))
3523 		stripe_add_to_batch_list(conf, sh);
3524 	return 1;
3525 
3526  overlap:
3527 	set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3528 	spin_unlock_irq(&sh->stripe_lock);
3529 	return 0;
3530 }
3531 
3532 static void end_reshape(struct r5conf *conf);
3533 
3534 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3535 			    struct stripe_head *sh)
3536 {
3537 	int sectors_per_chunk =
3538 		previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3539 	int dd_idx;
3540 	int chunk_offset = sector_div(stripe, sectors_per_chunk);
3541 	int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3542 
3543 	raid5_compute_sector(conf,
3544 			     stripe * (disks - conf->max_degraded)
3545 			     *sectors_per_chunk + chunk_offset,
3546 			     previous,
3547 			     &dd_idx, sh);
3548 }
3549 
3550 static void
3551 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3552 		     struct stripe_head_state *s, int disks)
3553 {
3554 	int i;
3555 	BUG_ON(sh->batch_head);
3556 	for (i = disks; i--; ) {
3557 		struct bio *bi;
3558 		int bitmap_end = 0;
3559 
3560 		if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3561 			struct md_rdev *rdev;
3562 			rcu_read_lock();
3563 			rdev = rcu_dereference(conf->disks[i].rdev);
3564 			if (rdev && test_bit(In_sync, &rdev->flags) &&
3565 			    !test_bit(Faulty, &rdev->flags))
3566 				atomic_inc(&rdev->nr_pending);
3567 			else
3568 				rdev = NULL;
3569 			rcu_read_unlock();
3570 			if (rdev) {
3571 				if (!rdev_set_badblocks(
3572 					    rdev,
3573 					    sh->sector,
3574 					    RAID5_STRIPE_SECTORS(conf), 0))
3575 					md_error(conf->mddev, rdev);
3576 				rdev_dec_pending(rdev, conf->mddev);
3577 			}
3578 		}
3579 		spin_lock_irq(&sh->stripe_lock);
3580 		/* fail all writes first */
3581 		bi = sh->dev[i].towrite;
3582 		sh->dev[i].towrite = NULL;
3583 		sh->overwrite_disks = 0;
3584 		spin_unlock_irq(&sh->stripe_lock);
3585 		if (bi)
3586 			bitmap_end = 1;
3587 
3588 		log_stripe_write_finished(sh);
3589 
3590 		if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3591 			wake_up(&conf->wait_for_overlap);
3592 
3593 		while (bi && bi->bi_iter.bi_sector <
3594 			sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3595 			struct bio *nextbi = r5_next_bio(conf, bi, sh->dev[i].sector);
3596 
3597 			md_write_end(conf->mddev);
3598 			bio_io_error(bi);
3599 			bi = nextbi;
3600 		}
3601 		if (bitmap_end)
3602 			md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3603 					   RAID5_STRIPE_SECTORS(conf), 0, 0);
3604 		bitmap_end = 0;
3605 		/* and fail all 'written' */
3606 		bi = sh->dev[i].written;
3607 		sh->dev[i].written = NULL;
3608 		if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3609 			WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3610 			sh->dev[i].page = sh->dev[i].orig_page;
3611 		}
3612 
3613 		if (bi) bitmap_end = 1;
3614 		while (bi && bi->bi_iter.bi_sector <
3615 		       sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3616 			struct bio *bi2 = r5_next_bio(conf, bi, sh->dev[i].sector);
3617 
3618 			md_write_end(conf->mddev);
3619 			bio_io_error(bi);
3620 			bi = bi2;
3621 		}
3622 
3623 		/* fail any reads if this device is non-operational and
3624 		 * the data has not reached the cache yet.
3625 		 */
3626 		if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3627 		    s->failed > conf->max_degraded &&
3628 		    (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3629 		      test_bit(R5_ReadError, &sh->dev[i].flags))) {
3630 			spin_lock_irq(&sh->stripe_lock);
3631 			bi = sh->dev[i].toread;
3632 			sh->dev[i].toread = NULL;
3633 			spin_unlock_irq(&sh->stripe_lock);
3634 			if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3635 				wake_up(&conf->wait_for_overlap);
3636 			if (bi)
3637 				s->to_read--;
3638 			while (bi && bi->bi_iter.bi_sector <
3639 			       sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3640 				struct bio *nextbi =
3641 					r5_next_bio(conf, bi, sh->dev[i].sector);
3642 
3643 				bio_io_error(bi);
3644 				bi = nextbi;
3645 			}
3646 		}
3647 		if (bitmap_end)
3648 			md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3649 					   RAID5_STRIPE_SECTORS(conf), 0, 0);
3650 		/* If we were in the middle of a write the parity block might
3651 		 * still be locked - so just clear all R5_LOCKED flags
3652 		 */
3653 		clear_bit(R5_LOCKED, &sh->dev[i].flags);
3654 	}
3655 	s->to_write = 0;
3656 	s->written = 0;
3657 
3658 	if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3659 		if (atomic_dec_and_test(&conf->pending_full_writes))
3660 			md_wakeup_thread(conf->mddev->thread);
3661 }
3662 
3663 static void
3664 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3665 		   struct stripe_head_state *s)
3666 {
3667 	int abort = 0;
3668 	int i;
3669 
3670 	BUG_ON(sh->batch_head);
3671 	clear_bit(STRIPE_SYNCING, &sh->state);
3672 	if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3673 		wake_up(&conf->wait_for_overlap);
3674 	s->syncing = 0;
3675 	s->replacing = 0;
3676 	/* There is nothing more to do for sync/check/repair.
3677 	 * Don't even need to abort as that is handled elsewhere
3678 	 * if needed, and not always wanted e.g. if there is a known
3679 	 * bad block here.
3680 	 * For recover/replace we need to record a bad block on all
3681 	 * non-sync devices, or abort the recovery
3682 	 */
3683 	if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3684 		/* During recovery devices cannot be removed, so
3685 		 * locking and refcounting of rdevs is not needed
3686 		 */
3687 		rcu_read_lock();
3688 		for (i = 0; i < conf->raid_disks; i++) {
3689 			struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
3690 			if (rdev
3691 			    && !test_bit(Faulty, &rdev->flags)
3692 			    && !test_bit(In_sync, &rdev->flags)
3693 			    && !rdev_set_badblocks(rdev, sh->sector,
3694 						   RAID5_STRIPE_SECTORS(conf), 0))
3695 				abort = 1;
3696 			rdev = rcu_dereference(conf->disks[i].replacement);
3697 			if (rdev
3698 			    && !test_bit(Faulty, &rdev->flags)
3699 			    && !test_bit(In_sync, &rdev->flags)
3700 			    && !rdev_set_badblocks(rdev, sh->sector,
3701 						   RAID5_STRIPE_SECTORS(conf), 0))
3702 				abort = 1;
3703 		}
3704 		rcu_read_unlock();
3705 		if (abort)
3706 			conf->recovery_disabled =
3707 				conf->mddev->recovery_disabled;
3708 	}
3709 	md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), !abort);
3710 }
3711 
3712 static int want_replace(struct stripe_head *sh, int disk_idx)
3713 {
3714 	struct md_rdev *rdev;
3715 	int rv = 0;
3716 
3717 	rcu_read_lock();
3718 	rdev = rcu_dereference(sh->raid_conf->disks[disk_idx].replacement);
3719 	if (rdev
3720 	    && !test_bit(Faulty, &rdev->flags)
3721 	    && !test_bit(In_sync, &rdev->flags)
3722 	    && (rdev->recovery_offset <= sh->sector
3723 		|| rdev->mddev->recovery_cp <= sh->sector))
3724 		rv = 1;
3725 	rcu_read_unlock();
3726 	return rv;
3727 }
3728 
3729 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3730 			   int disk_idx, int disks)
3731 {
3732 	struct r5dev *dev = &sh->dev[disk_idx];
3733 	struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3734 				  &sh->dev[s->failed_num[1]] };
3735 	int i;
3736 	bool force_rcw = (sh->raid_conf->rmw_level == PARITY_DISABLE_RMW);
3737 
3738 
3739 	if (test_bit(R5_LOCKED, &dev->flags) ||
3740 	    test_bit(R5_UPTODATE, &dev->flags))
3741 		/* No point reading this as we already have it or have
3742 		 * decided to get it.
3743 		 */
3744 		return 0;
3745 
3746 	if (dev->toread ||
3747 	    (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3748 		/* We need this block to directly satisfy a request */
3749 		return 1;
3750 
3751 	if (s->syncing || s->expanding ||
3752 	    (s->replacing && want_replace(sh, disk_idx)))
3753 		/* When syncing, or expanding we read everything.
3754 		 * When replacing, we need the replaced block.
3755 		 */
3756 		return 1;
3757 
3758 	if ((s->failed >= 1 && fdev[0]->toread) ||
3759 	    (s->failed >= 2 && fdev[1]->toread))
3760 		/* If we want to read from a failed device, then
3761 		 * we need to actually read every other device.
3762 		 */
3763 		return 1;
3764 
3765 	/* Sometimes neither read-modify-write nor reconstruct-write
3766 	 * cycles can work.  In those cases we read every block we
3767 	 * can.  Then the parity-update is certain to have enough to
3768 	 * work with.
3769 	 * This can only be a problem when we need to write something,
3770 	 * and some device has failed.  If either of those tests
3771 	 * fail we need look no further.
3772 	 */
3773 	if (!s->failed || !s->to_write)
3774 		return 0;
3775 
3776 	if (test_bit(R5_Insync, &dev->flags) &&
3777 	    !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3778 		/* Pre-reads at not permitted until after short delay
3779 		 * to gather multiple requests.  However if this
3780 		 * device is no Insync, the block could only be computed
3781 		 * and there is no need to delay that.
3782 		 */
3783 		return 0;
3784 
3785 	for (i = 0; i < s->failed && i < 2; i++) {
3786 		if (fdev[i]->towrite &&
3787 		    !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3788 		    !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3789 			/* If we have a partial write to a failed
3790 			 * device, then we will need to reconstruct
3791 			 * the content of that device, so all other
3792 			 * devices must be read.
3793 			 */
3794 			return 1;
3795 
3796 		if (s->failed >= 2 &&
3797 		    (fdev[i]->towrite ||
3798 		     s->failed_num[i] == sh->pd_idx ||
3799 		     s->failed_num[i] == sh->qd_idx) &&
3800 		    !test_bit(R5_UPTODATE, &fdev[i]->flags))
3801 			/* In max degraded raid6, If the failed disk is P, Q,
3802 			 * or we want to read the failed disk, we need to do
3803 			 * reconstruct-write.
3804 			 */
3805 			force_rcw = true;
3806 	}
3807 
3808 	/* If we are forced to do a reconstruct-write, because parity
3809 	 * cannot be trusted and we are currently recovering it, there
3810 	 * is extra need to be careful.
3811 	 * If one of the devices that we would need to read, because
3812 	 * it is not being overwritten (and maybe not written at all)
3813 	 * is missing/faulty, then we need to read everything we can.
3814 	 */
3815 	if (!force_rcw &&
3816 	    sh->sector < sh->raid_conf->mddev->recovery_cp)
3817 		/* reconstruct-write isn't being forced */
3818 		return 0;
3819 	for (i = 0; i < s->failed && i < 2; i++) {
3820 		if (s->failed_num[i] != sh->pd_idx &&
3821 		    s->failed_num[i] != sh->qd_idx &&
3822 		    !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3823 		    !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3824 			return 1;
3825 	}
3826 
3827 	return 0;
3828 }
3829 
3830 /* fetch_block - checks the given member device to see if its data needs
3831  * to be read or computed to satisfy a request.
3832  *
3833  * Returns 1 when no more member devices need to be checked, otherwise returns
3834  * 0 to tell the loop in handle_stripe_fill to continue
3835  */
3836 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3837 		       int disk_idx, int disks)
3838 {
3839 	struct r5dev *dev = &sh->dev[disk_idx];
3840 
3841 	/* is the data in this block needed, and can we get it? */
3842 	if (need_this_block(sh, s, disk_idx, disks)) {
3843 		/* we would like to get this block, possibly by computing it,
3844 		 * otherwise read it if the backing disk is insync
3845 		 */
3846 		BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3847 		BUG_ON(test_bit(R5_Wantread, &dev->flags));
3848 		BUG_ON(sh->batch_head);
3849 
3850 		/*
3851 		 * In the raid6 case if the only non-uptodate disk is P
3852 		 * then we already trusted P to compute the other failed
3853 		 * drives. It is safe to compute rather than re-read P.
3854 		 * In other cases we only compute blocks from failed
3855 		 * devices, otherwise check/repair might fail to detect
3856 		 * a real inconsistency.
3857 		 */
3858 
3859 		if ((s->uptodate == disks - 1) &&
3860 		    ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3861 		    (s->failed && (disk_idx == s->failed_num[0] ||
3862 				   disk_idx == s->failed_num[1])))) {
3863 			/* have disk failed, and we're requested to fetch it;
3864 			 * do compute it
3865 			 */
3866 			pr_debug("Computing stripe %llu block %d\n",
3867 			       (unsigned long long)sh->sector, disk_idx);
3868 			set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3869 			set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3870 			set_bit(R5_Wantcompute, &dev->flags);
3871 			sh->ops.target = disk_idx;
3872 			sh->ops.target2 = -1; /* no 2nd target */
3873 			s->req_compute = 1;
3874 			/* Careful: from this point on 'uptodate' is in the eye
3875 			 * of raid_run_ops which services 'compute' operations
3876 			 * before writes. R5_Wantcompute flags a block that will
3877 			 * be R5_UPTODATE by the time it is needed for a
3878 			 * subsequent operation.
3879 			 */
3880 			s->uptodate++;
3881 			return 1;
3882 		} else if (s->uptodate == disks-2 && s->failed >= 2) {
3883 			/* Computing 2-failure is *very* expensive; only
3884 			 * do it if failed >= 2
3885 			 */
3886 			int other;
3887 			for (other = disks; other--; ) {
3888 				if (other == disk_idx)
3889 					continue;
3890 				if (!test_bit(R5_UPTODATE,
3891 				      &sh->dev[other].flags))
3892 					break;
3893 			}
3894 			BUG_ON(other < 0);
3895 			pr_debug("Computing stripe %llu blocks %d,%d\n",
3896 			       (unsigned long long)sh->sector,
3897 			       disk_idx, other);
3898 			set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3899 			set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3900 			set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3901 			set_bit(R5_Wantcompute, &sh->dev[other].flags);
3902 			sh->ops.target = disk_idx;
3903 			sh->ops.target2 = other;
3904 			s->uptodate += 2;
3905 			s->req_compute = 1;
3906 			return 1;
3907 		} else if (test_bit(R5_Insync, &dev->flags)) {
3908 			set_bit(R5_LOCKED, &dev->flags);
3909 			set_bit(R5_Wantread, &dev->flags);
3910 			s->locked++;
3911 			pr_debug("Reading block %d (sync=%d)\n",
3912 				disk_idx, s->syncing);
3913 		}
3914 	}
3915 
3916 	return 0;
3917 }
3918 
3919 /*
3920  * handle_stripe_fill - read or compute data to satisfy pending requests.
3921  */
3922 static void handle_stripe_fill(struct stripe_head *sh,
3923 			       struct stripe_head_state *s,
3924 			       int disks)
3925 {
3926 	int i;
3927 
3928 	/* look for blocks to read/compute, skip this if a compute
3929 	 * is already in flight, or if the stripe contents are in the
3930 	 * midst of changing due to a write
3931 	 */
3932 	if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3933 	    !sh->reconstruct_state) {
3934 
3935 		/*
3936 		 * For degraded stripe with data in journal, do not handle
3937 		 * read requests yet, instead, flush the stripe to raid
3938 		 * disks first, this avoids handling complex rmw of write
3939 		 * back cache (prexor with orig_page, and then xor with
3940 		 * page) in the read path
3941 		 */
3942 		if (s->injournal && s->failed) {
3943 			if (test_bit(STRIPE_R5C_CACHING, &sh->state))
3944 				r5c_make_stripe_write_out(sh);
3945 			goto out;
3946 		}
3947 
3948 		for (i = disks; i--; )
3949 			if (fetch_block(sh, s, i, disks))
3950 				break;
3951 	}
3952 out:
3953 	set_bit(STRIPE_HANDLE, &sh->state);
3954 }
3955 
3956 static void break_stripe_batch_list(struct stripe_head *head_sh,
3957 				    unsigned long handle_flags);
3958 /* handle_stripe_clean_event
3959  * any written block on an uptodate or failed drive can be returned.
3960  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3961  * never LOCKED, so we don't need to test 'failed' directly.
3962  */
3963 static void handle_stripe_clean_event(struct r5conf *conf,
3964 	struct stripe_head *sh, int disks)
3965 {
3966 	int i;
3967 	struct r5dev *dev;
3968 	int discard_pending = 0;
3969 	struct stripe_head *head_sh = sh;
3970 	bool do_endio = false;
3971 
3972 	for (i = disks; i--; )
3973 		if (sh->dev[i].written) {
3974 			dev = &sh->dev[i];
3975 			if (!test_bit(R5_LOCKED, &dev->flags) &&
3976 			    (test_bit(R5_UPTODATE, &dev->flags) ||
3977 			     test_bit(R5_Discard, &dev->flags) ||
3978 			     test_bit(R5_SkipCopy, &dev->flags))) {
3979 				/* We can return any write requests */
3980 				struct bio *wbi, *wbi2;
3981 				pr_debug("Return write for disc %d\n", i);
3982 				if (test_and_clear_bit(R5_Discard, &dev->flags))
3983 					clear_bit(R5_UPTODATE, &dev->flags);
3984 				if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3985 					WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3986 				}
3987 				do_endio = true;
3988 
3989 returnbi:
3990 				dev->page = dev->orig_page;
3991 				wbi = dev->written;
3992 				dev->written = NULL;
3993 				while (wbi && wbi->bi_iter.bi_sector <
3994 					dev->sector + RAID5_STRIPE_SECTORS(conf)) {
3995 					wbi2 = r5_next_bio(conf, wbi, dev->sector);
3996 					md_write_end(conf->mddev);
3997 					bio_endio(wbi);
3998 					wbi = wbi2;
3999 				}
4000 				md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
4001 						   RAID5_STRIPE_SECTORS(conf),
4002 						   !test_bit(STRIPE_DEGRADED, &sh->state),
4003 						   0);
4004 				if (head_sh->batch_head) {
4005 					sh = list_first_entry(&sh->batch_list,
4006 							      struct stripe_head,
4007 							      batch_list);
4008 					if (sh != head_sh) {
4009 						dev = &sh->dev[i];
4010 						goto returnbi;
4011 					}
4012 				}
4013 				sh = head_sh;
4014 				dev = &sh->dev[i];
4015 			} else if (test_bit(R5_Discard, &dev->flags))
4016 				discard_pending = 1;
4017 		}
4018 
4019 	log_stripe_write_finished(sh);
4020 
4021 	if (!discard_pending &&
4022 	    test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
4023 		int hash;
4024 		clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
4025 		clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4026 		if (sh->qd_idx >= 0) {
4027 			clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
4028 			clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
4029 		}
4030 		/* now that discard is done we can proceed with any sync */
4031 		clear_bit(STRIPE_DISCARD, &sh->state);
4032 		/*
4033 		 * SCSI discard will change some bio fields and the stripe has
4034 		 * no updated data, so remove it from hash list and the stripe
4035 		 * will be reinitialized
4036 		 */
4037 unhash:
4038 		hash = sh->hash_lock_index;
4039 		spin_lock_irq(conf->hash_locks + hash);
4040 		remove_hash(sh);
4041 		spin_unlock_irq(conf->hash_locks + hash);
4042 		if (head_sh->batch_head) {
4043 			sh = list_first_entry(&sh->batch_list,
4044 					      struct stripe_head, batch_list);
4045 			if (sh != head_sh)
4046 					goto unhash;
4047 		}
4048 		sh = head_sh;
4049 
4050 		if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
4051 			set_bit(STRIPE_HANDLE, &sh->state);
4052 
4053 	}
4054 
4055 	if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
4056 		if (atomic_dec_and_test(&conf->pending_full_writes))
4057 			md_wakeup_thread(conf->mddev->thread);
4058 
4059 	if (head_sh->batch_head && do_endio)
4060 		break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
4061 }
4062 
4063 /*
4064  * For RMW in write back cache, we need extra page in prexor to store the
4065  * old data. This page is stored in dev->orig_page.
4066  *
4067  * This function checks whether we have data for prexor. The exact logic
4068  * is:
4069  *       R5_UPTODATE && (!R5_InJournal || R5_OrigPageUPTDODATE)
4070  */
4071 static inline bool uptodate_for_rmw(struct r5dev *dev)
4072 {
4073 	return (test_bit(R5_UPTODATE, &dev->flags)) &&
4074 		(!test_bit(R5_InJournal, &dev->flags) ||
4075 		 test_bit(R5_OrigPageUPTDODATE, &dev->flags));
4076 }
4077 
4078 static int handle_stripe_dirtying(struct r5conf *conf,
4079 				  struct stripe_head *sh,
4080 				  struct stripe_head_state *s,
4081 				  int disks)
4082 {
4083 	int rmw = 0, rcw = 0, i;
4084 	sector_t recovery_cp = conf->mddev->recovery_cp;
4085 
4086 	/* Check whether resync is now happening or should start.
4087 	 * If yes, then the array is dirty (after unclean shutdown or
4088 	 * initial creation), so parity in some stripes might be inconsistent.
4089 	 * In this case, we need to always do reconstruct-write, to ensure
4090 	 * that in case of drive failure or read-error correction, we
4091 	 * generate correct data from the parity.
4092 	 */
4093 	if (conf->rmw_level == PARITY_DISABLE_RMW ||
4094 	    (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
4095 	     s->failed == 0)) {
4096 		/* Calculate the real rcw later - for now make it
4097 		 * look like rcw is cheaper
4098 		 */
4099 		rcw = 1; rmw = 2;
4100 		pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
4101 			 conf->rmw_level, (unsigned long long)recovery_cp,
4102 			 (unsigned long long)sh->sector);
4103 	} else for (i = disks; i--; ) {
4104 		/* would I have to read this buffer for read_modify_write */
4105 		struct r5dev *dev = &sh->dev[i];
4106 		if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
4107 		     i == sh->pd_idx || i == sh->qd_idx ||
4108 		     test_bit(R5_InJournal, &dev->flags)) &&
4109 		    !test_bit(R5_LOCKED, &dev->flags) &&
4110 		    !(uptodate_for_rmw(dev) ||
4111 		      test_bit(R5_Wantcompute, &dev->flags))) {
4112 			if (test_bit(R5_Insync, &dev->flags))
4113 				rmw++;
4114 			else
4115 				rmw += 2*disks;  /* cannot read it */
4116 		}
4117 		/* Would I have to read this buffer for reconstruct_write */
4118 		if (!test_bit(R5_OVERWRITE, &dev->flags) &&
4119 		    i != sh->pd_idx && i != sh->qd_idx &&
4120 		    !test_bit(R5_LOCKED, &dev->flags) &&
4121 		    !(test_bit(R5_UPTODATE, &dev->flags) ||
4122 		      test_bit(R5_Wantcompute, &dev->flags))) {
4123 			if (test_bit(R5_Insync, &dev->flags))
4124 				rcw++;
4125 			else
4126 				rcw += 2*disks;
4127 		}
4128 	}
4129 
4130 	pr_debug("for sector %llu state 0x%lx, rmw=%d rcw=%d\n",
4131 		 (unsigned long long)sh->sector, sh->state, rmw, rcw);
4132 	set_bit(STRIPE_HANDLE, &sh->state);
4133 	if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_PREFER_RMW)) && rmw > 0) {
4134 		/* prefer read-modify-write, but need to get some data */
4135 		if (conf->mddev->queue)
4136 			blk_add_trace_msg(conf->mddev->queue,
4137 					  "raid5 rmw %llu %d",
4138 					  (unsigned long long)sh->sector, rmw);
4139 		for (i = disks; i--; ) {
4140 			struct r5dev *dev = &sh->dev[i];
4141 			if (test_bit(R5_InJournal, &dev->flags) &&
4142 			    dev->page == dev->orig_page &&
4143 			    !test_bit(R5_LOCKED, &sh->dev[sh->pd_idx].flags)) {
4144 				/* alloc page for prexor */
4145 				struct page *p = alloc_page(GFP_NOIO);
4146 
4147 				if (p) {
4148 					dev->orig_page = p;
4149 					continue;
4150 				}
4151 
4152 				/*
4153 				 * alloc_page() failed, try use
4154 				 * disk_info->extra_page
4155 				 */
4156 				if (!test_and_set_bit(R5C_EXTRA_PAGE_IN_USE,
4157 						      &conf->cache_state)) {
4158 					r5c_use_extra_page(sh);
4159 					break;
4160 				}
4161 
4162 				/* extra_page in use, add to delayed_list */
4163 				set_bit(STRIPE_DELAYED, &sh->state);
4164 				s->waiting_extra_page = 1;
4165 				return -EAGAIN;
4166 			}
4167 		}
4168 
4169 		for (i = disks; i--; ) {
4170 			struct r5dev *dev = &sh->dev[i];
4171 			if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
4172 			     i == sh->pd_idx || i == sh->qd_idx ||
4173 			     test_bit(R5_InJournal, &dev->flags)) &&
4174 			    !test_bit(R5_LOCKED, &dev->flags) &&
4175 			    !(uptodate_for_rmw(dev) ||
4176 			      test_bit(R5_Wantcompute, &dev->flags)) &&
4177 			    test_bit(R5_Insync, &dev->flags)) {
4178 				if (test_bit(STRIPE_PREREAD_ACTIVE,
4179 					     &sh->state)) {
4180 					pr_debug("Read_old block %d for r-m-w\n",
4181 						 i);
4182 					set_bit(R5_LOCKED, &dev->flags);
4183 					set_bit(R5_Wantread, &dev->flags);
4184 					s->locked++;
4185 				} else
4186 					set_bit(STRIPE_DELAYED, &sh->state);
4187 			}
4188 		}
4189 	}
4190 	if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_PREFER_RMW)) && rcw > 0) {
4191 		/* want reconstruct write, but need to get some data */
4192 		int qread =0;
4193 		rcw = 0;
4194 		for (i = disks; i--; ) {
4195 			struct r5dev *dev = &sh->dev[i];
4196 			if (!test_bit(R5_OVERWRITE, &dev->flags) &&
4197 			    i != sh->pd_idx && i != sh->qd_idx &&
4198 			    !test_bit(R5_LOCKED, &dev->flags) &&
4199 			    !(test_bit(R5_UPTODATE, &dev->flags) ||
4200 			      test_bit(R5_Wantcompute, &dev->flags))) {
4201 				rcw++;
4202 				if (test_bit(R5_Insync, &dev->flags) &&
4203 				    test_bit(STRIPE_PREREAD_ACTIVE,
4204 					     &sh->state)) {
4205 					pr_debug("Read_old block "
4206 						"%d for Reconstruct\n", i);
4207 					set_bit(R5_LOCKED, &dev->flags);
4208 					set_bit(R5_Wantread, &dev->flags);
4209 					s->locked++;
4210 					qread++;
4211 				} else
4212 					set_bit(STRIPE_DELAYED, &sh->state);
4213 			}
4214 		}
4215 		if (rcw && conf->mddev->queue)
4216 			blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
4217 					  (unsigned long long)sh->sector,
4218 					  rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
4219 	}
4220 
4221 	if (rcw > disks && rmw > disks &&
4222 	    !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4223 		set_bit(STRIPE_DELAYED, &sh->state);
4224 
4225 	/* now if nothing is locked, and if we have enough data,
4226 	 * we can start a write request
4227 	 */
4228 	/* since handle_stripe can be called at any time we need to handle the
4229 	 * case where a compute block operation has been submitted and then a
4230 	 * subsequent call wants to start a write request.  raid_run_ops only
4231 	 * handles the case where compute block and reconstruct are requested
4232 	 * simultaneously.  If this is not the case then new writes need to be
4233 	 * held off until the compute completes.
4234 	 */
4235 	if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
4236 	    (s->locked == 0 && (rcw == 0 || rmw == 0) &&
4237 	     !test_bit(STRIPE_BIT_DELAY, &sh->state)))
4238 		schedule_reconstruction(sh, s, rcw == 0, 0);
4239 	return 0;
4240 }
4241 
4242 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
4243 				struct stripe_head_state *s, int disks)
4244 {
4245 	struct r5dev *dev = NULL;
4246 
4247 	BUG_ON(sh->batch_head);
4248 	set_bit(STRIPE_HANDLE, &sh->state);
4249 
4250 	switch (sh->check_state) {
4251 	case check_state_idle:
4252 		/* start a new check operation if there are no failures */
4253 		if (s->failed == 0) {
4254 			BUG_ON(s->uptodate != disks);
4255 			sh->check_state = check_state_run;
4256 			set_bit(STRIPE_OP_CHECK, &s->ops_request);
4257 			clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4258 			s->uptodate--;
4259 			break;
4260 		}
4261 		dev = &sh->dev[s->failed_num[0]];
4262 		fallthrough;
4263 	case check_state_compute_result:
4264 		sh->check_state = check_state_idle;
4265 		if (!dev)
4266 			dev = &sh->dev[sh->pd_idx];
4267 
4268 		/* check that a write has not made the stripe insync */
4269 		if (test_bit(STRIPE_INSYNC, &sh->state))
4270 			break;
4271 
4272 		/* either failed parity check, or recovery is happening */
4273 		BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
4274 		BUG_ON(s->uptodate != disks);
4275 
4276 		set_bit(R5_LOCKED, &dev->flags);
4277 		s->locked++;
4278 		set_bit(R5_Wantwrite, &dev->flags);
4279 
4280 		clear_bit(STRIPE_DEGRADED, &sh->state);
4281 		set_bit(STRIPE_INSYNC, &sh->state);
4282 		break;
4283 	case check_state_run:
4284 		break; /* we will be called again upon completion */
4285 	case check_state_check_result:
4286 		sh->check_state = check_state_idle;
4287 
4288 		/* if a failure occurred during the check operation, leave
4289 		 * STRIPE_INSYNC not set and let the stripe be handled again
4290 		 */
4291 		if (s->failed)
4292 			break;
4293 
4294 		/* handle a successful check operation, if parity is correct
4295 		 * we are done.  Otherwise update the mismatch count and repair
4296 		 * parity if !MD_RECOVERY_CHECK
4297 		 */
4298 		if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
4299 			/* parity is correct (on disc,
4300 			 * not in buffer any more)
4301 			 */
4302 			set_bit(STRIPE_INSYNC, &sh->state);
4303 		else {
4304 			atomic64_add(RAID5_STRIPE_SECTORS(conf), &conf->mddev->resync_mismatches);
4305 			if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4306 				/* don't try to repair!! */
4307 				set_bit(STRIPE_INSYNC, &sh->state);
4308 				pr_warn_ratelimited("%s: mismatch sector in range "
4309 						    "%llu-%llu\n", mdname(conf->mddev),
4310 						    (unsigned long long) sh->sector,
4311 						    (unsigned long long) sh->sector +
4312 						    RAID5_STRIPE_SECTORS(conf));
4313 			} else {
4314 				sh->check_state = check_state_compute_run;
4315 				set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4316 				set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4317 				set_bit(R5_Wantcompute,
4318 					&sh->dev[sh->pd_idx].flags);
4319 				sh->ops.target = sh->pd_idx;
4320 				sh->ops.target2 = -1;
4321 				s->uptodate++;
4322 			}
4323 		}
4324 		break;
4325 	case check_state_compute_run:
4326 		break;
4327 	default:
4328 		pr_err("%s: unknown check_state: %d sector: %llu\n",
4329 		       __func__, sh->check_state,
4330 		       (unsigned long long) sh->sector);
4331 		BUG();
4332 	}
4333 }
4334 
4335 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
4336 				  struct stripe_head_state *s,
4337 				  int disks)
4338 {
4339 	int pd_idx = sh->pd_idx;
4340 	int qd_idx = sh->qd_idx;
4341 	struct r5dev *dev;
4342 
4343 	BUG_ON(sh->batch_head);
4344 	set_bit(STRIPE_HANDLE, &sh->state);
4345 
4346 	BUG_ON(s->failed > 2);
4347 
4348 	/* Want to check and possibly repair P and Q.
4349 	 * However there could be one 'failed' device, in which
4350 	 * case we can only check one of them, possibly using the
4351 	 * other to generate missing data
4352 	 */
4353 
4354 	switch (sh->check_state) {
4355 	case check_state_idle:
4356 		/* start a new check operation if there are < 2 failures */
4357 		if (s->failed == s->q_failed) {
4358 			/* The only possible failed device holds Q, so it
4359 			 * makes sense to check P (If anything else were failed,
4360 			 * we would have used P to recreate it).
4361 			 */
4362 			sh->check_state = check_state_run;
4363 		}
4364 		if (!s->q_failed && s->failed < 2) {
4365 			/* Q is not failed, and we didn't use it to generate
4366 			 * anything, so it makes sense to check it
4367 			 */
4368 			if (sh->check_state == check_state_run)
4369 				sh->check_state = check_state_run_pq;
4370 			else
4371 				sh->check_state = check_state_run_q;
4372 		}
4373 
4374 		/* discard potentially stale zero_sum_result */
4375 		sh->ops.zero_sum_result = 0;
4376 
4377 		if (sh->check_state == check_state_run) {
4378 			/* async_xor_zero_sum destroys the contents of P */
4379 			clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
4380 			s->uptodate--;
4381 		}
4382 		if (sh->check_state >= check_state_run &&
4383 		    sh->check_state <= check_state_run_pq) {
4384 			/* async_syndrome_zero_sum preserves P and Q, so
4385 			 * no need to mark them !uptodate here
4386 			 */
4387 			set_bit(STRIPE_OP_CHECK, &s->ops_request);
4388 			break;
4389 		}
4390 
4391 		/* we have 2-disk failure */
4392 		BUG_ON(s->failed != 2);
4393 		fallthrough;
4394 	case check_state_compute_result:
4395 		sh->check_state = check_state_idle;
4396 
4397 		/* check that a write has not made the stripe insync */
4398 		if (test_bit(STRIPE_INSYNC, &sh->state))
4399 			break;
4400 
4401 		/* now write out any block on a failed drive,
4402 		 * or P or Q if they were recomputed
4403 		 */
4404 		dev = NULL;
4405 		if (s->failed == 2) {
4406 			dev = &sh->dev[s->failed_num[1]];
4407 			s->locked++;
4408 			set_bit(R5_LOCKED, &dev->flags);
4409 			set_bit(R5_Wantwrite, &dev->flags);
4410 		}
4411 		if (s->failed >= 1) {
4412 			dev = &sh->dev[s->failed_num[0]];
4413 			s->locked++;
4414 			set_bit(R5_LOCKED, &dev->flags);
4415 			set_bit(R5_Wantwrite, &dev->flags);
4416 		}
4417 		if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4418 			dev = &sh->dev[pd_idx];
4419 			s->locked++;
4420 			set_bit(R5_LOCKED, &dev->flags);
4421 			set_bit(R5_Wantwrite, &dev->flags);
4422 		}
4423 		if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4424 			dev = &sh->dev[qd_idx];
4425 			s->locked++;
4426 			set_bit(R5_LOCKED, &dev->flags);
4427 			set_bit(R5_Wantwrite, &dev->flags);
4428 		}
4429 		if (WARN_ONCE(dev && !test_bit(R5_UPTODATE, &dev->flags),
4430 			      "%s: disk%td not up to date\n",
4431 			      mdname(conf->mddev),
4432 			      dev - (struct r5dev *) &sh->dev)) {
4433 			clear_bit(R5_LOCKED, &dev->flags);
4434 			clear_bit(R5_Wantwrite, &dev->flags);
4435 			s->locked--;
4436 		}
4437 		clear_bit(STRIPE_DEGRADED, &sh->state);
4438 
4439 		set_bit(STRIPE_INSYNC, &sh->state);
4440 		break;
4441 	case check_state_run:
4442 	case check_state_run_q:
4443 	case check_state_run_pq:
4444 		break; /* we will be called again upon completion */
4445 	case check_state_check_result:
4446 		sh->check_state = check_state_idle;
4447 
4448 		/* handle a successful check operation, if parity is correct
4449 		 * we are done.  Otherwise update the mismatch count and repair
4450 		 * parity if !MD_RECOVERY_CHECK
4451 		 */
4452 		if (sh->ops.zero_sum_result == 0) {
4453 			/* both parities are correct */
4454 			if (!s->failed)
4455 				set_bit(STRIPE_INSYNC, &sh->state);
4456 			else {
4457 				/* in contrast to the raid5 case we can validate
4458 				 * parity, but still have a failure to write
4459 				 * back
4460 				 */
4461 				sh->check_state = check_state_compute_result;
4462 				/* Returning at this point means that we may go
4463 				 * off and bring p and/or q uptodate again so
4464 				 * we make sure to check zero_sum_result again
4465 				 * to verify if p or q need writeback
4466 				 */
4467 			}
4468 		} else {
4469 			atomic64_add(RAID5_STRIPE_SECTORS(conf), &conf->mddev->resync_mismatches);
4470 			if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4471 				/* don't try to repair!! */
4472 				set_bit(STRIPE_INSYNC, &sh->state);
4473 				pr_warn_ratelimited("%s: mismatch sector in range "
4474 						    "%llu-%llu\n", mdname(conf->mddev),
4475 						    (unsigned long long) sh->sector,
4476 						    (unsigned long long) sh->sector +
4477 						    RAID5_STRIPE_SECTORS(conf));
4478 			} else {
4479 				int *target = &sh->ops.target;
4480 
4481 				sh->ops.target = -1;
4482 				sh->ops.target2 = -1;
4483 				sh->check_state = check_state_compute_run;
4484 				set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4485 				set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4486 				if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4487 					set_bit(R5_Wantcompute,
4488 						&sh->dev[pd_idx].flags);
4489 					*target = pd_idx;
4490 					target = &sh->ops.target2;
4491 					s->uptodate++;
4492 				}
4493 				if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4494 					set_bit(R5_Wantcompute,
4495 						&sh->dev[qd_idx].flags);
4496 					*target = qd_idx;
4497 					s->uptodate++;
4498 				}
4499 			}
4500 		}
4501 		break;
4502 	case check_state_compute_run:
4503 		break;
4504 	default:
4505 		pr_warn("%s: unknown check_state: %d sector: %llu\n",
4506 			__func__, sh->check_state,
4507 			(unsigned long long) sh->sector);
4508 		BUG();
4509 	}
4510 }
4511 
4512 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
4513 {
4514 	int i;
4515 
4516 	/* We have read all the blocks in this stripe and now we need to
4517 	 * copy some of them into a target stripe for expand.
4518 	 */
4519 	struct dma_async_tx_descriptor *tx = NULL;
4520 	BUG_ON(sh->batch_head);
4521 	clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4522 	for (i = 0; i < sh->disks; i++)
4523 		if (i != sh->pd_idx && i != sh->qd_idx) {
4524 			int dd_idx, j;
4525 			struct stripe_head *sh2;
4526 			struct async_submit_ctl submit;
4527 
4528 			sector_t bn = raid5_compute_blocknr(sh, i, 1);
4529 			sector_t s = raid5_compute_sector(conf, bn, 0,
4530 							  &dd_idx, NULL);
4531 			sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
4532 			if (sh2 == NULL)
4533 				/* so far only the early blocks of this stripe
4534 				 * have been requested.  When later blocks
4535 				 * get requested, we will try again
4536 				 */
4537 				continue;
4538 			if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
4539 			   test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
4540 				/* must have already done this block */
4541 				raid5_release_stripe(sh2);
4542 				continue;
4543 			}
4544 
4545 			/* place all the copies on one channel */
4546 			init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
4547 			tx = async_memcpy(sh2->dev[dd_idx].page,
4548 					  sh->dev[i].page, sh2->dev[dd_idx].offset,
4549 					  sh->dev[i].offset, RAID5_STRIPE_SIZE(conf),
4550 					  &submit);
4551 
4552 			set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
4553 			set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4554 			for (j = 0; j < conf->raid_disks; j++)
4555 				if (j != sh2->pd_idx &&
4556 				    j != sh2->qd_idx &&
4557 				    !test_bit(R5_Expanded, &sh2->dev[j].flags))
4558 					break;
4559 			if (j == conf->raid_disks) {
4560 				set_bit(STRIPE_EXPAND_READY, &sh2->state);
4561 				set_bit(STRIPE_HANDLE, &sh2->state);
4562 			}
4563 			raid5_release_stripe(sh2);
4564 
4565 		}
4566 	/* done submitting copies, wait for them to complete */
4567 	async_tx_quiesce(&tx);
4568 }
4569 
4570 /*
4571  * handle_stripe - do things to a stripe.
4572  *
4573  * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4574  * state of various bits to see what needs to be done.
4575  * Possible results:
4576  *    return some read requests which now have data
4577  *    return some write requests which are safely on storage
4578  *    schedule a read on some buffers
4579  *    schedule a write of some buffers
4580  *    return confirmation of parity correctness
4581  *
4582  */
4583 
4584 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4585 {
4586 	struct r5conf *conf = sh->raid_conf;
4587 	int disks = sh->disks;
4588 	struct r5dev *dev;
4589 	int i;
4590 	int do_recovery = 0;
4591 
4592 	memset(s, 0, sizeof(*s));
4593 
4594 	s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4595 	s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4596 	s->failed_num[0] = -1;
4597 	s->failed_num[1] = -1;
4598 	s->log_failed = r5l_log_disk_error(conf);
4599 
4600 	/* Now to look around and see what can be done */
4601 	rcu_read_lock();
4602 	for (i=disks; i--; ) {
4603 		struct md_rdev *rdev;
4604 		sector_t first_bad;
4605 		int bad_sectors;
4606 		int is_bad = 0;
4607 
4608 		dev = &sh->dev[i];
4609 
4610 		pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4611 			 i, dev->flags,
4612 			 dev->toread, dev->towrite, dev->written);
4613 		/* maybe we can reply to a read
4614 		 *
4615 		 * new wantfill requests are only permitted while
4616 		 * ops_complete_biofill is guaranteed to be inactive
4617 		 */
4618 		if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4619 		    !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4620 			set_bit(R5_Wantfill, &dev->flags);
4621 
4622 		/* now count some things */
4623 		if (test_bit(R5_LOCKED, &dev->flags))
4624 			s->locked++;
4625 		if (test_bit(R5_UPTODATE, &dev->flags))
4626 			s->uptodate++;
4627 		if (test_bit(R5_Wantcompute, &dev->flags)) {
4628 			s->compute++;
4629 			BUG_ON(s->compute > 2);
4630 		}
4631 
4632 		if (test_bit(R5_Wantfill, &dev->flags))
4633 			s->to_fill++;
4634 		else if (dev->toread)
4635 			s->to_read++;
4636 		if (dev->towrite) {
4637 			s->to_write++;
4638 			if (!test_bit(R5_OVERWRITE, &dev->flags))
4639 				s->non_overwrite++;
4640 		}
4641 		if (dev->written)
4642 			s->written++;
4643 		/* Prefer to use the replacement for reads, but only
4644 		 * if it is recovered enough and has no bad blocks.
4645 		 */
4646 		rdev = rcu_dereference(conf->disks[i].replacement);
4647 		if (rdev && !test_bit(Faulty, &rdev->flags) &&
4648 		    rdev->recovery_offset >= sh->sector + RAID5_STRIPE_SECTORS(conf) &&
4649 		    !is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
4650 				 &first_bad, &bad_sectors))
4651 			set_bit(R5_ReadRepl, &dev->flags);
4652 		else {
4653 			if (rdev && !test_bit(Faulty, &rdev->flags))
4654 				set_bit(R5_NeedReplace, &dev->flags);
4655 			else
4656 				clear_bit(R5_NeedReplace, &dev->flags);
4657 			rdev = rcu_dereference(conf->disks[i].rdev);
4658 			clear_bit(R5_ReadRepl, &dev->flags);
4659 		}
4660 		if (rdev && test_bit(Faulty, &rdev->flags))
4661 			rdev = NULL;
4662 		if (rdev) {
4663 			is_bad = is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
4664 					     &first_bad, &bad_sectors);
4665 			if (s->blocked_rdev == NULL
4666 			    && (test_bit(Blocked, &rdev->flags)
4667 				|| is_bad < 0)) {
4668 				if (is_bad < 0)
4669 					set_bit(BlockedBadBlocks,
4670 						&rdev->flags);
4671 				s->blocked_rdev = rdev;
4672 				atomic_inc(&rdev->nr_pending);
4673 			}
4674 		}
4675 		clear_bit(R5_Insync, &dev->flags);
4676 		if (!rdev)
4677 			/* Not in-sync */;
4678 		else if (is_bad) {
4679 			/* also not in-sync */
4680 			if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4681 			    test_bit(R5_UPTODATE, &dev->flags)) {
4682 				/* treat as in-sync, but with a read error
4683 				 * which we can now try to correct
4684 				 */
4685 				set_bit(R5_Insync, &dev->flags);
4686 				set_bit(R5_ReadError, &dev->flags);
4687 			}
4688 		} else if (test_bit(In_sync, &rdev->flags))
4689 			set_bit(R5_Insync, &dev->flags);
4690 		else if (sh->sector + RAID5_STRIPE_SECTORS(conf) <= rdev->recovery_offset)
4691 			/* in sync if before recovery_offset */
4692 			set_bit(R5_Insync, &dev->flags);
4693 		else if (test_bit(R5_UPTODATE, &dev->flags) &&
4694 			 test_bit(R5_Expanded, &dev->flags))
4695 			/* If we've reshaped into here, we assume it is Insync.
4696 			 * We will shortly update recovery_offset to make
4697 			 * it official.
4698 			 */
4699 			set_bit(R5_Insync, &dev->flags);
4700 
4701 		if (test_bit(R5_WriteError, &dev->flags)) {
4702 			/* This flag does not apply to '.replacement'
4703 			 * only to .rdev, so make sure to check that*/
4704 			struct md_rdev *rdev2 = rcu_dereference(
4705 				conf->disks[i].rdev);
4706 			if (rdev2 == rdev)
4707 				clear_bit(R5_Insync, &dev->flags);
4708 			if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4709 				s->handle_bad_blocks = 1;
4710 				atomic_inc(&rdev2->nr_pending);
4711 			} else
4712 				clear_bit(R5_WriteError, &dev->flags);
4713 		}
4714 		if (test_bit(R5_MadeGood, &dev->flags)) {
4715 			/* This flag does not apply to '.replacement'
4716 			 * only to .rdev, so make sure to check that*/
4717 			struct md_rdev *rdev2 = rcu_dereference(
4718 				conf->disks[i].rdev);
4719 			if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4720 				s->handle_bad_blocks = 1;
4721 				atomic_inc(&rdev2->nr_pending);
4722 			} else
4723 				clear_bit(R5_MadeGood, &dev->flags);
4724 		}
4725 		if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4726 			struct md_rdev *rdev2 = rcu_dereference(
4727 				conf->disks[i].replacement);
4728 			if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4729 				s->handle_bad_blocks = 1;
4730 				atomic_inc(&rdev2->nr_pending);
4731 			} else
4732 				clear_bit(R5_MadeGoodRepl, &dev->flags);
4733 		}
4734 		if (!test_bit(R5_Insync, &dev->flags)) {
4735 			/* The ReadError flag will just be confusing now */
4736 			clear_bit(R5_ReadError, &dev->flags);
4737 			clear_bit(R5_ReWrite, &dev->flags);
4738 		}
4739 		if (test_bit(R5_ReadError, &dev->flags))
4740 			clear_bit(R5_Insync, &dev->flags);
4741 		if (!test_bit(R5_Insync, &dev->flags)) {
4742 			if (s->failed < 2)
4743 				s->failed_num[s->failed] = i;
4744 			s->failed++;
4745 			if (rdev && !test_bit(Faulty, &rdev->flags))
4746 				do_recovery = 1;
4747 			else if (!rdev) {
4748 				rdev = rcu_dereference(
4749 				    conf->disks[i].replacement);
4750 				if (rdev && !test_bit(Faulty, &rdev->flags))
4751 					do_recovery = 1;
4752 			}
4753 		}
4754 
4755 		if (test_bit(R5_InJournal, &dev->flags))
4756 			s->injournal++;
4757 		if (test_bit(R5_InJournal, &dev->flags) && dev->written)
4758 			s->just_cached++;
4759 	}
4760 	if (test_bit(STRIPE_SYNCING, &sh->state)) {
4761 		/* If there is a failed device being replaced,
4762 		 *     we must be recovering.
4763 		 * else if we are after recovery_cp, we must be syncing
4764 		 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4765 		 * else we can only be replacing
4766 		 * sync and recovery both need to read all devices, and so
4767 		 * use the same flag.
4768 		 */
4769 		if (do_recovery ||
4770 		    sh->sector >= conf->mddev->recovery_cp ||
4771 		    test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4772 			s->syncing = 1;
4773 		else
4774 			s->replacing = 1;
4775 	}
4776 	rcu_read_unlock();
4777 }
4778 
4779 /*
4780  * Return '1' if this is a member of batch, or '0' if it is a lone stripe or
4781  * a head which can now be handled.
4782  */
4783 static int clear_batch_ready(struct stripe_head *sh)
4784 {
4785 	struct stripe_head *tmp;
4786 	if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4787 		return (sh->batch_head && sh->batch_head != sh);
4788 	spin_lock(&sh->stripe_lock);
4789 	if (!sh->batch_head) {
4790 		spin_unlock(&sh->stripe_lock);
4791 		return 0;
4792 	}
4793 
4794 	/*
4795 	 * this stripe could be added to a batch list before we check
4796 	 * BATCH_READY, skips it
4797 	 */
4798 	if (sh->batch_head != sh) {
4799 		spin_unlock(&sh->stripe_lock);
4800 		return 1;
4801 	}
4802 	spin_lock(&sh->batch_lock);
4803 	list_for_each_entry(tmp, &sh->batch_list, batch_list)
4804 		clear_bit(STRIPE_BATCH_READY, &tmp->state);
4805 	spin_unlock(&sh->batch_lock);
4806 	spin_unlock(&sh->stripe_lock);
4807 
4808 	/*
4809 	 * BATCH_READY is cleared, no new stripes can be added.
4810 	 * batch_list can be accessed without lock
4811 	 */
4812 	return 0;
4813 }
4814 
4815 static void break_stripe_batch_list(struct stripe_head *head_sh,
4816 				    unsigned long handle_flags)
4817 {
4818 	struct stripe_head *sh, *next;
4819 	int i;
4820 	int do_wakeup = 0;
4821 
4822 	list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4823 
4824 		list_del_init(&sh->batch_list);
4825 
4826 		WARN_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4827 					  (1 << STRIPE_SYNCING) |
4828 					  (1 << STRIPE_REPLACED) |
4829 					  (1 << STRIPE_DELAYED) |
4830 					  (1 << STRIPE_BIT_DELAY) |
4831 					  (1 << STRIPE_FULL_WRITE) |
4832 					  (1 << STRIPE_BIOFILL_RUN) |
4833 					  (1 << STRIPE_COMPUTE_RUN)  |
4834 					  (1 << STRIPE_DISCARD) |
4835 					  (1 << STRIPE_BATCH_READY) |
4836 					  (1 << STRIPE_BATCH_ERR) |
4837 					  (1 << STRIPE_BITMAP_PENDING)),
4838 			"stripe state: %lx\n", sh->state);
4839 		WARN_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4840 					      (1 << STRIPE_REPLACED)),
4841 			"head stripe state: %lx\n", head_sh->state);
4842 
4843 		set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4844 					    (1 << STRIPE_PREREAD_ACTIVE) |
4845 					    (1 << STRIPE_DEGRADED) |
4846 					    (1 << STRIPE_ON_UNPLUG_LIST)),
4847 			      head_sh->state & (1 << STRIPE_INSYNC));
4848 
4849 		sh->check_state = head_sh->check_state;
4850 		sh->reconstruct_state = head_sh->reconstruct_state;
4851 		spin_lock_irq(&sh->stripe_lock);
4852 		sh->batch_head = NULL;
4853 		spin_unlock_irq(&sh->stripe_lock);
4854 		for (i = 0; i < sh->disks; i++) {
4855 			if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4856 				do_wakeup = 1;
4857 			sh->dev[i].flags = head_sh->dev[i].flags &
4858 				(~((1 << R5_WriteError) | (1 << R5_Overlap)));
4859 		}
4860 		if (handle_flags == 0 ||
4861 		    sh->state & handle_flags)
4862 			set_bit(STRIPE_HANDLE, &sh->state);
4863 		raid5_release_stripe(sh);
4864 	}
4865 	spin_lock_irq(&head_sh->stripe_lock);
4866 	head_sh->batch_head = NULL;
4867 	spin_unlock_irq(&head_sh->stripe_lock);
4868 	for (i = 0; i < head_sh->disks; i++)
4869 		if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4870 			do_wakeup = 1;
4871 	if (head_sh->state & handle_flags)
4872 		set_bit(STRIPE_HANDLE, &head_sh->state);
4873 
4874 	if (do_wakeup)
4875 		wake_up(&head_sh->raid_conf->wait_for_overlap);
4876 }
4877 
4878 static void handle_stripe(struct stripe_head *sh)
4879 {
4880 	struct stripe_head_state s;
4881 	struct r5conf *conf = sh->raid_conf;
4882 	int i;
4883 	int prexor;
4884 	int disks = sh->disks;
4885 	struct r5dev *pdev, *qdev;
4886 
4887 	clear_bit(STRIPE_HANDLE, &sh->state);
4888 
4889 	/*
4890 	 * handle_stripe should not continue handle the batched stripe, only
4891 	 * the head of batch list or lone stripe can continue. Otherwise we
4892 	 * could see break_stripe_batch_list warns about the STRIPE_ACTIVE
4893 	 * is set for the batched stripe.
4894 	 */
4895 	if (clear_batch_ready(sh))
4896 		return;
4897 
4898 	if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4899 		/* already being handled, ensure it gets handled
4900 		 * again when current action finishes */
4901 		set_bit(STRIPE_HANDLE, &sh->state);
4902 		return;
4903 	}
4904 
4905 	if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4906 		break_stripe_batch_list(sh, 0);
4907 
4908 	if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4909 		spin_lock(&sh->stripe_lock);
4910 		/*
4911 		 * Cannot process 'sync' concurrently with 'discard'.
4912 		 * Flush data in r5cache before 'sync'.
4913 		 */
4914 		if (!test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state) &&
4915 		    !test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) &&
4916 		    !test_bit(STRIPE_DISCARD, &sh->state) &&
4917 		    test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4918 			set_bit(STRIPE_SYNCING, &sh->state);
4919 			clear_bit(STRIPE_INSYNC, &sh->state);
4920 			clear_bit(STRIPE_REPLACED, &sh->state);
4921 		}
4922 		spin_unlock(&sh->stripe_lock);
4923 	}
4924 	clear_bit(STRIPE_DELAYED, &sh->state);
4925 
4926 	pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4927 		"pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4928 	       (unsigned long long)sh->sector, sh->state,
4929 	       atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4930 	       sh->check_state, sh->reconstruct_state);
4931 
4932 	analyse_stripe(sh, &s);
4933 
4934 	if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4935 		goto finish;
4936 
4937 	if (s.handle_bad_blocks ||
4938 	    test_bit(MD_SB_CHANGE_PENDING, &conf->mddev->sb_flags)) {
4939 		set_bit(STRIPE_HANDLE, &sh->state);
4940 		goto finish;
4941 	}
4942 
4943 	if (unlikely(s.blocked_rdev)) {
4944 		if (s.syncing || s.expanding || s.expanded ||
4945 		    s.replacing || s.to_write || s.written) {
4946 			set_bit(STRIPE_HANDLE, &sh->state);
4947 			goto finish;
4948 		}
4949 		/* There is nothing for the blocked_rdev to block */
4950 		rdev_dec_pending(s.blocked_rdev, conf->mddev);
4951 		s.blocked_rdev = NULL;
4952 	}
4953 
4954 	if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4955 		set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4956 		set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4957 	}
4958 
4959 	pr_debug("locked=%d uptodate=%d to_read=%d"
4960 	       " to_write=%d failed=%d failed_num=%d,%d\n",
4961 	       s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4962 	       s.failed_num[0], s.failed_num[1]);
4963 	/*
4964 	 * check if the array has lost more than max_degraded devices and,
4965 	 * if so, some requests might need to be failed.
4966 	 *
4967 	 * When journal device failed (log_failed), we will only process
4968 	 * the stripe if there is data need write to raid disks
4969 	 */
4970 	if (s.failed > conf->max_degraded ||
4971 	    (s.log_failed && s.injournal == 0)) {
4972 		sh->check_state = 0;
4973 		sh->reconstruct_state = 0;
4974 		break_stripe_batch_list(sh, 0);
4975 		if (s.to_read+s.to_write+s.written)
4976 			handle_failed_stripe(conf, sh, &s, disks);
4977 		if (s.syncing + s.replacing)
4978 			handle_failed_sync(conf, sh, &s);
4979 	}
4980 
4981 	/* Now we check to see if any write operations have recently
4982 	 * completed
4983 	 */
4984 	prexor = 0;
4985 	if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4986 		prexor = 1;
4987 	if (sh->reconstruct_state == reconstruct_state_drain_result ||
4988 	    sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4989 		sh->reconstruct_state = reconstruct_state_idle;
4990 
4991 		/* All the 'written' buffers and the parity block are ready to
4992 		 * be written back to disk
4993 		 */
4994 		BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4995 		       !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4996 		BUG_ON(sh->qd_idx >= 0 &&
4997 		       !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4998 		       !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4999 		for (i = disks; i--; ) {
5000 			struct r5dev *dev = &sh->dev[i];
5001 			if (test_bit(R5_LOCKED, &dev->flags) &&
5002 				(i == sh->pd_idx || i == sh->qd_idx ||
5003 				 dev->written || test_bit(R5_InJournal,
5004 							  &dev->flags))) {
5005 				pr_debug("Writing block %d\n", i);
5006 				set_bit(R5_Wantwrite, &dev->flags);
5007 				if (prexor)
5008 					continue;
5009 				if (s.failed > 1)
5010 					continue;
5011 				if (!test_bit(R5_Insync, &dev->flags) ||
5012 				    ((i == sh->pd_idx || i == sh->qd_idx)  &&
5013 				     s.failed == 0))
5014 					set_bit(STRIPE_INSYNC, &sh->state);
5015 			}
5016 		}
5017 		if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5018 			s.dec_preread_active = 1;
5019 	}
5020 
5021 	/*
5022 	 * might be able to return some write requests if the parity blocks
5023 	 * are safe, or on a failed drive
5024 	 */
5025 	pdev = &sh->dev[sh->pd_idx];
5026 	s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
5027 		|| (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
5028 	qdev = &sh->dev[sh->qd_idx];
5029 	s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
5030 		|| (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
5031 		|| conf->level < 6;
5032 
5033 	if (s.written &&
5034 	    (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
5035 			     && !test_bit(R5_LOCKED, &pdev->flags)
5036 			     && (test_bit(R5_UPTODATE, &pdev->flags) ||
5037 				 test_bit(R5_Discard, &pdev->flags))))) &&
5038 	    (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
5039 			     && !test_bit(R5_LOCKED, &qdev->flags)
5040 			     && (test_bit(R5_UPTODATE, &qdev->flags) ||
5041 				 test_bit(R5_Discard, &qdev->flags))))))
5042 		handle_stripe_clean_event(conf, sh, disks);
5043 
5044 	if (s.just_cached)
5045 		r5c_handle_cached_data_endio(conf, sh, disks);
5046 	log_stripe_write_finished(sh);
5047 
5048 	/* Now we might consider reading some blocks, either to check/generate
5049 	 * parity, or to satisfy requests
5050 	 * or to load a block that is being partially written.
5051 	 */
5052 	if (s.to_read || s.non_overwrite
5053 	    || (s.to_write && s.failed)
5054 	    || (s.syncing && (s.uptodate + s.compute < disks))
5055 	    || s.replacing
5056 	    || s.expanding)
5057 		handle_stripe_fill(sh, &s, disks);
5058 
5059 	/*
5060 	 * When the stripe finishes full journal write cycle (write to journal
5061 	 * and raid disk), this is the clean up procedure so it is ready for
5062 	 * next operation.
5063 	 */
5064 	r5c_finish_stripe_write_out(conf, sh, &s);
5065 
5066 	/*
5067 	 * Now to consider new write requests, cache write back and what else,
5068 	 * if anything should be read.  We do not handle new writes when:
5069 	 * 1/ A 'write' operation (copy+xor) is already in flight.
5070 	 * 2/ A 'check' operation is in flight, as it may clobber the parity
5071 	 *    block.
5072 	 * 3/ A r5c cache log write is in flight.
5073 	 */
5074 
5075 	if (!sh->reconstruct_state && !sh->check_state && !sh->log_io) {
5076 		if (!r5c_is_writeback(conf->log)) {
5077 			if (s.to_write)
5078 				handle_stripe_dirtying(conf, sh, &s, disks);
5079 		} else { /* write back cache */
5080 			int ret = 0;
5081 
5082 			/* First, try handle writes in caching phase */
5083 			if (s.to_write)
5084 				ret = r5c_try_caching_write(conf, sh, &s,
5085 							    disks);
5086 			/*
5087 			 * If caching phase failed: ret == -EAGAIN
5088 			 *    OR
5089 			 * stripe under reclaim: !caching && injournal
5090 			 *
5091 			 * fall back to handle_stripe_dirtying()
5092 			 */
5093 			if (ret == -EAGAIN ||
5094 			    /* stripe under reclaim: !caching && injournal */
5095 			    (!test_bit(STRIPE_R5C_CACHING, &sh->state) &&
5096 			     s.injournal > 0)) {
5097 				ret = handle_stripe_dirtying(conf, sh, &s,
5098 							     disks);
5099 				if (ret == -EAGAIN)
5100 					goto finish;
5101 			}
5102 		}
5103 	}
5104 
5105 	/* maybe we need to check and possibly fix the parity for this stripe
5106 	 * Any reads will already have been scheduled, so we just see if enough
5107 	 * data is available.  The parity check is held off while parity
5108 	 * dependent operations are in flight.
5109 	 */
5110 	if (sh->check_state ||
5111 	    (s.syncing && s.locked == 0 &&
5112 	     !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
5113 	     !test_bit(STRIPE_INSYNC, &sh->state))) {
5114 		if (conf->level == 6)
5115 			handle_parity_checks6(conf, sh, &s, disks);
5116 		else
5117 			handle_parity_checks5(conf, sh, &s, disks);
5118 	}
5119 
5120 	if ((s.replacing || s.syncing) && s.locked == 0
5121 	    && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
5122 	    && !test_bit(STRIPE_REPLACED, &sh->state)) {
5123 		/* Write out to replacement devices where possible */
5124 		for (i = 0; i < conf->raid_disks; i++)
5125 			if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
5126 				WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
5127 				set_bit(R5_WantReplace, &sh->dev[i].flags);
5128 				set_bit(R5_LOCKED, &sh->dev[i].flags);
5129 				s.locked++;
5130 			}
5131 		if (s.replacing)
5132 			set_bit(STRIPE_INSYNC, &sh->state);
5133 		set_bit(STRIPE_REPLACED, &sh->state);
5134 	}
5135 	if ((s.syncing || s.replacing) && s.locked == 0 &&
5136 	    !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
5137 	    test_bit(STRIPE_INSYNC, &sh->state)) {
5138 		md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), 1);
5139 		clear_bit(STRIPE_SYNCING, &sh->state);
5140 		if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
5141 			wake_up(&conf->wait_for_overlap);
5142 	}
5143 
5144 	/* If the failed drives are just a ReadError, then we might need
5145 	 * to progress the repair/check process
5146 	 */
5147 	if (s.failed <= conf->max_degraded && !conf->mddev->ro)
5148 		for (i = 0; i < s.failed; i++) {
5149 			struct r5dev *dev = &sh->dev[s.failed_num[i]];
5150 			if (test_bit(R5_ReadError, &dev->flags)
5151 			    && !test_bit(R5_LOCKED, &dev->flags)
5152 			    && test_bit(R5_UPTODATE, &dev->flags)
5153 				) {
5154 				if (!test_bit(R5_ReWrite, &dev->flags)) {
5155 					set_bit(R5_Wantwrite, &dev->flags);
5156 					set_bit(R5_ReWrite, &dev->flags);
5157 				} else
5158 					/* let's read it back */
5159 					set_bit(R5_Wantread, &dev->flags);
5160 				set_bit(R5_LOCKED, &dev->flags);
5161 				s.locked++;
5162 			}
5163 		}
5164 
5165 	/* Finish reconstruct operations initiated by the expansion process */
5166 	if (sh->reconstruct_state == reconstruct_state_result) {
5167 		struct stripe_head *sh_src
5168 			= raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
5169 		if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
5170 			/* sh cannot be written until sh_src has been read.
5171 			 * so arrange for sh to be delayed a little
5172 			 */
5173 			set_bit(STRIPE_DELAYED, &sh->state);
5174 			set_bit(STRIPE_HANDLE, &sh->state);
5175 			if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
5176 					      &sh_src->state))
5177 				atomic_inc(&conf->preread_active_stripes);
5178 			raid5_release_stripe(sh_src);
5179 			goto finish;
5180 		}
5181 		if (sh_src)
5182 			raid5_release_stripe(sh_src);
5183 
5184 		sh->reconstruct_state = reconstruct_state_idle;
5185 		clear_bit(STRIPE_EXPANDING, &sh->state);
5186 		for (i = conf->raid_disks; i--; ) {
5187 			set_bit(R5_Wantwrite, &sh->dev[i].flags);
5188 			set_bit(R5_LOCKED, &sh->dev[i].flags);
5189 			s.locked++;
5190 		}
5191 	}
5192 
5193 	if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
5194 	    !sh->reconstruct_state) {
5195 		/* Need to write out all blocks after computing parity */
5196 		sh->disks = conf->raid_disks;
5197 		stripe_set_idx(sh->sector, conf, 0, sh);
5198 		schedule_reconstruction(sh, &s, 1, 1);
5199 	} else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
5200 		clear_bit(STRIPE_EXPAND_READY, &sh->state);
5201 		atomic_dec(&conf->reshape_stripes);
5202 		wake_up(&conf->wait_for_overlap);
5203 		md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), 1);
5204 	}
5205 
5206 	if (s.expanding && s.locked == 0 &&
5207 	    !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
5208 		handle_stripe_expansion(conf, sh);
5209 
5210 finish:
5211 	/* wait for this device to become unblocked */
5212 	if (unlikely(s.blocked_rdev)) {
5213 		if (conf->mddev->external)
5214 			md_wait_for_blocked_rdev(s.blocked_rdev,
5215 						 conf->mddev);
5216 		else
5217 			/* Internal metadata will immediately
5218 			 * be written by raid5d, so we don't
5219 			 * need to wait here.
5220 			 */
5221 			rdev_dec_pending(s.blocked_rdev,
5222 					 conf->mddev);
5223 	}
5224 
5225 	if (s.handle_bad_blocks)
5226 		for (i = disks; i--; ) {
5227 			struct md_rdev *rdev;
5228 			struct r5dev *dev = &sh->dev[i];
5229 			if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
5230 				/* We own a safe reference to the rdev */
5231 				rdev = conf->disks[i].rdev;
5232 				if (!rdev_set_badblocks(rdev, sh->sector,
5233 							RAID5_STRIPE_SECTORS(conf), 0))
5234 					md_error(conf->mddev, rdev);
5235 				rdev_dec_pending(rdev, conf->mddev);
5236 			}
5237 			if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
5238 				rdev = conf->disks[i].rdev;
5239 				rdev_clear_badblocks(rdev, sh->sector,
5240 						     RAID5_STRIPE_SECTORS(conf), 0);
5241 				rdev_dec_pending(rdev, conf->mddev);
5242 			}
5243 			if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
5244 				rdev = conf->disks[i].replacement;
5245 				if (!rdev)
5246 					/* rdev have been moved down */
5247 					rdev = conf->disks[i].rdev;
5248 				rdev_clear_badblocks(rdev, sh->sector,
5249 						     RAID5_STRIPE_SECTORS(conf), 0);
5250 				rdev_dec_pending(rdev, conf->mddev);
5251 			}
5252 		}
5253 
5254 	if (s.ops_request)
5255 		raid_run_ops(sh, s.ops_request);
5256 
5257 	ops_run_io(sh, &s);
5258 
5259 	if (s.dec_preread_active) {
5260 		/* We delay this until after ops_run_io so that if make_request
5261 		 * is waiting on a flush, it won't continue until the writes
5262 		 * have actually been submitted.
5263 		 */
5264 		atomic_dec(&conf->preread_active_stripes);
5265 		if (atomic_read(&conf->preread_active_stripes) <
5266 		    IO_THRESHOLD)
5267 			md_wakeup_thread(conf->mddev->thread);
5268 	}
5269 
5270 	clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
5271 }
5272 
5273 static void raid5_activate_delayed(struct r5conf *conf)
5274 {
5275 	if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
5276 		while (!list_empty(&conf->delayed_list)) {
5277 			struct list_head *l = conf->delayed_list.next;
5278 			struct stripe_head *sh;
5279 			sh = list_entry(l, struct stripe_head, lru);
5280 			list_del_init(l);
5281 			clear_bit(STRIPE_DELAYED, &sh->state);
5282 			if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5283 				atomic_inc(&conf->preread_active_stripes);
5284 			list_add_tail(&sh->lru, &conf->hold_list);
5285 			raid5_wakeup_stripe_thread(sh);
5286 		}
5287 	}
5288 }
5289 
5290 static void activate_bit_delay(struct r5conf *conf,
5291 	struct list_head *temp_inactive_list)
5292 {
5293 	/* device_lock is held */
5294 	struct list_head head;
5295 	list_add(&head, &conf->bitmap_list);
5296 	list_del_init(&conf->bitmap_list);
5297 	while (!list_empty(&head)) {
5298 		struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
5299 		int hash;
5300 		list_del_init(&sh->lru);
5301 		atomic_inc(&sh->count);
5302 		hash = sh->hash_lock_index;
5303 		__release_stripe(conf, sh, &temp_inactive_list[hash]);
5304 	}
5305 }
5306 
5307 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
5308 {
5309 	struct r5conf *conf = mddev->private;
5310 	sector_t sector = bio->bi_iter.bi_sector;
5311 	unsigned int chunk_sectors;
5312 	unsigned int bio_sectors = bio_sectors(bio);
5313 
5314 	WARN_ON_ONCE(bio->bi_bdev->bd_partno);
5315 
5316 	chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
5317 	return  chunk_sectors >=
5318 		((sector & (chunk_sectors - 1)) + bio_sectors);
5319 }
5320 
5321 /*
5322  *  add bio to the retry LIFO  ( in O(1) ... we are in interrupt )
5323  *  later sampled by raid5d.
5324  */
5325 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
5326 {
5327 	unsigned long flags;
5328 
5329 	spin_lock_irqsave(&conf->device_lock, flags);
5330 
5331 	bi->bi_next = conf->retry_read_aligned_list;
5332 	conf->retry_read_aligned_list = bi;
5333 
5334 	spin_unlock_irqrestore(&conf->device_lock, flags);
5335 	md_wakeup_thread(conf->mddev->thread);
5336 }
5337 
5338 static struct bio *remove_bio_from_retry(struct r5conf *conf,
5339 					 unsigned int *offset)
5340 {
5341 	struct bio *bi;
5342 
5343 	bi = conf->retry_read_aligned;
5344 	if (bi) {
5345 		*offset = conf->retry_read_offset;
5346 		conf->retry_read_aligned = NULL;
5347 		return bi;
5348 	}
5349 	bi = conf->retry_read_aligned_list;
5350 	if(bi) {
5351 		conf->retry_read_aligned_list = bi->bi_next;
5352 		bi->bi_next = NULL;
5353 		*offset = 0;
5354 	}
5355 
5356 	return bi;
5357 }
5358 
5359 /*
5360  *  The "raid5_align_endio" should check if the read succeeded and if it
5361  *  did, call bio_endio on the original bio (having bio_put the new bio
5362  *  first).
5363  *  If the read failed..
5364  */
5365 static void raid5_align_endio(struct bio *bi)
5366 {
5367 	struct bio* raid_bi  = bi->bi_private;
5368 	struct mddev *mddev;
5369 	struct r5conf *conf;
5370 	struct md_rdev *rdev;
5371 	blk_status_t error = bi->bi_status;
5372 
5373 	bio_put(bi);
5374 
5375 	rdev = (void*)raid_bi->bi_next;
5376 	raid_bi->bi_next = NULL;
5377 	mddev = rdev->mddev;
5378 	conf = mddev->private;
5379 
5380 	rdev_dec_pending(rdev, conf->mddev);
5381 
5382 	if (!error) {
5383 		bio_endio(raid_bi);
5384 		if (atomic_dec_and_test(&conf->active_aligned_reads))
5385 			wake_up(&conf->wait_for_quiescent);
5386 		return;
5387 	}
5388 
5389 	pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
5390 
5391 	add_bio_to_retry(raid_bi, conf);
5392 }
5393 
5394 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
5395 {
5396 	struct r5conf *conf = mddev->private;
5397 	struct bio *align_bio;
5398 	struct md_rdev *rdev;
5399 	sector_t sector, end_sector, first_bad;
5400 	int bad_sectors, dd_idx;
5401 
5402 	if (!in_chunk_boundary(mddev, raid_bio)) {
5403 		pr_debug("%s: non aligned\n", __func__);
5404 		return 0;
5405 	}
5406 
5407 	sector = raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector, 0,
5408 				      &dd_idx, NULL);
5409 	end_sector = bio_end_sector(raid_bio);
5410 
5411 	rcu_read_lock();
5412 	if (r5c_big_stripe_cached(conf, sector))
5413 		goto out_rcu_unlock;
5414 
5415 	rdev = rcu_dereference(conf->disks[dd_idx].replacement);
5416 	if (!rdev || test_bit(Faulty, &rdev->flags) ||
5417 	    rdev->recovery_offset < end_sector) {
5418 		rdev = rcu_dereference(conf->disks[dd_idx].rdev);
5419 		if (!rdev)
5420 			goto out_rcu_unlock;
5421 		if (test_bit(Faulty, &rdev->flags) ||
5422 		    !(test_bit(In_sync, &rdev->flags) ||
5423 		      rdev->recovery_offset >= end_sector))
5424 			goto out_rcu_unlock;
5425 	}
5426 
5427 	atomic_inc(&rdev->nr_pending);
5428 	rcu_read_unlock();
5429 
5430 	align_bio = bio_clone_fast(raid_bio, GFP_NOIO, &mddev->bio_set);
5431 	bio_set_dev(align_bio, rdev->bdev);
5432 	align_bio->bi_end_io = raid5_align_endio;
5433 	align_bio->bi_private = raid_bio;
5434 	align_bio->bi_iter.bi_sector = sector;
5435 
5436 	raid_bio->bi_next = (void *)rdev;
5437 
5438 	if (is_badblock(rdev, sector, bio_sectors(align_bio), &first_bad,
5439 			&bad_sectors)) {
5440 		bio_put(align_bio);
5441 		rdev_dec_pending(rdev, mddev);
5442 		return 0;
5443 	}
5444 
5445 	/* No reshape active, so we can trust rdev->data_offset */
5446 	align_bio->bi_iter.bi_sector += rdev->data_offset;
5447 
5448 	spin_lock_irq(&conf->device_lock);
5449 	wait_event_lock_irq(conf->wait_for_quiescent, conf->quiesce == 0,
5450 			    conf->device_lock);
5451 	atomic_inc(&conf->active_aligned_reads);
5452 	spin_unlock_irq(&conf->device_lock);
5453 
5454 	if (mddev->gendisk)
5455 		trace_block_bio_remap(align_bio, disk_devt(mddev->gendisk),
5456 				      raid_bio->bi_iter.bi_sector);
5457 	submit_bio_noacct(align_bio);
5458 	return 1;
5459 
5460 out_rcu_unlock:
5461 	rcu_read_unlock();
5462 	return 0;
5463 }
5464 
5465 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
5466 {
5467 	struct bio *split;
5468 	sector_t sector = raid_bio->bi_iter.bi_sector;
5469 	unsigned chunk_sects = mddev->chunk_sectors;
5470 	unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
5471 
5472 	if (sectors < bio_sectors(raid_bio)) {
5473 		struct r5conf *conf = mddev->private;
5474 		split = bio_split(raid_bio, sectors, GFP_NOIO, &conf->bio_split);
5475 		bio_chain(split, raid_bio);
5476 		submit_bio_noacct(raid_bio);
5477 		raid_bio = split;
5478 	}
5479 
5480 	if (!raid5_read_one_chunk(mddev, raid_bio))
5481 		return raid_bio;
5482 
5483 	return NULL;
5484 }
5485 
5486 /* __get_priority_stripe - get the next stripe to process
5487  *
5488  * Full stripe writes are allowed to pass preread active stripes up until
5489  * the bypass_threshold is exceeded.  In general the bypass_count
5490  * increments when the handle_list is handled before the hold_list; however, it
5491  * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
5492  * stripe with in flight i/o.  The bypass_count will be reset when the
5493  * head of the hold_list has changed, i.e. the head was promoted to the
5494  * handle_list.
5495  */
5496 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
5497 {
5498 	struct stripe_head *sh, *tmp;
5499 	struct list_head *handle_list = NULL;
5500 	struct r5worker_group *wg;
5501 	bool second_try = !r5c_is_writeback(conf->log) &&
5502 		!r5l_log_disk_error(conf);
5503 	bool try_loprio = test_bit(R5C_LOG_TIGHT, &conf->cache_state) ||
5504 		r5l_log_disk_error(conf);
5505 
5506 again:
5507 	wg = NULL;
5508 	sh = NULL;
5509 	if (conf->worker_cnt_per_group == 0) {
5510 		handle_list = try_loprio ? &conf->loprio_list :
5511 					&conf->handle_list;
5512 	} else if (group != ANY_GROUP) {
5513 		handle_list = try_loprio ? &conf->worker_groups[group].loprio_list :
5514 				&conf->worker_groups[group].handle_list;
5515 		wg = &conf->worker_groups[group];
5516 	} else {
5517 		int i;
5518 		for (i = 0; i < conf->group_cnt; i++) {
5519 			handle_list = try_loprio ? &conf->worker_groups[i].loprio_list :
5520 				&conf->worker_groups[i].handle_list;
5521 			wg = &conf->worker_groups[i];
5522 			if (!list_empty(handle_list))
5523 				break;
5524 		}
5525 	}
5526 
5527 	pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
5528 		  __func__,
5529 		  list_empty(handle_list) ? "empty" : "busy",
5530 		  list_empty(&conf->hold_list) ? "empty" : "busy",
5531 		  atomic_read(&conf->pending_full_writes), conf->bypass_count);
5532 
5533 	if (!list_empty(handle_list)) {
5534 		sh = list_entry(handle_list->next, typeof(*sh), lru);
5535 
5536 		if (list_empty(&conf->hold_list))
5537 			conf->bypass_count = 0;
5538 		else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
5539 			if (conf->hold_list.next == conf->last_hold)
5540 				conf->bypass_count++;
5541 			else {
5542 				conf->last_hold = conf->hold_list.next;
5543 				conf->bypass_count -= conf->bypass_threshold;
5544 				if (conf->bypass_count < 0)
5545 					conf->bypass_count = 0;
5546 			}
5547 		}
5548 	} else if (!list_empty(&conf->hold_list) &&
5549 		   ((conf->bypass_threshold &&
5550 		     conf->bypass_count > conf->bypass_threshold) ||
5551 		    atomic_read(&conf->pending_full_writes) == 0)) {
5552 
5553 		list_for_each_entry(tmp, &conf->hold_list,  lru) {
5554 			if (conf->worker_cnt_per_group == 0 ||
5555 			    group == ANY_GROUP ||
5556 			    !cpu_online(tmp->cpu) ||
5557 			    cpu_to_group(tmp->cpu) == group) {
5558 				sh = tmp;
5559 				break;
5560 			}
5561 		}
5562 
5563 		if (sh) {
5564 			conf->bypass_count -= conf->bypass_threshold;
5565 			if (conf->bypass_count < 0)
5566 				conf->bypass_count = 0;
5567 		}
5568 		wg = NULL;
5569 	}
5570 
5571 	if (!sh) {
5572 		if (second_try)
5573 			return NULL;
5574 		second_try = true;
5575 		try_loprio = !try_loprio;
5576 		goto again;
5577 	}
5578 
5579 	if (wg) {
5580 		wg->stripes_cnt--;
5581 		sh->group = NULL;
5582 	}
5583 	list_del_init(&sh->lru);
5584 	BUG_ON(atomic_inc_return(&sh->count) != 1);
5585 	return sh;
5586 }
5587 
5588 struct raid5_plug_cb {
5589 	struct blk_plug_cb	cb;
5590 	struct list_head	list;
5591 	struct list_head	temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5592 };
5593 
5594 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5595 {
5596 	struct raid5_plug_cb *cb = container_of(
5597 		blk_cb, struct raid5_plug_cb, cb);
5598 	struct stripe_head *sh;
5599 	struct mddev *mddev = cb->cb.data;
5600 	struct r5conf *conf = mddev->private;
5601 	int cnt = 0;
5602 	int hash;
5603 
5604 	if (cb->list.next && !list_empty(&cb->list)) {
5605 		spin_lock_irq(&conf->device_lock);
5606 		while (!list_empty(&cb->list)) {
5607 			sh = list_first_entry(&cb->list, struct stripe_head, lru);
5608 			list_del_init(&sh->lru);
5609 			/*
5610 			 * avoid race release_stripe_plug() sees
5611 			 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5612 			 * is still in our list
5613 			 */
5614 			smp_mb__before_atomic();
5615 			clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5616 			/*
5617 			 * STRIPE_ON_RELEASE_LIST could be set here. In that
5618 			 * case, the count is always > 1 here
5619 			 */
5620 			hash = sh->hash_lock_index;
5621 			__release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5622 			cnt++;
5623 		}
5624 		spin_unlock_irq(&conf->device_lock);
5625 	}
5626 	release_inactive_stripe_list(conf, cb->temp_inactive_list,
5627 				     NR_STRIPE_HASH_LOCKS);
5628 	if (mddev->queue)
5629 		trace_block_unplug(mddev->queue, cnt, !from_schedule);
5630 	kfree(cb);
5631 }
5632 
5633 static void release_stripe_plug(struct mddev *mddev,
5634 				struct stripe_head *sh)
5635 {
5636 	struct blk_plug_cb *blk_cb = blk_check_plugged(
5637 		raid5_unplug, mddev,
5638 		sizeof(struct raid5_plug_cb));
5639 	struct raid5_plug_cb *cb;
5640 
5641 	if (!blk_cb) {
5642 		raid5_release_stripe(sh);
5643 		return;
5644 	}
5645 
5646 	cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5647 
5648 	if (cb->list.next == NULL) {
5649 		int i;
5650 		INIT_LIST_HEAD(&cb->list);
5651 		for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5652 			INIT_LIST_HEAD(cb->temp_inactive_list + i);
5653 	}
5654 
5655 	if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5656 		list_add_tail(&sh->lru, &cb->list);
5657 	else
5658 		raid5_release_stripe(sh);
5659 }
5660 
5661 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5662 {
5663 	struct r5conf *conf = mddev->private;
5664 	sector_t logical_sector, last_sector;
5665 	struct stripe_head *sh;
5666 	int stripe_sectors;
5667 
5668 	if (mddev->reshape_position != MaxSector)
5669 		/* Skip discard while reshape is happening */
5670 		return;
5671 
5672 	logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5673 	last_sector = bio_end_sector(bi);
5674 
5675 	bi->bi_next = NULL;
5676 
5677 	stripe_sectors = conf->chunk_sectors *
5678 		(conf->raid_disks - conf->max_degraded);
5679 	logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5680 					       stripe_sectors);
5681 	sector_div(last_sector, stripe_sectors);
5682 
5683 	logical_sector *= conf->chunk_sectors;
5684 	last_sector *= conf->chunk_sectors;
5685 
5686 	for (; logical_sector < last_sector;
5687 	     logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5688 		DEFINE_WAIT(w);
5689 		int d;
5690 	again:
5691 		sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5692 		prepare_to_wait(&conf->wait_for_overlap, &w,
5693 				TASK_UNINTERRUPTIBLE);
5694 		set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5695 		if (test_bit(STRIPE_SYNCING, &sh->state)) {
5696 			raid5_release_stripe(sh);
5697 			schedule();
5698 			goto again;
5699 		}
5700 		clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5701 		spin_lock_irq(&sh->stripe_lock);
5702 		for (d = 0; d < conf->raid_disks; d++) {
5703 			if (d == sh->pd_idx || d == sh->qd_idx)
5704 				continue;
5705 			if (sh->dev[d].towrite || sh->dev[d].toread) {
5706 				set_bit(R5_Overlap, &sh->dev[d].flags);
5707 				spin_unlock_irq(&sh->stripe_lock);
5708 				raid5_release_stripe(sh);
5709 				schedule();
5710 				goto again;
5711 			}
5712 		}
5713 		set_bit(STRIPE_DISCARD, &sh->state);
5714 		finish_wait(&conf->wait_for_overlap, &w);
5715 		sh->overwrite_disks = 0;
5716 		for (d = 0; d < conf->raid_disks; d++) {
5717 			if (d == sh->pd_idx || d == sh->qd_idx)
5718 				continue;
5719 			sh->dev[d].towrite = bi;
5720 			set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5721 			bio_inc_remaining(bi);
5722 			md_write_inc(mddev, bi);
5723 			sh->overwrite_disks++;
5724 		}
5725 		spin_unlock_irq(&sh->stripe_lock);
5726 		if (conf->mddev->bitmap) {
5727 			for (d = 0;
5728 			     d < conf->raid_disks - conf->max_degraded;
5729 			     d++)
5730 				md_bitmap_startwrite(mddev->bitmap,
5731 						     sh->sector,
5732 						     RAID5_STRIPE_SECTORS(conf),
5733 						     0);
5734 			sh->bm_seq = conf->seq_flush + 1;
5735 			set_bit(STRIPE_BIT_DELAY, &sh->state);
5736 		}
5737 
5738 		set_bit(STRIPE_HANDLE, &sh->state);
5739 		clear_bit(STRIPE_DELAYED, &sh->state);
5740 		if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5741 			atomic_inc(&conf->preread_active_stripes);
5742 		release_stripe_plug(mddev, sh);
5743 	}
5744 
5745 	bio_endio(bi);
5746 }
5747 
5748 static bool raid5_make_request(struct mddev *mddev, struct bio * bi)
5749 {
5750 	struct r5conf *conf = mddev->private;
5751 	int dd_idx;
5752 	sector_t new_sector;
5753 	sector_t logical_sector, last_sector;
5754 	struct stripe_head *sh;
5755 	const int rw = bio_data_dir(bi);
5756 	DEFINE_WAIT(w);
5757 	bool do_prepare;
5758 	bool do_flush = false;
5759 
5760 	if (unlikely(bi->bi_opf & REQ_PREFLUSH)) {
5761 		int ret = log_handle_flush_request(conf, bi);
5762 
5763 		if (ret == 0)
5764 			return true;
5765 		if (ret == -ENODEV) {
5766 			if (md_flush_request(mddev, bi))
5767 				return true;
5768 		}
5769 		/* ret == -EAGAIN, fallback */
5770 		/*
5771 		 * if r5l_handle_flush_request() didn't clear REQ_PREFLUSH,
5772 		 * we need to flush journal device
5773 		 */
5774 		do_flush = bi->bi_opf & REQ_PREFLUSH;
5775 	}
5776 
5777 	if (!md_write_start(mddev, bi))
5778 		return false;
5779 	/*
5780 	 * If array is degraded, better not do chunk aligned read because
5781 	 * later we might have to read it again in order to reconstruct
5782 	 * data on failed drives.
5783 	 */
5784 	if (rw == READ && mddev->degraded == 0 &&
5785 	    mddev->reshape_position == MaxSector) {
5786 		bi = chunk_aligned_read(mddev, bi);
5787 		if (!bi)
5788 			return true;
5789 	}
5790 
5791 	if (unlikely(bio_op(bi) == REQ_OP_DISCARD)) {
5792 		make_discard_request(mddev, bi);
5793 		md_write_end(mddev);
5794 		return true;
5795 	}
5796 
5797 	logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5798 	last_sector = bio_end_sector(bi);
5799 	bi->bi_next = NULL;
5800 
5801 	prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5802 	for (; logical_sector < last_sector; logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5803 		int previous;
5804 		int seq;
5805 
5806 		do_prepare = false;
5807 	retry:
5808 		seq = read_seqcount_begin(&conf->gen_lock);
5809 		previous = 0;
5810 		if (do_prepare)
5811 			prepare_to_wait(&conf->wait_for_overlap, &w,
5812 				TASK_UNINTERRUPTIBLE);
5813 		if (unlikely(conf->reshape_progress != MaxSector)) {
5814 			/* spinlock is needed as reshape_progress may be
5815 			 * 64bit on a 32bit platform, and so it might be
5816 			 * possible to see a half-updated value
5817 			 * Of course reshape_progress could change after
5818 			 * the lock is dropped, so once we get a reference
5819 			 * to the stripe that we think it is, we will have
5820 			 * to check again.
5821 			 */
5822 			spin_lock_irq(&conf->device_lock);
5823 			if (mddev->reshape_backwards
5824 			    ? logical_sector < conf->reshape_progress
5825 			    : logical_sector >= conf->reshape_progress) {
5826 				previous = 1;
5827 			} else {
5828 				if (mddev->reshape_backwards
5829 				    ? logical_sector < conf->reshape_safe
5830 				    : logical_sector >= conf->reshape_safe) {
5831 					spin_unlock_irq(&conf->device_lock);
5832 					schedule();
5833 					do_prepare = true;
5834 					goto retry;
5835 				}
5836 			}
5837 			spin_unlock_irq(&conf->device_lock);
5838 		}
5839 
5840 		new_sector = raid5_compute_sector(conf, logical_sector,
5841 						  previous,
5842 						  &dd_idx, NULL);
5843 		pr_debug("raid456: raid5_make_request, sector %llu logical %llu\n",
5844 			(unsigned long long)new_sector,
5845 			(unsigned long long)logical_sector);
5846 
5847 		sh = raid5_get_active_stripe(conf, new_sector, previous,
5848 				       (bi->bi_opf & REQ_RAHEAD), 0);
5849 		if (sh) {
5850 			if (unlikely(previous)) {
5851 				/* expansion might have moved on while waiting for a
5852 				 * stripe, so we must do the range check again.
5853 				 * Expansion could still move past after this
5854 				 * test, but as we are holding a reference to
5855 				 * 'sh', we know that if that happens,
5856 				 *  STRIPE_EXPANDING will get set and the expansion
5857 				 * won't proceed until we finish with the stripe.
5858 				 */
5859 				int must_retry = 0;
5860 				spin_lock_irq(&conf->device_lock);
5861 				if (mddev->reshape_backwards
5862 				    ? logical_sector >= conf->reshape_progress
5863 				    : logical_sector < conf->reshape_progress)
5864 					/* mismatch, need to try again */
5865 					must_retry = 1;
5866 				spin_unlock_irq(&conf->device_lock);
5867 				if (must_retry) {
5868 					raid5_release_stripe(sh);
5869 					schedule();
5870 					do_prepare = true;
5871 					goto retry;
5872 				}
5873 			}
5874 			if (read_seqcount_retry(&conf->gen_lock, seq)) {
5875 				/* Might have got the wrong stripe_head
5876 				 * by accident
5877 				 */
5878 				raid5_release_stripe(sh);
5879 				goto retry;
5880 			}
5881 
5882 			if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5883 			    !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5884 				/* Stripe is busy expanding or
5885 				 * add failed due to overlap.  Flush everything
5886 				 * and wait a while
5887 				 */
5888 				md_wakeup_thread(mddev->thread);
5889 				raid5_release_stripe(sh);
5890 				schedule();
5891 				do_prepare = true;
5892 				goto retry;
5893 			}
5894 			if (do_flush) {
5895 				set_bit(STRIPE_R5C_PREFLUSH, &sh->state);
5896 				/* we only need flush for one stripe */
5897 				do_flush = false;
5898 			}
5899 
5900 			set_bit(STRIPE_HANDLE, &sh->state);
5901 			clear_bit(STRIPE_DELAYED, &sh->state);
5902 			if ((!sh->batch_head || sh == sh->batch_head) &&
5903 			    (bi->bi_opf & REQ_SYNC) &&
5904 			    !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5905 				atomic_inc(&conf->preread_active_stripes);
5906 			release_stripe_plug(mddev, sh);
5907 		} else {
5908 			/* cannot get stripe for read-ahead, just give-up */
5909 			bi->bi_status = BLK_STS_IOERR;
5910 			break;
5911 		}
5912 	}
5913 	finish_wait(&conf->wait_for_overlap, &w);
5914 
5915 	if (rw == WRITE)
5916 		md_write_end(mddev);
5917 	bio_endio(bi);
5918 	return true;
5919 }
5920 
5921 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5922 
5923 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5924 {
5925 	/* reshaping is quite different to recovery/resync so it is
5926 	 * handled quite separately ... here.
5927 	 *
5928 	 * On each call to sync_request, we gather one chunk worth of
5929 	 * destination stripes and flag them as expanding.
5930 	 * Then we find all the source stripes and request reads.
5931 	 * As the reads complete, handle_stripe will copy the data
5932 	 * into the destination stripe and release that stripe.
5933 	 */
5934 	struct r5conf *conf = mddev->private;
5935 	struct stripe_head *sh;
5936 	struct md_rdev *rdev;
5937 	sector_t first_sector, last_sector;
5938 	int raid_disks = conf->previous_raid_disks;
5939 	int data_disks = raid_disks - conf->max_degraded;
5940 	int new_data_disks = conf->raid_disks - conf->max_degraded;
5941 	int i;
5942 	int dd_idx;
5943 	sector_t writepos, readpos, safepos;
5944 	sector_t stripe_addr;
5945 	int reshape_sectors;
5946 	struct list_head stripes;
5947 	sector_t retn;
5948 
5949 	if (sector_nr == 0) {
5950 		/* If restarting in the middle, skip the initial sectors */
5951 		if (mddev->reshape_backwards &&
5952 		    conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5953 			sector_nr = raid5_size(mddev, 0, 0)
5954 				- conf->reshape_progress;
5955 		} else if (mddev->reshape_backwards &&
5956 			   conf->reshape_progress == MaxSector) {
5957 			/* shouldn't happen, but just in case, finish up.*/
5958 			sector_nr = MaxSector;
5959 		} else if (!mddev->reshape_backwards &&
5960 			   conf->reshape_progress > 0)
5961 			sector_nr = conf->reshape_progress;
5962 		sector_div(sector_nr, new_data_disks);
5963 		if (sector_nr) {
5964 			mddev->curr_resync_completed = sector_nr;
5965 			sysfs_notify_dirent_safe(mddev->sysfs_completed);
5966 			*skipped = 1;
5967 			retn = sector_nr;
5968 			goto finish;
5969 		}
5970 	}
5971 
5972 	/* We need to process a full chunk at a time.
5973 	 * If old and new chunk sizes differ, we need to process the
5974 	 * largest of these
5975 	 */
5976 
5977 	reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5978 
5979 	/* We update the metadata at least every 10 seconds, or when
5980 	 * the data about to be copied would over-write the source of
5981 	 * the data at the front of the range.  i.e. one new_stripe
5982 	 * along from reshape_progress new_maps to after where
5983 	 * reshape_safe old_maps to
5984 	 */
5985 	writepos = conf->reshape_progress;
5986 	sector_div(writepos, new_data_disks);
5987 	readpos = conf->reshape_progress;
5988 	sector_div(readpos, data_disks);
5989 	safepos = conf->reshape_safe;
5990 	sector_div(safepos, data_disks);
5991 	if (mddev->reshape_backwards) {
5992 		BUG_ON(writepos < reshape_sectors);
5993 		writepos -= reshape_sectors;
5994 		readpos += reshape_sectors;
5995 		safepos += reshape_sectors;
5996 	} else {
5997 		writepos += reshape_sectors;
5998 		/* readpos and safepos are worst-case calculations.
5999 		 * A negative number is overly pessimistic, and causes
6000 		 * obvious problems for unsigned storage.  So clip to 0.
6001 		 */
6002 		readpos -= min_t(sector_t, reshape_sectors, readpos);
6003 		safepos -= min_t(sector_t, reshape_sectors, safepos);
6004 	}
6005 
6006 	/* Having calculated the 'writepos' possibly use it
6007 	 * to set 'stripe_addr' which is where we will write to.
6008 	 */
6009 	if (mddev->reshape_backwards) {
6010 		BUG_ON(conf->reshape_progress == 0);
6011 		stripe_addr = writepos;
6012 		BUG_ON((mddev->dev_sectors &
6013 			~((sector_t)reshape_sectors - 1))
6014 		       - reshape_sectors - stripe_addr
6015 		       != sector_nr);
6016 	} else {
6017 		BUG_ON(writepos != sector_nr + reshape_sectors);
6018 		stripe_addr = sector_nr;
6019 	}
6020 
6021 	/* 'writepos' is the most advanced device address we might write.
6022 	 * 'readpos' is the least advanced device address we might read.
6023 	 * 'safepos' is the least address recorded in the metadata as having
6024 	 *     been reshaped.
6025 	 * If there is a min_offset_diff, these are adjusted either by
6026 	 * increasing the safepos/readpos if diff is negative, or
6027 	 * increasing writepos if diff is positive.
6028 	 * If 'readpos' is then behind 'writepos', there is no way that we can
6029 	 * ensure safety in the face of a crash - that must be done by userspace
6030 	 * making a backup of the data.  So in that case there is no particular
6031 	 * rush to update metadata.
6032 	 * Otherwise if 'safepos' is behind 'writepos', then we really need to
6033 	 * update the metadata to advance 'safepos' to match 'readpos' so that
6034 	 * we can be safe in the event of a crash.
6035 	 * So we insist on updating metadata if safepos is behind writepos and
6036 	 * readpos is beyond writepos.
6037 	 * In any case, update the metadata every 10 seconds.
6038 	 * Maybe that number should be configurable, but I'm not sure it is
6039 	 * worth it.... maybe it could be a multiple of safemode_delay???
6040 	 */
6041 	if (conf->min_offset_diff < 0) {
6042 		safepos += -conf->min_offset_diff;
6043 		readpos += -conf->min_offset_diff;
6044 	} else
6045 		writepos += conf->min_offset_diff;
6046 
6047 	if ((mddev->reshape_backwards
6048 	     ? (safepos > writepos && readpos < writepos)
6049 	     : (safepos < writepos && readpos > writepos)) ||
6050 	    time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
6051 		/* Cannot proceed until we've updated the superblock... */
6052 		wait_event(conf->wait_for_overlap,
6053 			   atomic_read(&conf->reshape_stripes)==0
6054 			   || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6055 		if (atomic_read(&conf->reshape_stripes) != 0)
6056 			return 0;
6057 		mddev->reshape_position = conf->reshape_progress;
6058 		mddev->curr_resync_completed = sector_nr;
6059 		if (!mddev->reshape_backwards)
6060 			/* Can update recovery_offset */
6061 			rdev_for_each(rdev, mddev)
6062 				if (rdev->raid_disk >= 0 &&
6063 				    !test_bit(Journal, &rdev->flags) &&
6064 				    !test_bit(In_sync, &rdev->flags) &&
6065 				    rdev->recovery_offset < sector_nr)
6066 					rdev->recovery_offset = sector_nr;
6067 
6068 		conf->reshape_checkpoint = jiffies;
6069 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6070 		md_wakeup_thread(mddev->thread);
6071 		wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
6072 			   test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6073 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6074 			return 0;
6075 		spin_lock_irq(&conf->device_lock);
6076 		conf->reshape_safe = mddev->reshape_position;
6077 		spin_unlock_irq(&conf->device_lock);
6078 		wake_up(&conf->wait_for_overlap);
6079 		sysfs_notify_dirent_safe(mddev->sysfs_completed);
6080 	}
6081 
6082 	INIT_LIST_HEAD(&stripes);
6083 	for (i = 0; i < reshape_sectors; i += RAID5_STRIPE_SECTORS(conf)) {
6084 		int j;
6085 		int skipped_disk = 0;
6086 		sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
6087 		set_bit(STRIPE_EXPANDING, &sh->state);
6088 		atomic_inc(&conf->reshape_stripes);
6089 		/* If any of this stripe is beyond the end of the old
6090 		 * array, then we need to zero those blocks
6091 		 */
6092 		for (j=sh->disks; j--;) {
6093 			sector_t s;
6094 			if (j == sh->pd_idx)
6095 				continue;
6096 			if (conf->level == 6 &&
6097 			    j == sh->qd_idx)
6098 				continue;
6099 			s = raid5_compute_blocknr(sh, j, 0);
6100 			if (s < raid5_size(mddev, 0, 0)) {
6101 				skipped_disk = 1;
6102 				continue;
6103 			}
6104 			memset(page_address(sh->dev[j].page), 0, RAID5_STRIPE_SIZE(conf));
6105 			set_bit(R5_Expanded, &sh->dev[j].flags);
6106 			set_bit(R5_UPTODATE, &sh->dev[j].flags);
6107 		}
6108 		if (!skipped_disk) {
6109 			set_bit(STRIPE_EXPAND_READY, &sh->state);
6110 			set_bit(STRIPE_HANDLE, &sh->state);
6111 		}
6112 		list_add(&sh->lru, &stripes);
6113 	}
6114 	spin_lock_irq(&conf->device_lock);
6115 	if (mddev->reshape_backwards)
6116 		conf->reshape_progress -= reshape_sectors * new_data_disks;
6117 	else
6118 		conf->reshape_progress += reshape_sectors * new_data_disks;
6119 	spin_unlock_irq(&conf->device_lock);
6120 	/* Ok, those stripe are ready. We can start scheduling
6121 	 * reads on the source stripes.
6122 	 * The source stripes are determined by mapping the first and last
6123 	 * block on the destination stripes.
6124 	 */
6125 	first_sector =
6126 		raid5_compute_sector(conf, stripe_addr*(new_data_disks),
6127 				     1, &dd_idx, NULL);
6128 	last_sector =
6129 		raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
6130 					    * new_data_disks - 1),
6131 				     1, &dd_idx, NULL);
6132 	if (last_sector >= mddev->dev_sectors)
6133 		last_sector = mddev->dev_sectors - 1;
6134 	while (first_sector <= last_sector) {
6135 		sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
6136 		set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
6137 		set_bit(STRIPE_HANDLE, &sh->state);
6138 		raid5_release_stripe(sh);
6139 		first_sector += RAID5_STRIPE_SECTORS(conf);
6140 	}
6141 	/* Now that the sources are clearly marked, we can release
6142 	 * the destination stripes
6143 	 */
6144 	while (!list_empty(&stripes)) {
6145 		sh = list_entry(stripes.next, struct stripe_head, lru);
6146 		list_del_init(&sh->lru);
6147 		raid5_release_stripe(sh);
6148 	}
6149 	/* If this takes us to the resync_max point where we have to pause,
6150 	 * then we need to write out the superblock.
6151 	 */
6152 	sector_nr += reshape_sectors;
6153 	retn = reshape_sectors;
6154 finish:
6155 	if (mddev->curr_resync_completed > mddev->resync_max ||
6156 	    (sector_nr - mddev->curr_resync_completed) * 2
6157 	    >= mddev->resync_max - mddev->curr_resync_completed) {
6158 		/* Cannot proceed until we've updated the superblock... */
6159 		wait_event(conf->wait_for_overlap,
6160 			   atomic_read(&conf->reshape_stripes) == 0
6161 			   || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6162 		if (atomic_read(&conf->reshape_stripes) != 0)
6163 			goto ret;
6164 		mddev->reshape_position = conf->reshape_progress;
6165 		mddev->curr_resync_completed = sector_nr;
6166 		if (!mddev->reshape_backwards)
6167 			/* Can update recovery_offset */
6168 			rdev_for_each(rdev, mddev)
6169 				if (rdev->raid_disk >= 0 &&
6170 				    !test_bit(Journal, &rdev->flags) &&
6171 				    !test_bit(In_sync, &rdev->flags) &&
6172 				    rdev->recovery_offset < sector_nr)
6173 					rdev->recovery_offset = sector_nr;
6174 		conf->reshape_checkpoint = jiffies;
6175 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6176 		md_wakeup_thread(mddev->thread);
6177 		wait_event(mddev->sb_wait,
6178 			   !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)
6179 			   || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6180 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6181 			goto ret;
6182 		spin_lock_irq(&conf->device_lock);
6183 		conf->reshape_safe = mddev->reshape_position;
6184 		spin_unlock_irq(&conf->device_lock);
6185 		wake_up(&conf->wait_for_overlap);
6186 		sysfs_notify_dirent_safe(mddev->sysfs_completed);
6187 	}
6188 ret:
6189 	return retn;
6190 }
6191 
6192 static inline sector_t raid5_sync_request(struct mddev *mddev, sector_t sector_nr,
6193 					  int *skipped)
6194 {
6195 	struct r5conf *conf = mddev->private;
6196 	struct stripe_head *sh;
6197 	sector_t max_sector = mddev->dev_sectors;
6198 	sector_t sync_blocks;
6199 	int still_degraded = 0;
6200 	int i;
6201 
6202 	if (sector_nr >= max_sector) {
6203 		/* just being told to finish up .. nothing much to do */
6204 
6205 		if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
6206 			end_reshape(conf);
6207 			return 0;
6208 		}
6209 
6210 		if (mddev->curr_resync < max_sector) /* aborted */
6211 			md_bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
6212 					   &sync_blocks, 1);
6213 		else /* completed sync */
6214 			conf->fullsync = 0;
6215 		md_bitmap_close_sync(mddev->bitmap);
6216 
6217 		return 0;
6218 	}
6219 
6220 	/* Allow raid5_quiesce to complete */
6221 	wait_event(conf->wait_for_overlap, conf->quiesce != 2);
6222 
6223 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6224 		return reshape_request(mddev, sector_nr, skipped);
6225 
6226 	/* No need to check resync_max as we never do more than one
6227 	 * stripe, and as resync_max will always be on a chunk boundary,
6228 	 * if the check in md_do_sync didn't fire, there is no chance
6229 	 * of overstepping resync_max here
6230 	 */
6231 
6232 	/* if there is too many failed drives and we are trying
6233 	 * to resync, then assert that we are finished, because there is
6234 	 * nothing we can do.
6235 	 */
6236 	if (mddev->degraded >= conf->max_degraded &&
6237 	    test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6238 		sector_t rv = mddev->dev_sectors - sector_nr;
6239 		*skipped = 1;
6240 		return rv;
6241 	}
6242 	if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
6243 	    !conf->fullsync &&
6244 	    !md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
6245 	    sync_blocks >= RAID5_STRIPE_SECTORS(conf)) {
6246 		/* we can skip this block, and probably more */
6247 		do_div(sync_blocks, RAID5_STRIPE_SECTORS(conf));
6248 		*skipped = 1;
6249 		/* keep things rounded to whole stripes */
6250 		return sync_blocks * RAID5_STRIPE_SECTORS(conf);
6251 	}
6252 
6253 	md_bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
6254 
6255 	sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
6256 	if (sh == NULL) {
6257 		sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
6258 		/* make sure we don't swamp the stripe cache if someone else
6259 		 * is trying to get access
6260 		 */
6261 		schedule_timeout_uninterruptible(1);
6262 	}
6263 	/* Need to check if array will still be degraded after recovery/resync
6264 	 * Note in case of > 1 drive failures it's possible we're rebuilding
6265 	 * one drive while leaving another faulty drive in array.
6266 	 */
6267 	rcu_read_lock();
6268 	for (i = 0; i < conf->raid_disks; i++) {
6269 		struct md_rdev *rdev = READ_ONCE(conf->disks[i].rdev);
6270 
6271 		if (rdev == NULL || test_bit(Faulty, &rdev->flags))
6272 			still_degraded = 1;
6273 	}
6274 	rcu_read_unlock();
6275 
6276 	md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
6277 
6278 	set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
6279 	set_bit(STRIPE_HANDLE, &sh->state);
6280 
6281 	raid5_release_stripe(sh);
6282 
6283 	return RAID5_STRIPE_SECTORS(conf);
6284 }
6285 
6286 static int  retry_aligned_read(struct r5conf *conf, struct bio *raid_bio,
6287 			       unsigned int offset)
6288 {
6289 	/* We may not be able to submit a whole bio at once as there
6290 	 * may not be enough stripe_heads available.
6291 	 * We cannot pre-allocate enough stripe_heads as we may need
6292 	 * more than exist in the cache (if we allow ever large chunks).
6293 	 * So we do one stripe head at a time and record in
6294 	 * ->bi_hw_segments how many have been done.
6295 	 *
6296 	 * We *know* that this entire raid_bio is in one chunk, so
6297 	 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
6298 	 */
6299 	struct stripe_head *sh;
6300 	int dd_idx;
6301 	sector_t sector, logical_sector, last_sector;
6302 	int scnt = 0;
6303 	int handled = 0;
6304 
6305 	logical_sector = raid_bio->bi_iter.bi_sector &
6306 		~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
6307 	sector = raid5_compute_sector(conf, logical_sector,
6308 				      0, &dd_idx, NULL);
6309 	last_sector = bio_end_sector(raid_bio);
6310 
6311 	for (; logical_sector < last_sector;
6312 	     logical_sector += RAID5_STRIPE_SECTORS(conf),
6313 		     sector += RAID5_STRIPE_SECTORS(conf),
6314 		     scnt++) {
6315 
6316 		if (scnt < offset)
6317 			/* already done this stripe */
6318 			continue;
6319 
6320 		sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
6321 
6322 		if (!sh) {
6323 			/* failed to get a stripe - must wait */
6324 			conf->retry_read_aligned = raid_bio;
6325 			conf->retry_read_offset = scnt;
6326 			return handled;
6327 		}
6328 
6329 		if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
6330 			raid5_release_stripe(sh);
6331 			conf->retry_read_aligned = raid_bio;
6332 			conf->retry_read_offset = scnt;
6333 			return handled;
6334 		}
6335 
6336 		set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
6337 		handle_stripe(sh);
6338 		raid5_release_stripe(sh);
6339 		handled++;
6340 	}
6341 
6342 	bio_endio(raid_bio);
6343 
6344 	if (atomic_dec_and_test(&conf->active_aligned_reads))
6345 		wake_up(&conf->wait_for_quiescent);
6346 	return handled;
6347 }
6348 
6349 static int handle_active_stripes(struct r5conf *conf, int group,
6350 				 struct r5worker *worker,
6351 				 struct list_head *temp_inactive_list)
6352 		__releases(&conf->device_lock)
6353 		__acquires(&conf->device_lock)
6354 {
6355 	struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
6356 	int i, batch_size = 0, hash;
6357 	bool release_inactive = false;
6358 
6359 	while (batch_size < MAX_STRIPE_BATCH &&
6360 			(sh = __get_priority_stripe(conf, group)) != NULL)
6361 		batch[batch_size++] = sh;
6362 
6363 	if (batch_size == 0) {
6364 		for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6365 			if (!list_empty(temp_inactive_list + i))
6366 				break;
6367 		if (i == NR_STRIPE_HASH_LOCKS) {
6368 			spin_unlock_irq(&conf->device_lock);
6369 			log_flush_stripe_to_raid(conf);
6370 			spin_lock_irq(&conf->device_lock);
6371 			return batch_size;
6372 		}
6373 		release_inactive = true;
6374 	}
6375 	spin_unlock_irq(&conf->device_lock);
6376 
6377 	release_inactive_stripe_list(conf, temp_inactive_list,
6378 				     NR_STRIPE_HASH_LOCKS);
6379 
6380 	r5l_flush_stripe_to_raid(conf->log);
6381 	if (release_inactive) {
6382 		spin_lock_irq(&conf->device_lock);
6383 		return 0;
6384 	}
6385 
6386 	for (i = 0; i < batch_size; i++)
6387 		handle_stripe(batch[i]);
6388 	log_write_stripe_run(conf);
6389 
6390 	cond_resched();
6391 
6392 	spin_lock_irq(&conf->device_lock);
6393 	for (i = 0; i < batch_size; i++) {
6394 		hash = batch[i]->hash_lock_index;
6395 		__release_stripe(conf, batch[i], &temp_inactive_list[hash]);
6396 	}
6397 	return batch_size;
6398 }
6399 
6400 static void raid5_do_work(struct work_struct *work)
6401 {
6402 	struct r5worker *worker = container_of(work, struct r5worker, work);
6403 	struct r5worker_group *group = worker->group;
6404 	struct r5conf *conf = group->conf;
6405 	struct mddev *mddev = conf->mddev;
6406 	int group_id = group - conf->worker_groups;
6407 	int handled;
6408 	struct blk_plug plug;
6409 
6410 	pr_debug("+++ raid5worker active\n");
6411 
6412 	blk_start_plug(&plug);
6413 	handled = 0;
6414 	spin_lock_irq(&conf->device_lock);
6415 	while (1) {
6416 		int batch_size, released;
6417 
6418 		released = release_stripe_list(conf, worker->temp_inactive_list);
6419 
6420 		batch_size = handle_active_stripes(conf, group_id, worker,
6421 						   worker->temp_inactive_list);
6422 		worker->working = false;
6423 		if (!batch_size && !released)
6424 			break;
6425 		handled += batch_size;
6426 		wait_event_lock_irq(mddev->sb_wait,
6427 			!test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6428 			conf->device_lock);
6429 	}
6430 	pr_debug("%d stripes handled\n", handled);
6431 
6432 	spin_unlock_irq(&conf->device_lock);
6433 
6434 	flush_deferred_bios(conf);
6435 
6436 	r5l_flush_stripe_to_raid(conf->log);
6437 
6438 	async_tx_issue_pending_all();
6439 	blk_finish_plug(&plug);
6440 
6441 	pr_debug("--- raid5worker inactive\n");
6442 }
6443 
6444 /*
6445  * This is our raid5 kernel thread.
6446  *
6447  * We scan the hash table for stripes which can be handled now.
6448  * During the scan, completed stripes are saved for us by the interrupt
6449  * handler, so that they will not have to wait for our next wakeup.
6450  */
6451 static void raid5d(struct md_thread *thread)
6452 {
6453 	struct mddev *mddev = thread->mddev;
6454 	struct r5conf *conf = mddev->private;
6455 	int handled;
6456 	struct blk_plug plug;
6457 
6458 	pr_debug("+++ raid5d active\n");
6459 
6460 	md_check_recovery(mddev);
6461 
6462 	blk_start_plug(&plug);
6463 	handled = 0;
6464 	spin_lock_irq(&conf->device_lock);
6465 	while (1) {
6466 		struct bio *bio;
6467 		int batch_size, released;
6468 		unsigned int offset;
6469 
6470 		released = release_stripe_list(conf, conf->temp_inactive_list);
6471 		if (released)
6472 			clear_bit(R5_DID_ALLOC, &conf->cache_state);
6473 
6474 		if (
6475 		    !list_empty(&conf->bitmap_list)) {
6476 			/* Now is a good time to flush some bitmap updates */
6477 			conf->seq_flush++;
6478 			spin_unlock_irq(&conf->device_lock);
6479 			md_bitmap_unplug(mddev->bitmap);
6480 			spin_lock_irq(&conf->device_lock);
6481 			conf->seq_write = conf->seq_flush;
6482 			activate_bit_delay(conf, conf->temp_inactive_list);
6483 		}
6484 		raid5_activate_delayed(conf);
6485 
6486 		while ((bio = remove_bio_from_retry(conf, &offset))) {
6487 			int ok;
6488 			spin_unlock_irq(&conf->device_lock);
6489 			ok = retry_aligned_read(conf, bio, offset);
6490 			spin_lock_irq(&conf->device_lock);
6491 			if (!ok)
6492 				break;
6493 			handled++;
6494 		}
6495 
6496 		batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
6497 						   conf->temp_inactive_list);
6498 		if (!batch_size && !released)
6499 			break;
6500 		handled += batch_size;
6501 
6502 		if (mddev->sb_flags & ~(1 << MD_SB_CHANGE_PENDING)) {
6503 			spin_unlock_irq(&conf->device_lock);
6504 			md_check_recovery(mddev);
6505 			spin_lock_irq(&conf->device_lock);
6506 		}
6507 	}
6508 	pr_debug("%d stripes handled\n", handled);
6509 
6510 	spin_unlock_irq(&conf->device_lock);
6511 	if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
6512 	    mutex_trylock(&conf->cache_size_mutex)) {
6513 		grow_one_stripe(conf, __GFP_NOWARN);
6514 		/* Set flag even if allocation failed.  This helps
6515 		 * slow down allocation requests when mem is short
6516 		 */
6517 		set_bit(R5_DID_ALLOC, &conf->cache_state);
6518 		mutex_unlock(&conf->cache_size_mutex);
6519 	}
6520 
6521 	flush_deferred_bios(conf);
6522 
6523 	r5l_flush_stripe_to_raid(conf->log);
6524 
6525 	async_tx_issue_pending_all();
6526 	blk_finish_plug(&plug);
6527 
6528 	pr_debug("--- raid5d inactive\n");
6529 }
6530 
6531 static ssize_t
6532 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
6533 {
6534 	struct r5conf *conf;
6535 	int ret = 0;
6536 	spin_lock(&mddev->lock);
6537 	conf = mddev->private;
6538 	if (conf)
6539 		ret = sprintf(page, "%d\n", conf->min_nr_stripes);
6540 	spin_unlock(&mddev->lock);
6541 	return ret;
6542 }
6543 
6544 int
6545 raid5_set_cache_size(struct mddev *mddev, int size)
6546 {
6547 	int result = 0;
6548 	struct r5conf *conf = mddev->private;
6549 
6550 	if (size <= 16 || size > 32768)
6551 		return -EINVAL;
6552 
6553 	conf->min_nr_stripes = size;
6554 	mutex_lock(&conf->cache_size_mutex);
6555 	while (size < conf->max_nr_stripes &&
6556 	       drop_one_stripe(conf))
6557 		;
6558 	mutex_unlock(&conf->cache_size_mutex);
6559 
6560 	md_allow_write(mddev);
6561 
6562 	mutex_lock(&conf->cache_size_mutex);
6563 	while (size > conf->max_nr_stripes)
6564 		if (!grow_one_stripe(conf, GFP_KERNEL)) {
6565 			conf->min_nr_stripes = conf->max_nr_stripes;
6566 			result = -ENOMEM;
6567 			break;
6568 		}
6569 	mutex_unlock(&conf->cache_size_mutex);
6570 
6571 	return result;
6572 }
6573 EXPORT_SYMBOL(raid5_set_cache_size);
6574 
6575 static ssize_t
6576 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6577 {
6578 	struct r5conf *conf;
6579 	unsigned long new;
6580 	int err;
6581 
6582 	if (len >= PAGE_SIZE)
6583 		return -EINVAL;
6584 	if (kstrtoul(page, 10, &new))
6585 		return -EINVAL;
6586 	err = mddev_lock(mddev);
6587 	if (err)
6588 		return err;
6589 	conf = mddev->private;
6590 	if (!conf)
6591 		err = -ENODEV;
6592 	else
6593 		err = raid5_set_cache_size(mddev, new);
6594 	mddev_unlock(mddev);
6595 
6596 	return err ?: len;
6597 }
6598 
6599 static struct md_sysfs_entry
6600 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6601 				raid5_show_stripe_cache_size,
6602 				raid5_store_stripe_cache_size);
6603 
6604 static ssize_t
6605 raid5_show_rmw_level(struct mddev  *mddev, char *page)
6606 {
6607 	struct r5conf *conf = mddev->private;
6608 	if (conf)
6609 		return sprintf(page, "%d\n", conf->rmw_level);
6610 	else
6611 		return 0;
6612 }
6613 
6614 static ssize_t
6615 raid5_store_rmw_level(struct mddev  *mddev, const char *page, size_t len)
6616 {
6617 	struct r5conf *conf = mddev->private;
6618 	unsigned long new;
6619 
6620 	if (!conf)
6621 		return -ENODEV;
6622 
6623 	if (len >= PAGE_SIZE)
6624 		return -EINVAL;
6625 
6626 	if (kstrtoul(page, 10, &new))
6627 		return -EINVAL;
6628 
6629 	if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6630 		return -EINVAL;
6631 
6632 	if (new != PARITY_DISABLE_RMW &&
6633 	    new != PARITY_ENABLE_RMW &&
6634 	    new != PARITY_PREFER_RMW)
6635 		return -EINVAL;
6636 
6637 	conf->rmw_level = new;
6638 	return len;
6639 }
6640 
6641 static struct md_sysfs_entry
6642 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6643 			 raid5_show_rmw_level,
6644 			 raid5_store_rmw_level);
6645 
6646 static ssize_t
6647 raid5_show_stripe_size(struct mddev  *mddev, char *page)
6648 {
6649 	struct r5conf *conf;
6650 	int ret = 0;
6651 
6652 	spin_lock(&mddev->lock);
6653 	conf = mddev->private;
6654 	if (conf)
6655 		ret = sprintf(page, "%lu\n", RAID5_STRIPE_SIZE(conf));
6656 	spin_unlock(&mddev->lock);
6657 	return ret;
6658 }
6659 
6660 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
6661 static ssize_t
6662 raid5_store_stripe_size(struct mddev  *mddev, const char *page, size_t len)
6663 {
6664 	struct r5conf *conf;
6665 	unsigned long new;
6666 	int err;
6667 	int size;
6668 
6669 	if (len >= PAGE_SIZE)
6670 		return -EINVAL;
6671 	if (kstrtoul(page, 10, &new))
6672 		return -EINVAL;
6673 
6674 	/*
6675 	 * The value should not be bigger than PAGE_SIZE. It requires to
6676 	 * be multiple of DEFAULT_STRIPE_SIZE and the value should be power
6677 	 * of two.
6678 	 */
6679 	if (new % DEFAULT_STRIPE_SIZE != 0 ||
6680 			new > PAGE_SIZE || new == 0 ||
6681 			new != roundup_pow_of_two(new))
6682 		return -EINVAL;
6683 
6684 	err = mddev_lock(mddev);
6685 	if (err)
6686 		return err;
6687 
6688 	conf = mddev->private;
6689 	if (!conf) {
6690 		err = -ENODEV;
6691 		goto out_unlock;
6692 	}
6693 
6694 	if (new == conf->stripe_size)
6695 		goto out_unlock;
6696 
6697 	pr_debug("md/raid: change stripe_size from %lu to %lu\n",
6698 			conf->stripe_size, new);
6699 
6700 	if (mddev->sync_thread ||
6701 		test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6702 		mddev->reshape_position != MaxSector ||
6703 		mddev->sysfs_active) {
6704 		err = -EBUSY;
6705 		goto out_unlock;
6706 	}
6707 
6708 	mddev_suspend(mddev);
6709 	mutex_lock(&conf->cache_size_mutex);
6710 	size = conf->max_nr_stripes;
6711 
6712 	shrink_stripes(conf);
6713 
6714 	conf->stripe_size = new;
6715 	conf->stripe_shift = ilog2(new) - 9;
6716 	conf->stripe_sectors = new >> 9;
6717 	if (grow_stripes(conf, size)) {
6718 		pr_warn("md/raid:%s: couldn't allocate buffers\n",
6719 				mdname(mddev));
6720 		err = -ENOMEM;
6721 	}
6722 	mutex_unlock(&conf->cache_size_mutex);
6723 	mddev_resume(mddev);
6724 
6725 out_unlock:
6726 	mddev_unlock(mddev);
6727 	return err ?: len;
6728 }
6729 
6730 static struct md_sysfs_entry
6731 raid5_stripe_size = __ATTR(stripe_size, 0644,
6732 			 raid5_show_stripe_size,
6733 			 raid5_store_stripe_size);
6734 #else
6735 static struct md_sysfs_entry
6736 raid5_stripe_size = __ATTR(stripe_size, 0444,
6737 			 raid5_show_stripe_size,
6738 			 NULL);
6739 #endif
6740 
6741 static ssize_t
6742 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6743 {
6744 	struct r5conf *conf;
6745 	int ret = 0;
6746 	spin_lock(&mddev->lock);
6747 	conf = mddev->private;
6748 	if (conf)
6749 		ret = sprintf(page, "%d\n", conf->bypass_threshold);
6750 	spin_unlock(&mddev->lock);
6751 	return ret;
6752 }
6753 
6754 static ssize_t
6755 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6756 {
6757 	struct r5conf *conf;
6758 	unsigned long new;
6759 	int err;
6760 
6761 	if (len >= PAGE_SIZE)
6762 		return -EINVAL;
6763 	if (kstrtoul(page, 10, &new))
6764 		return -EINVAL;
6765 
6766 	err = mddev_lock(mddev);
6767 	if (err)
6768 		return err;
6769 	conf = mddev->private;
6770 	if (!conf)
6771 		err = -ENODEV;
6772 	else if (new > conf->min_nr_stripes)
6773 		err = -EINVAL;
6774 	else
6775 		conf->bypass_threshold = new;
6776 	mddev_unlock(mddev);
6777 	return err ?: len;
6778 }
6779 
6780 static struct md_sysfs_entry
6781 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6782 					S_IRUGO | S_IWUSR,
6783 					raid5_show_preread_threshold,
6784 					raid5_store_preread_threshold);
6785 
6786 static ssize_t
6787 raid5_show_skip_copy(struct mddev *mddev, char *page)
6788 {
6789 	struct r5conf *conf;
6790 	int ret = 0;
6791 	spin_lock(&mddev->lock);
6792 	conf = mddev->private;
6793 	if (conf)
6794 		ret = sprintf(page, "%d\n", conf->skip_copy);
6795 	spin_unlock(&mddev->lock);
6796 	return ret;
6797 }
6798 
6799 static ssize_t
6800 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6801 {
6802 	struct r5conf *conf;
6803 	unsigned long new;
6804 	int err;
6805 
6806 	if (len >= PAGE_SIZE)
6807 		return -EINVAL;
6808 	if (kstrtoul(page, 10, &new))
6809 		return -EINVAL;
6810 	new = !!new;
6811 
6812 	err = mddev_lock(mddev);
6813 	if (err)
6814 		return err;
6815 	conf = mddev->private;
6816 	if (!conf)
6817 		err = -ENODEV;
6818 	else if (new != conf->skip_copy) {
6819 		struct request_queue *q = mddev->queue;
6820 
6821 		mddev_suspend(mddev);
6822 		conf->skip_copy = new;
6823 		if (new)
6824 			blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, q);
6825 		else
6826 			blk_queue_flag_clear(QUEUE_FLAG_STABLE_WRITES, q);
6827 		mddev_resume(mddev);
6828 	}
6829 	mddev_unlock(mddev);
6830 	return err ?: len;
6831 }
6832 
6833 static struct md_sysfs_entry
6834 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6835 					raid5_show_skip_copy,
6836 					raid5_store_skip_copy);
6837 
6838 static ssize_t
6839 stripe_cache_active_show(struct mddev *mddev, char *page)
6840 {
6841 	struct r5conf *conf = mddev->private;
6842 	if (conf)
6843 		return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6844 	else
6845 		return 0;
6846 }
6847 
6848 static struct md_sysfs_entry
6849 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6850 
6851 static ssize_t
6852 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6853 {
6854 	struct r5conf *conf;
6855 	int ret = 0;
6856 	spin_lock(&mddev->lock);
6857 	conf = mddev->private;
6858 	if (conf)
6859 		ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6860 	spin_unlock(&mddev->lock);
6861 	return ret;
6862 }
6863 
6864 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6865 			       int *group_cnt,
6866 			       struct r5worker_group **worker_groups);
6867 static ssize_t
6868 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6869 {
6870 	struct r5conf *conf;
6871 	unsigned int new;
6872 	int err;
6873 	struct r5worker_group *new_groups, *old_groups;
6874 	int group_cnt;
6875 
6876 	if (len >= PAGE_SIZE)
6877 		return -EINVAL;
6878 	if (kstrtouint(page, 10, &new))
6879 		return -EINVAL;
6880 	/* 8192 should be big enough */
6881 	if (new > 8192)
6882 		return -EINVAL;
6883 
6884 	err = mddev_lock(mddev);
6885 	if (err)
6886 		return err;
6887 	conf = mddev->private;
6888 	if (!conf)
6889 		err = -ENODEV;
6890 	else if (new != conf->worker_cnt_per_group) {
6891 		mddev_suspend(mddev);
6892 
6893 		old_groups = conf->worker_groups;
6894 		if (old_groups)
6895 			flush_workqueue(raid5_wq);
6896 
6897 		err = alloc_thread_groups(conf, new, &group_cnt, &new_groups);
6898 		if (!err) {
6899 			spin_lock_irq(&conf->device_lock);
6900 			conf->group_cnt = group_cnt;
6901 			conf->worker_cnt_per_group = new;
6902 			conf->worker_groups = new_groups;
6903 			spin_unlock_irq(&conf->device_lock);
6904 
6905 			if (old_groups)
6906 				kfree(old_groups[0].workers);
6907 			kfree(old_groups);
6908 		}
6909 		mddev_resume(mddev);
6910 	}
6911 	mddev_unlock(mddev);
6912 
6913 	return err ?: len;
6914 }
6915 
6916 static struct md_sysfs_entry
6917 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6918 				raid5_show_group_thread_cnt,
6919 				raid5_store_group_thread_cnt);
6920 
6921 static struct attribute *raid5_attrs[] =  {
6922 	&raid5_stripecache_size.attr,
6923 	&raid5_stripecache_active.attr,
6924 	&raid5_preread_bypass_threshold.attr,
6925 	&raid5_group_thread_cnt.attr,
6926 	&raid5_skip_copy.attr,
6927 	&raid5_rmw_level.attr,
6928 	&raid5_stripe_size.attr,
6929 	&r5c_journal_mode.attr,
6930 	&ppl_write_hint.attr,
6931 	NULL,
6932 };
6933 static struct attribute_group raid5_attrs_group = {
6934 	.name = NULL,
6935 	.attrs = raid5_attrs,
6936 };
6937 
6938 static int alloc_thread_groups(struct r5conf *conf, int cnt, int *group_cnt,
6939 			       struct r5worker_group **worker_groups)
6940 {
6941 	int i, j, k;
6942 	ssize_t size;
6943 	struct r5worker *workers;
6944 
6945 	if (cnt == 0) {
6946 		*group_cnt = 0;
6947 		*worker_groups = NULL;
6948 		return 0;
6949 	}
6950 	*group_cnt = num_possible_nodes();
6951 	size = sizeof(struct r5worker) * cnt;
6952 	workers = kcalloc(size, *group_cnt, GFP_NOIO);
6953 	*worker_groups = kcalloc(*group_cnt, sizeof(struct r5worker_group),
6954 				 GFP_NOIO);
6955 	if (!*worker_groups || !workers) {
6956 		kfree(workers);
6957 		kfree(*worker_groups);
6958 		return -ENOMEM;
6959 	}
6960 
6961 	for (i = 0; i < *group_cnt; i++) {
6962 		struct r5worker_group *group;
6963 
6964 		group = &(*worker_groups)[i];
6965 		INIT_LIST_HEAD(&group->handle_list);
6966 		INIT_LIST_HEAD(&group->loprio_list);
6967 		group->conf = conf;
6968 		group->workers = workers + i * cnt;
6969 
6970 		for (j = 0; j < cnt; j++) {
6971 			struct r5worker *worker = group->workers + j;
6972 			worker->group = group;
6973 			INIT_WORK(&worker->work, raid5_do_work);
6974 
6975 			for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
6976 				INIT_LIST_HEAD(worker->temp_inactive_list + k);
6977 		}
6978 	}
6979 
6980 	return 0;
6981 }
6982 
6983 static void free_thread_groups(struct r5conf *conf)
6984 {
6985 	if (conf->worker_groups)
6986 		kfree(conf->worker_groups[0].workers);
6987 	kfree(conf->worker_groups);
6988 	conf->worker_groups = NULL;
6989 }
6990 
6991 static sector_t
6992 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
6993 {
6994 	struct r5conf *conf = mddev->private;
6995 
6996 	if (!sectors)
6997 		sectors = mddev->dev_sectors;
6998 	if (!raid_disks)
6999 		/* size is defined by the smallest of previous and new size */
7000 		raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
7001 
7002 	sectors &= ~((sector_t)conf->chunk_sectors - 1);
7003 	sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
7004 	return sectors * (raid_disks - conf->max_degraded);
7005 }
7006 
7007 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7008 {
7009 	safe_put_page(percpu->spare_page);
7010 	percpu->spare_page = NULL;
7011 	kvfree(percpu->scribble);
7012 	percpu->scribble = NULL;
7013 }
7014 
7015 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7016 {
7017 	if (conf->level == 6 && !percpu->spare_page) {
7018 		percpu->spare_page = alloc_page(GFP_KERNEL);
7019 		if (!percpu->spare_page)
7020 			return -ENOMEM;
7021 	}
7022 
7023 	if (scribble_alloc(percpu,
7024 			   max(conf->raid_disks,
7025 			       conf->previous_raid_disks),
7026 			   max(conf->chunk_sectors,
7027 			       conf->prev_chunk_sectors)
7028 			   / RAID5_STRIPE_SECTORS(conf))) {
7029 		free_scratch_buffer(conf, percpu);
7030 		return -ENOMEM;
7031 	}
7032 
7033 	return 0;
7034 }
7035 
7036 static int raid456_cpu_dead(unsigned int cpu, struct hlist_node *node)
7037 {
7038 	struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7039 
7040 	free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
7041 	return 0;
7042 }
7043 
7044 static void raid5_free_percpu(struct r5conf *conf)
7045 {
7046 	if (!conf->percpu)
7047 		return;
7048 
7049 	cpuhp_state_remove_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7050 	free_percpu(conf->percpu);
7051 }
7052 
7053 static void free_conf(struct r5conf *conf)
7054 {
7055 	int i;
7056 
7057 	log_exit(conf);
7058 
7059 	unregister_shrinker(&conf->shrinker);
7060 	free_thread_groups(conf);
7061 	shrink_stripes(conf);
7062 	raid5_free_percpu(conf);
7063 	for (i = 0; i < conf->pool_size; i++)
7064 		if (conf->disks[i].extra_page)
7065 			put_page(conf->disks[i].extra_page);
7066 	kfree(conf->disks);
7067 	bioset_exit(&conf->bio_split);
7068 	kfree(conf->stripe_hashtbl);
7069 	kfree(conf->pending_data);
7070 	kfree(conf);
7071 }
7072 
7073 static int raid456_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
7074 {
7075 	struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7076 	struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
7077 
7078 	if (alloc_scratch_buffer(conf, percpu)) {
7079 		pr_warn("%s: failed memory allocation for cpu%u\n",
7080 			__func__, cpu);
7081 		return -ENOMEM;
7082 	}
7083 	return 0;
7084 }
7085 
7086 static int raid5_alloc_percpu(struct r5conf *conf)
7087 {
7088 	int err = 0;
7089 
7090 	conf->percpu = alloc_percpu(struct raid5_percpu);
7091 	if (!conf->percpu)
7092 		return -ENOMEM;
7093 
7094 	err = cpuhp_state_add_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7095 	if (!err) {
7096 		conf->scribble_disks = max(conf->raid_disks,
7097 			conf->previous_raid_disks);
7098 		conf->scribble_sectors = max(conf->chunk_sectors,
7099 			conf->prev_chunk_sectors);
7100 	}
7101 	return err;
7102 }
7103 
7104 static unsigned long raid5_cache_scan(struct shrinker *shrink,
7105 				      struct shrink_control *sc)
7106 {
7107 	struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7108 	unsigned long ret = SHRINK_STOP;
7109 
7110 	if (mutex_trylock(&conf->cache_size_mutex)) {
7111 		ret= 0;
7112 		while (ret < sc->nr_to_scan &&
7113 		       conf->max_nr_stripes > conf->min_nr_stripes) {
7114 			if (drop_one_stripe(conf) == 0) {
7115 				ret = SHRINK_STOP;
7116 				break;
7117 			}
7118 			ret++;
7119 		}
7120 		mutex_unlock(&conf->cache_size_mutex);
7121 	}
7122 	return ret;
7123 }
7124 
7125 static unsigned long raid5_cache_count(struct shrinker *shrink,
7126 				       struct shrink_control *sc)
7127 {
7128 	struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7129 
7130 	if (conf->max_nr_stripes < conf->min_nr_stripes)
7131 		/* unlikely, but not impossible */
7132 		return 0;
7133 	return conf->max_nr_stripes - conf->min_nr_stripes;
7134 }
7135 
7136 static struct r5conf *setup_conf(struct mddev *mddev)
7137 {
7138 	struct r5conf *conf;
7139 	int raid_disk, memory, max_disks;
7140 	struct md_rdev *rdev;
7141 	struct disk_info *disk;
7142 	char pers_name[6];
7143 	int i;
7144 	int group_cnt;
7145 	struct r5worker_group *new_group;
7146 	int ret;
7147 
7148 	if (mddev->new_level != 5
7149 	    && mddev->new_level != 4
7150 	    && mddev->new_level != 6) {
7151 		pr_warn("md/raid:%s: raid level not set to 4/5/6 (%d)\n",
7152 			mdname(mddev), mddev->new_level);
7153 		return ERR_PTR(-EIO);
7154 	}
7155 	if ((mddev->new_level == 5
7156 	     && !algorithm_valid_raid5(mddev->new_layout)) ||
7157 	    (mddev->new_level == 6
7158 	     && !algorithm_valid_raid6(mddev->new_layout))) {
7159 		pr_warn("md/raid:%s: layout %d not supported\n",
7160 			mdname(mddev), mddev->new_layout);
7161 		return ERR_PTR(-EIO);
7162 	}
7163 	if (mddev->new_level == 6 && mddev->raid_disks < 4) {
7164 		pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n",
7165 			mdname(mddev), mddev->raid_disks);
7166 		return ERR_PTR(-EINVAL);
7167 	}
7168 
7169 	if (!mddev->new_chunk_sectors ||
7170 	    (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
7171 	    !is_power_of_2(mddev->new_chunk_sectors)) {
7172 		pr_warn("md/raid:%s: invalid chunk size %d\n",
7173 			mdname(mddev), mddev->new_chunk_sectors << 9);
7174 		return ERR_PTR(-EINVAL);
7175 	}
7176 
7177 	conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
7178 	if (conf == NULL)
7179 		goto abort;
7180 
7181 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
7182 	conf->stripe_size = DEFAULT_STRIPE_SIZE;
7183 	conf->stripe_shift = ilog2(DEFAULT_STRIPE_SIZE) - 9;
7184 	conf->stripe_sectors = DEFAULT_STRIPE_SIZE >> 9;
7185 #endif
7186 	INIT_LIST_HEAD(&conf->free_list);
7187 	INIT_LIST_HEAD(&conf->pending_list);
7188 	conf->pending_data = kcalloc(PENDING_IO_MAX,
7189 				     sizeof(struct r5pending_data),
7190 				     GFP_KERNEL);
7191 	if (!conf->pending_data)
7192 		goto abort;
7193 	for (i = 0; i < PENDING_IO_MAX; i++)
7194 		list_add(&conf->pending_data[i].sibling, &conf->free_list);
7195 	/* Don't enable multi-threading by default*/
7196 	if (!alloc_thread_groups(conf, 0, &group_cnt, &new_group)) {
7197 		conf->group_cnt = group_cnt;
7198 		conf->worker_cnt_per_group = 0;
7199 		conf->worker_groups = new_group;
7200 	} else
7201 		goto abort;
7202 	spin_lock_init(&conf->device_lock);
7203 	seqcount_spinlock_init(&conf->gen_lock, &conf->device_lock);
7204 	mutex_init(&conf->cache_size_mutex);
7205 	init_waitqueue_head(&conf->wait_for_quiescent);
7206 	init_waitqueue_head(&conf->wait_for_stripe);
7207 	init_waitqueue_head(&conf->wait_for_overlap);
7208 	INIT_LIST_HEAD(&conf->handle_list);
7209 	INIT_LIST_HEAD(&conf->loprio_list);
7210 	INIT_LIST_HEAD(&conf->hold_list);
7211 	INIT_LIST_HEAD(&conf->delayed_list);
7212 	INIT_LIST_HEAD(&conf->bitmap_list);
7213 	init_llist_head(&conf->released_stripes);
7214 	atomic_set(&conf->active_stripes, 0);
7215 	atomic_set(&conf->preread_active_stripes, 0);
7216 	atomic_set(&conf->active_aligned_reads, 0);
7217 	spin_lock_init(&conf->pending_bios_lock);
7218 	conf->batch_bio_dispatch = true;
7219 	rdev_for_each(rdev, mddev) {
7220 		if (test_bit(Journal, &rdev->flags))
7221 			continue;
7222 		if (blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
7223 			conf->batch_bio_dispatch = false;
7224 			break;
7225 		}
7226 	}
7227 
7228 	conf->bypass_threshold = BYPASS_THRESHOLD;
7229 	conf->recovery_disabled = mddev->recovery_disabled - 1;
7230 
7231 	conf->raid_disks = mddev->raid_disks;
7232 	if (mddev->reshape_position == MaxSector)
7233 		conf->previous_raid_disks = mddev->raid_disks;
7234 	else
7235 		conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
7236 	max_disks = max(conf->raid_disks, conf->previous_raid_disks);
7237 
7238 	conf->disks = kcalloc(max_disks, sizeof(struct disk_info),
7239 			      GFP_KERNEL);
7240 
7241 	if (!conf->disks)
7242 		goto abort;
7243 
7244 	for (i = 0; i < max_disks; i++) {
7245 		conf->disks[i].extra_page = alloc_page(GFP_KERNEL);
7246 		if (!conf->disks[i].extra_page)
7247 			goto abort;
7248 	}
7249 
7250 	ret = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
7251 	if (ret)
7252 		goto abort;
7253 	conf->mddev = mddev;
7254 
7255 	if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
7256 		goto abort;
7257 
7258 	/* We init hash_locks[0] separately to that it can be used
7259 	 * as the reference lock in the spin_lock_nest_lock() call
7260 	 * in lock_all_device_hash_locks_irq in order to convince
7261 	 * lockdep that we know what we are doing.
7262 	 */
7263 	spin_lock_init(conf->hash_locks);
7264 	for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
7265 		spin_lock_init(conf->hash_locks + i);
7266 
7267 	for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7268 		INIT_LIST_HEAD(conf->inactive_list + i);
7269 
7270 	for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7271 		INIT_LIST_HEAD(conf->temp_inactive_list + i);
7272 
7273 	atomic_set(&conf->r5c_cached_full_stripes, 0);
7274 	INIT_LIST_HEAD(&conf->r5c_full_stripe_list);
7275 	atomic_set(&conf->r5c_cached_partial_stripes, 0);
7276 	INIT_LIST_HEAD(&conf->r5c_partial_stripe_list);
7277 	atomic_set(&conf->r5c_flushing_full_stripes, 0);
7278 	atomic_set(&conf->r5c_flushing_partial_stripes, 0);
7279 
7280 	conf->level = mddev->new_level;
7281 	conf->chunk_sectors = mddev->new_chunk_sectors;
7282 	if (raid5_alloc_percpu(conf) != 0)
7283 		goto abort;
7284 
7285 	pr_debug("raid456: run(%s) called.\n", mdname(mddev));
7286 
7287 	rdev_for_each(rdev, mddev) {
7288 		raid_disk = rdev->raid_disk;
7289 		if (raid_disk >= max_disks
7290 		    || raid_disk < 0 || test_bit(Journal, &rdev->flags))
7291 			continue;
7292 		disk = conf->disks + raid_disk;
7293 
7294 		if (test_bit(Replacement, &rdev->flags)) {
7295 			if (disk->replacement)
7296 				goto abort;
7297 			disk->replacement = rdev;
7298 		} else {
7299 			if (disk->rdev)
7300 				goto abort;
7301 			disk->rdev = rdev;
7302 		}
7303 
7304 		if (test_bit(In_sync, &rdev->flags)) {
7305 			char b[BDEVNAME_SIZE];
7306 			pr_info("md/raid:%s: device %s operational as raid disk %d\n",
7307 				mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
7308 		} else if (rdev->saved_raid_disk != raid_disk)
7309 			/* Cannot rely on bitmap to complete recovery */
7310 			conf->fullsync = 1;
7311 	}
7312 
7313 	conf->level = mddev->new_level;
7314 	if (conf->level == 6) {
7315 		conf->max_degraded = 2;
7316 		if (raid6_call.xor_syndrome)
7317 			conf->rmw_level = PARITY_ENABLE_RMW;
7318 		else
7319 			conf->rmw_level = PARITY_DISABLE_RMW;
7320 	} else {
7321 		conf->max_degraded = 1;
7322 		conf->rmw_level = PARITY_ENABLE_RMW;
7323 	}
7324 	conf->algorithm = mddev->new_layout;
7325 	conf->reshape_progress = mddev->reshape_position;
7326 	if (conf->reshape_progress != MaxSector) {
7327 		conf->prev_chunk_sectors = mddev->chunk_sectors;
7328 		conf->prev_algo = mddev->layout;
7329 	} else {
7330 		conf->prev_chunk_sectors = conf->chunk_sectors;
7331 		conf->prev_algo = conf->algorithm;
7332 	}
7333 
7334 	conf->min_nr_stripes = NR_STRIPES;
7335 	if (mddev->reshape_position != MaxSector) {
7336 		int stripes = max_t(int,
7337 			((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4,
7338 			((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4);
7339 		conf->min_nr_stripes = max(NR_STRIPES, stripes);
7340 		if (conf->min_nr_stripes != NR_STRIPES)
7341 			pr_info("md/raid:%s: force stripe size %d for reshape\n",
7342 				mdname(mddev), conf->min_nr_stripes);
7343 	}
7344 	memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
7345 		 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
7346 	atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
7347 	if (grow_stripes(conf, conf->min_nr_stripes)) {
7348 		pr_warn("md/raid:%s: couldn't allocate %dkB for buffers\n",
7349 			mdname(mddev), memory);
7350 		goto abort;
7351 	} else
7352 		pr_debug("md/raid:%s: allocated %dkB\n", mdname(mddev), memory);
7353 	/*
7354 	 * Losing a stripe head costs more than the time to refill it,
7355 	 * it reduces the queue depth and so can hurt throughput.
7356 	 * So set it rather large, scaled by number of devices.
7357 	 */
7358 	conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
7359 	conf->shrinker.scan_objects = raid5_cache_scan;
7360 	conf->shrinker.count_objects = raid5_cache_count;
7361 	conf->shrinker.batch = 128;
7362 	conf->shrinker.flags = 0;
7363 	if (register_shrinker(&conf->shrinker)) {
7364 		pr_warn("md/raid:%s: couldn't register shrinker.\n",
7365 			mdname(mddev));
7366 		goto abort;
7367 	}
7368 
7369 	sprintf(pers_name, "raid%d", mddev->new_level);
7370 	conf->thread = md_register_thread(raid5d, mddev, pers_name);
7371 	if (!conf->thread) {
7372 		pr_warn("md/raid:%s: couldn't allocate thread.\n",
7373 			mdname(mddev));
7374 		goto abort;
7375 	}
7376 
7377 	return conf;
7378 
7379  abort:
7380 	if (conf) {
7381 		free_conf(conf);
7382 		return ERR_PTR(-EIO);
7383 	} else
7384 		return ERR_PTR(-ENOMEM);
7385 }
7386 
7387 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
7388 {
7389 	switch (algo) {
7390 	case ALGORITHM_PARITY_0:
7391 		if (raid_disk < max_degraded)
7392 			return 1;
7393 		break;
7394 	case ALGORITHM_PARITY_N:
7395 		if (raid_disk >= raid_disks - max_degraded)
7396 			return 1;
7397 		break;
7398 	case ALGORITHM_PARITY_0_6:
7399 		if (raid_disk == 0 ||
7400 		    raid_disk == raid_disks - 1)
7401 			return 1;
7402 		break;
7403 	case ALGORITHM_LEFT_ASYMMETRIC_6:
7404 	case ALGORITHM_RIGHT_ASYMMETRIC_6:
7405 	case ALGORITHM_LEFT_SYMMETRIC_6:
7406 	case ALGORITHM_RIGHT_SYMMETRIC_6:
7407 		if (raid_disk == raid_disks - 1)
7408 			return 1;
7409 	}
7410 	return 0;
7411 }
7412 
7413 static void raid5_set_io_opt(struct r5conf *conf)
7414 {
7415 	blk_queue_io_opt(conf->mddev->queue, (conf->chunk_sectors << 9) *
7416 			 (conf->raid_disks - conf->max_degraded));
7417 }
7418 
7419 static int raid5_run(struct mddev *mddev)
7420 {
7421 	struct r5conf *conf;
7422 	int working_disks = 0;
7423 	int dirty_parity_disks = 0;
7424 	struct md_rdev *rdev;
7425 	struct md_rdev *journal_dev = NULL;
7426 	sector_t reshape_offset = 0;
7427 	int i;
7428 	long long min_offset_diff = 0;
7429 	int first = 1;
7430 
7431 	if (mddev_init_writes_pending(mddev) < 0)
7432 		return -ENOMEM;
7433 
7434 	if (mddev->recovery_cp != MaxSector)
7435 		pr_notice("md/raid:%s: not clean -- starting background reconstruction\n",
7436 			  mdname(mddev));
7437 
7438 	rdev_for_each(rdev, mddev) {
7439 		long long diff;
7440 
7441 		if (test_bit(Journal, &rdev->flags)) {
7442 			journal_dev = rdev;
7443 			continue;
7444 		}
7445 		if (rdev->raid_disk < 0)
7446 			continue;
7447 		diff = (rdev->new_data_offset - rdev->data_offset);
7448 		if (first) {
7449 			min_offset_diff = diff;
7450 			first = 0;
7451 		} else if (mddev->reshape_backwards &&
7452 			 diff < min_offset_diff)
7453 			min_offset_diff = diff;
7454 		else if (!mddev->reshape_backwards &&
7455 			 diff > min_offset_diff)
7456 			min_offset_diff = diff;
7457 	}
7458 
7459 	if ((test_bit(MD_HAS_JOURNAL, &mddev->flags) || journal_dev) &&
7460 	    (mddev->bitmap_info.offset || mddev->bitmap_info.file)) {
7461 		pr_notice("md/raid:%s: array cannot have both journal and bitmap\n",
7462 			  mdname(mddev));
7463 		return -EINVAL;
7464 	}
7465 
7466 	if (mddev->reshape_position != MaxSector) {
7467 		/* Check that we can continue the reshape.
7468 		 * Difficulties arise if the stripe we would write to
7469 		 * next is at or after the stripe we would read from next.
7470 		 * For a reshape that changes the number of devices, this
7471 		 * is only possible for a very short time, and mdadm makes
7472 		 * sure that time appears to have past before assembling
7473 		 * the array.  So we fail if that time hasn't passed.
7474 		 * For a reshape that keeps the number of devices the same
7475 		 * mdadm must be monitoring the reshape can keeping the
7476 		 * critical areas read-only and backed up.  It will start
7477 		 * the array in read-only mode, so we check for that.
7478 		 */
7479 		sector_t here_new, here_old;
7480 		int old_disks;
7481 		int max_degraded = (mddev->level == 6 ? 2 : 1);
7482 		int chunk_sectors;
7483 		int new_data_disks;
7484 
7485 		if (journal_dev) {
7486 			pr_warn("md/raid:%s: don't support reshape with journal - aborting.\n",
7487 				mdname(mddev));
7488 			return -EINVAL;
7489 		}
7490 
7491 		if (mddev->new_level != mddev->level) {
7492 			pr_warn("md/raid:%s: unsupported reshape required - aborting.\n",
7493 				mdname(mddev));
7494 			return -EINVAL;
7495 		}
7496 		old_disks = mddev->raid_disks - mddev->delta_disks;
7497 		/* reshape_position must be on a new-stripe boundary, and one
7498 		 * further up in new geometry must map after here in old
7499 		 * geometry.
7500 		 * If the chunk sizes are different, then as we perform reshape
7501 		 * in units of the largest of the two, reshape_position needs
7502 		 * be a multiple of the largest chunk size times new data disks.
7503 		 */
7504 		here_new = mddev->reshape_position;
7505 		chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
7506 		new_data_disks = mddev->raid_disks - max_degraded;
7507 		if (sector_div(here_new, chunk_sectors * new_data_disks)) {
7508 			pr_warn("md/raid:%s: reshape_position not on a stripe boundary\n",
7509 				mdname(mddev));
7510 			return -EINVAL;
7511 		}
7512 		reshape_offset = here_new * chunk_sectors;
7513 		/* here_new is the stripe we will write to */
7514 		here_old = mddev->reshape_position;
7515 		sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
7516 		/* here_old is the first stripe that we might need to read
7517 		 * from */
7518 		if (mddev->delta_disks == 0) {
7519 			/* We cannot be sure it is safe to start an in-place
7520 			 * reshape.  It is only safe if user-space is monitoring
7521 			 * and taking constant backups.
7522 			 * mdadm always starts a situation like this in
7523 			 * readonly mode so it can take control before
7524 			 * allowing any writes.  So just check for that.
7525 			 */
7526 			if (abs(min_offset_diff) >= mddev->chunk_sectors &&
7527 			    abs(min_offset_diff) >= mddev->new_chunk_sectors)
7528 				/* not really in-place - so OK */;
7529 			else if (mddev->ro == 0) {
7530 				pr_warn("md/raid:%s: in-place reshape must be started in read-only mode - aborting\n",
7531 					mdname(mddev));
7532 				return -EINVAL;
7533 			}
7534 		} else if (mddev->reshape_backwards
7535 		    ? (here_new * chunk_sectors + min_offset_diff <=
7536 		       here_old * chunk_sectors)
7537 		    : (here_new * chunk_sectors >=
7538 		       here_old * chunk_sectors + (-min_offset_diff))) {
7539 			/* Reading from the same stripe as writing to - bad */
7540 			pr_warn("md/raid:%s: reshape_position too early for auto-recovery - aborting.\n",
7541 				mdname(mddev));
7542 			return -EINVAL;
7543 		}
7544 		pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev));
7545 		/* OK, we should be able to continue; */
7546 	} else {
7547 		BUG_ON(mddev->level != mddev->new_level);
7548 		BUG_ON(mddev->layout != mddev->new_layout);
7549 		BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
7550 		BUG_ON(mddev->delta_disks != 0);
7551 	}
7552 
7553 	if (test_bit(MD_HAS_JOURNAL, &mddev->flags) &&
7554 	    test_bit(MD_HAS_PPL, &mddev->flags)) {
7555 		pr_warn("md/raid:%s: using journal device and PPL not allowed - disabling PPL\n",
7556 			mdname(mddev));
7557 		clear_bit(MD_HAS_PPL, &mddev->flags);
7558 		clear_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags);
7559 	}
7560 
7561 	if (mddev->private == NULL)
7562 		conf = setup_conf(mddev);
7563 	else
7564 		conf = mddev->private;
7565 
7566 	if (IS_ERR(conf))
7567 		return PTR_ERR(conf);
7568 
7569 	if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
7570 		if (!journal_dev) {
7571 			pr_warn("md/raid:%s: journal disk is missing, force array readonly\n",
7572 				mdname(mddev));
7573 			mddev->ro = 1;
7574 			set_disk_ro(mddev->gendisk, 1);
7575 		} else if (mddev->recovery_cp == MaxSector)
7576 			set_bit(MD_JOURNAL_CLEAN, &mddev->flags);
7577 	}
7578 
7579 	conf->min_offset_diff = min_offset_diff;
7580 	mddev->thread = conf->thread;
7581 	conf->thread = NULL;
7582 	mddev->private = conf;
7583 
7584 	for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
7585 	     i++) {
7586 		rdev = conf->disks[i].rdev;
7587 		if (!rdev && conf->disks[i].replacement) {
7588 			/* The replacement is all we have yet */
7589 			rdev = conf->disks[i].replacement;
7590 			conf->disks[i].replacement = NULL;
7591 			clear_bit(Replacement, &rdev->flags);
7592 			conf->disks[i].rdev = rdev;
7593 		}
7594 		if (!rdev)
7595 			continue;
7596 		if (conf->disks[i].replacement &&
7597 		    conf->reshape_progress != MaxSector) {
7598 			/* replacements and reshape simply do not mix. */
7599 			pr_warn("md: cannot handle concurrent replacement and reshape.\n");
7600 			goto abort;
7601 		}
7602 		if (test_bit(In_sync, &rdev->flags)) {
7603 			working_disks++;
7604 			continue;
7605 		}
7606 		/* This disc is not fully in-sync.  However if it
7607 		 * just stored parity (beyond the recovery_offset),
7608 		 * when we don't need to be concerned about the
7609 		 * array being dirty.
7610 		 * When reshape goes 'backwards', we never have
7611 		 * partially completed devices, so we only need
7612 		 * to worry about reshape going forwards.
7613 		 */
7614 		/* Hack because v0.91 doesn't store recovery_offset properly. */
7615 		if (mddev->major_version == 0 &&
7616 		    mddev->minor_version > 90)
7617 			rdev->recovery_offset = reshape_offset;
7618 
7619 		if (rdev->recovery_offset < reshape_offset) {
7620 			/* We need to check old and new layout */
7621 			if (!only_parity(rdev->raid_disk,
7622 					 conf->algorithm,
7623 					 conf->raid_disks,
7624 					 conf->max_degraded))
7625 				continue;
7626 		}
7627 		if (!only_parity(rdev->raid_disk,
7628 				 conf->prev_algo,
7629 				 conf->previous_raid_disks,
7630 				 conf->max_degraded))
7631 			continue;
7632 		dirty_parity_disks++;
7633 	}
7634 
7635 	/*
7636 	 * 0 for a fully functional array, 1 or 2 for a degraded array.
7637 	 */
7638 	mddev->degraded = raid5_calc_degraded(conf);
7639 
7640 	if (has_failed(conf)) {
7641 		pr_crit("md/raid:%s: not enough operational devices (%d/%d failed)\n",
7642 			mdname(mddev), mddev->degraded, conf->raid_disks);
7643 		goto abort;
7644 	}
7645 
7646 	/* device size must be a multiple of chunk size */
7647 	mddev->dev_sectors &= ~((sector_t)mddev->chunk_sectors - 1);
7648 	mddev->resync_max_sectors = mddev->dev_sectors;
7649 
7650 	if (mddev->degraded > dirty_parity_disks &&
7651 	    mddev->recovery_cp != MaxSector) {
7652 		if (test_bit(MD_HAS_PPL, &mddev->flags))
7653 			pr_crit("md/raid:%s: starting dirty degraded array with PPL.\n",
7654 				mdname(mddev));
7655 		else if (mddev->ok_start_degraded)
7656 			pr_crit("md/raid:%s: starting dirty degraded array - data corruption possible.\n",
7657 				mdname(mddev));
7658 		else {
7659 			pr_crit("md/raid:%s: cannot start dirty degraded array.\n",
7660 				mdname(mddev));
7661 			goto abort;
7662 		}
7663 	}
7664 
7665 	pr_info("md/raid:%s: raid level %d active with %d out of %d devices, algorithm %d\n",
7666 		mdname(mddev), conf->level,
7667 		mddev->raid_disks-mddev->degraded, mddev->raid_disks,
7668 		mddev->new_layout);
7669 
7670 	print_raid5_conf(conf);
7671 
7672 	if (conf->reshape_progress != MaxSector) {
7673 		conf->reshape_safe = conf->reshape_progress;
7674 		atomic_set(&conf->reshape_stripes, 0);
7675 		clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7676 		clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7677 		set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7678 		set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7679 		mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7680 							"reshape");
7681 		if (!mddev->sync_thread)
7682 			goto abort;
7683 	}
7684 
7685 	/* Ok, everything is just fine now */
7686 	if (mddev->to_remove == &raid5_attrs_group)
7687 		mddev->to_remove = NULL;
7688 	else if (mddev->kobj.sd &&
7689 	    sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
7690 		pr_warn("raid5: failed to create sysfs attributes for %s\n",
7691 			mdname(mddev));
7692 	md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7693 
7694 	if (mddev->queue) {
7695 		int chunk_size;
7696 		/* read-ahead size must cover two whole stripes, which
7697 		 * is 2 * (datadisks) * chunksize where 'n' is the
7698 		 * number of raid devices
7699 		 */
7700 		int data_disks = conf->previous_raid_disks - conf->max_degraded;
7701 		int stripe = data_disks *
7702 			((mddev->chunk_sectors << 9) / PAGE_SIZE);
7703 
7704 		chunk_size = mddev->chunk_sectors << 9;
7705 		blk_queue_io_min(mddev->queue, chunk_size);
7706 		raid5_set_io_opt(conf);
7707 		mddev->queue->limits.raid_partial_stripes_expensive = 1;
7708 		/*
7709 		 * We can only discard a whole stripe. It doesn't make sense to
7710 		 * discard data disk but write parity disk
7711 		 */
7712 		stripe = stripe * PAGE_SIZE;
7713 		/* Round up to power of 2, as discard handling
7714 		 * currently assumes that */
7715 		while ((stripe-1) & stripe)
7716 			stripe = (stripe | (stripe-1)) + 1;
7717 		mddev->queue->limits.discard_alignment = stripe;
7718 		mddev->queue->limits.discard_granularity = stripe;
7719 
7720 		blk_queue_max_write_same_sectors(mddev->queue, 0);
7721 		blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
7722 
7723 		rdev_for_each(rdev, mddev) {
7724 			disk_stack_limits(mddev->gendisk, rdev->bdev,
7725 					  rdev->data_offset << 9);
7726 			disk_stack_limits(mddev->gendisk, rdev->bdev,
7727 					  rdev->new_data_offset << 9);
7728 		}
7729 
7730 		/*
7731 		 * zeroing is required, otherwise data
7732 		 * could be lost. Consider a scenario: discard a stripe
7733 		 * (the stripe could be inconsistent if
7734 		 * discard_zeroes_data is 0); write one disk of the
7735 		 * stripe (the stripe could be inconsistent again
7736 		 * depending on which disks are used to calculate
7737 		 * parity); the disk is broken; The stripe data of this
7738 		 * disk is lost.
7739 		 *
7740 		 * We only allow DISCARD if the sysadmin has confirmed that
7741 		 * only safe devices are in use by setting a module parameter.
7742 		 * A better idea might be to turn DISCARD into WRITE_ZEROES
7743 		 * requests, as that is required to be safe.
7744 		 */
7745 		if (devices_handle_discard_safely &&
7746 		    mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7747 		    mddev->queue->limits.discard_granularity >= stripe)
7748 			blk_queue_flag_set(QUEUE_FLAG_DISCARD,
7749 						mddev->queue);
7750 		else
7751 			blk_queue_flag_clear(QUEUE_FLAG_DISCARD,
7752 						mddev->queue);
7753 
7754 		blk_queue_max_hw_sectors(mddev->queue, UINT_MAX);
7755 	}
7756 
7757 	if (log_init(conf, journal_dev, raid5_has_ppl(conf)))
7758 		goto abort;
7759 
7760 	return 0;
7761 abort:
7762 	md_unregister_thread(&mddev->thread);
7763 	print_raid5_conf(conf);
7764 	free_conf(conf);
7765 	mddev->private = NULL;
7766 	pr_warn("md/raid:%s: failed to run raid set.\n", mdname(mddev));
7767 	return -EIO;
7768 }
7769 
7770 static void raid5_free(struct mddev *mddev, void *priv)
7771 {
7772 	struct r5conf *conf = priv;
7773 
7774 	free_conf(conf);
7775 	mddev->to_remove = &raid5_attrs_group;
7776 }
7777 
7778 static void raid5_status(struct seq_file *seq, struct mddev *mddev)
7779 {
7780 	struct r5conf *conf = mddev->private;
7781 	int i;
7782 
7783 	seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7784 		conf->chunk_sectors / 2, mddev->layout);
7785 	seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7786 	rcu_read_lock();
7787 	for (i = 0; i < conf->raid_disks; i++) {
7788 		struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
7789 		seq_printf (seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
7790 	}
7791 	rcu_read_unlock();
7792 	seq_printf (seq, "]");
7793 }
7794 
7795 static void print_raid5_conf (struct r5conf *conf)
7796 {
7797 	int i;
7798 	struct disk_info *tmp;
7799 
7800 	pr_debug("RAID conf printout:\n");
7801 	if (!conf) {
7802 		pr_debug("(conf==NULL)\n");
7803 		return;
7804 	}
7805 	pr_debug(" --- level:%d rd:%d wd:%d\n", conf->level,
7806 	       conf->raid_disks,
7807 	       conf->raid_disks - conf->mddev->degraded);
7808 
7809 	for (i = 0; i < conf->raid_disks; i++) {
7810 		char b[BDEVNAME_SIZE];
7811 		tmp = conf->disks + i;
7812 		if (tmp->rdev)
7813 			pr_debug(" disk %d, o:%d, dev:%s\n",
7814 			       i, !test_bit(Faulty, &tmp->rdev->flags),
7815 			       bdevname(tmp->rdev->bdev, b));
7816 	}
7817 }
7818 
7819 static int raid5_spare_active(struct mddev *mddev)
7820 {
7821 	int i;
7822 	struct r5conf *conf = mddev->private;
7823 	struct disk_info *tmp;
7824 	int count = 0;
7825 	unsigned long flags;
7826 
7827 	for (i = 0; i < conf->raid_disks; i++) {
7828 		tmp = conf->disks + i;
7829 		if (tmp->replacement
7830 		    && tmp->replacement->recovery_offset == MaxSector
7831 		    && !test_bit(Faulty, &tmp->replacement->flags)
7832 		    && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7833 			/* Replacement has just become active. */
7834 			if (!tmp->rdev
7835 			    || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7836 				count++;
7837 			if (tmp->rdev) {
7838 				/* Replaced device not technically faulty,
7839 				 * but we need to be sure it gets removed
7840 				 * and never re-added.
7841 				 */
7842 				set_bit(Faulty, &tmp->rdev->flags);
7843 				sysfs_notify_dirent_safe(
7844 					tmp->rdev->sysfs_state);
7845 			}
7846 			sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7847 		} else if (tmp->rdev
7848 		    && tmp->rdev->recovery_offset == MaxSector
7849 		    && !test_bit(Faulty, &tmp->rdev->flags)
7850 		    && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7851 			count++;
7852 			sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7853 		}
7854 	}
7855 	spin_lock_irqsave(&conf->device_lock, flags);
7856 	mddev->degraded = raid5_calc_degraded(conf);
7857 	spin_unlock_irqrestore(&conf->device_lock, flags);
7858 	print_raid5_conf(conf);
7859 	return count;
7860 }
7861 
7862 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7863 {
7864 	struct r5conf *conf = mddev->private;
7865 	int err = 0;
7866 	int number = rdev->raid_disk;
7867 	struct md_rdev **rdevp;
7868 	struct disk_info *p = conf->disks + number;
7869 
7870 	print_raid5_conf(conf);
7871 	if (test_bit(Journal, &rdev->flags) && conf->log) {
7872 		/*
7873 		 * we can't wait pending write here, as this is called in
7874 		 * raid5d, wait will deadlock.
7875 		 * neilb: there is no locking about new writes here,
7876 		 * so this cannot be safe.
7877 		 */
7878 		if (atomic_read(&conf->active_stripes) ||
7879 		    atomic_read(&conf->r5c_cached_full_stripes) ||
7880 		    atomic_read(&conf->r5c_cached_partial_stripes)) {
7881 			return -EBUSY;
7882 		}
7883 		log_exit(conf);
7884 		return 0;
7885 	}
7886 	if (rdev == p->rdev)
7887 		rdevp = &p->rdev;
7888 	else if (rdev == p->replacement)
7889 		rdevp = &p->replacement;
7890 	else
7891 		return 0;
7892 
7893 	if (number >= conf->raid_disks &&
7894 	    conf->reshape_progress == MaxSector)
7895 		clear_bit(In_sync, &rdev->flags);
7896 
7897 	if (test_bit(In_sync, &rdev->flags) ||
7898 	    atomic_read(&rdev->nr_pending)) {
7899 		err = -EBUSY;
7900 		goto abort;
7901 	}
7902 	/* Only remove non-faulty devices if recovery
7903 	 * isn't possible.
7904 	 */
7905 	if (!test_bit(Faulty, &rdev->flags) &&
7906 	    mddev->recovery_disabled != conf->recovery_disabled &&
7907 	    !has_failed(conf) &&
7908 	    (!p->replacement || p->replacement == rdev) &&
7909 	    number < conf->raid_disks) {
7910 		err = -EBUSY;
7911 		goto abort;
7912 	}
7913 	*rdevp = NULL;
7914 	if (!test_bit(RemoveSynchronized, &rdev->flags)) {
7915 		synchronize_rcu();
7916 		if (atomic_read(&rdev->nr_pending)) {
7917 			/* lost the race, try later */
7918 			err = -EBUSY;
7919 			*rdevp = rdev;
7920 		}
7921 	}
7922 	if (!err) {
7923 		err = log_modify(conf, rdev, false);
7924 		if (err)
7925 			goto abort;
7926 	}
7927 	if (p->replacement) {
7928 		/* We must have just cleared 'rdev' */
7929 		p->rdev = p->replacement;
7930 		clear_bit(Replacement, &p->replacement->flags);
7931 		smp_mb(); /* Make sure other CPUs may see both as identical
7932 			   * but will never see neither - if they are careful
7933 			   */
7934 		p->replacement = NULL;
7935 
7936 		if (!err)
7937 			err = log_modify(conf, p->rdev, true);
7938 	}
7939 
7940 	clear_bit(WantReplacement, &rdev->flags);
7941 abort:
7942 
7943 	print_raid5_conf(conf);
7944 	return err;
7945 }
7946 
7947 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7948 {
7949 	struct r5conf *conf = mddev->private;
7950 	int ret, err = -EEXIST;
7951 	int disk;
7952 	struct disk_info *p;
7953 	int first = 0;
7954 	int last = conf->raid_disks - 1;
7955 
7956 	if (test_bit(Journal, &rdev->flags)) {
7957 		if (conf->log)
7958 			return -EBUSY;
7959 
7960 		rdev->raid_disk = 0;
7961 		/*
7962 		 * The array is in readonly mode if journal is missing, so no
7963 		 * write requests running. We should be safe
7964 		 */
7965 		ret = log_init(conf, rdev, false);
7966 		if (ret)
7967 			return ret;
7968 
7969 		ret = r5l_start(conf->log);
7970 		if (ret)
7971 			return ret;
7972 
7973 		return 0;
7974 	}
7975 	if (mddev->recovery_disabled == conf->recovery_disabled)
7976 		return -EBUSY;
7977 
7978 	if (rdev->saved_raid_disk < 0 && has_failed(conf))
7979 		/* no point adding a device */
7980 		return -EINVAL;
7981 
7982 	if (rdev->raid_disk >= 0)
7983 		first = last = rdev->raid_disk;
7984 
7985 	/*
7986 	 * find the disk ... but prefer rdev->saved_raid_disk
7987 	 * if possible.
7988 	 */
7989 	if (rdev->saved_raid_disk >= 0 &&
7990 	    rdev->saved_raid_disk >= first &&
7991 	    conf->disks[rdev->saved_raid_disk].rdev == NULL)
7992 		first = rdev->saved_raid_disk;
7993 
7994 	for (disk = first; disk <= last; disk++) {
7995 		p = conf->disks + disk;
7996 		if (p->rdev == NULL) {
7997 			clear_bit(In_sync, &rdev->flags);
7998 			rdev->raid_disk = disk;
7999 			if (rdev->saved_raid_disk != disk)
8000 				conf->fullsync = 1;
8001 			rcu_assign_pointer(p->rdev, rdev);
8002 
8003 			err = log_modify(conf, rdev, true);
8004 
8005 			goto out;
8006 		}
8007 	}
8008 	for (disk = first; disk <= last; disk++) {
8009 		p = conf->disks + disk;
8010 		if (test_bit(WantReplacement, &p->rdev->flags) &&
8011 		    p->replacement == NULL) {
8012 			clear_bit(In_sync, &rdev->flags);
8013 			set_bit(Replacement, &rdev->flags);
8014 			rdev->raid_disk = disk;
8015 			err = 0;
8016 			conf->fullsync = 1;
8017 			rcu_assign_pointer(p->replacement, rdev);
8018 			break;
8019 		}
8020 	}
8021 out:
8022 	print_raid5_conf(conf);
8023 	return err;
8024 }
8025 
8026 static int raid5_resize(struct mddev *mddev, sector_t sectors)
8027 {
8028 	/* no resync is happening, and there is enough space
8029 	 * on all devices, so we can resize.
8030 	 * We need to make sure resync covers any new space.
8031 	 * If the array is shrinking we should possibly wait until
8032 	 * any io in the removed space completes, but it hardly seems
8033 	 * worth it.
8034 	 */
8035 	sector_t newsize;
8036 	struct r5conf *conf = mddev->private;
8037 
8038 	if (raid5_has_log(conf) || raid5_has_ppl(conf))
8039 		return -EINVAL;
8040 	sectors &= ~((sector_t)conf->chunk_sectors - 1);
8041 	newsize = raid5_size(mddev, sectors, mddev->raid_disks);
8042 	if (mddev->external_size &&
8043 	    mddev->array_sectors > newsize)
8044 		return -EINVAL;
8045 	if (mddev->bitmap) {
8046 		int ret = md_bitmap_resize(mddev->bitmap, sectors, 0, 0);
8047 		if (ret)
8048 			return ret;
8049 	}
8050 	md_set_array_sectors(mddev, newsize);
8051 	if (sectors > mddev->dev_sectors &&
8052 	    mddev->recovery_cp > mddev->dev_sectors) {
8053 		mddev->recovery_cp = mddev->dev_sectors;
8054 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8055 	}
8056 	mddev->dev_sectors = sectors;
8057 	mddev->resync_max_sectors = sectors;
8058 	return 0;
8059 }
8060 
8061 static int check_stripe_cache(struct mddev *mddev)
8062 {
8063 	/* Can only proceed if there are plenty of stripe_heads.
8064 	 * We need a minimum of one full stripe,, and for sensible progress
8065 	 * it is best to have about 4 times that.
8066 	 * If we require 4 times, then the default 256 4K stripe_heads will
8067 	 * allow for chunk sizes up to 256K, which is probably OK.
8068 	 * If the chunk size is greater, user-space should request more
8069 	 * stripe_heads first.
8070 	 */
8071 	struct r5conf *conf = mddev->private;
8072 	if (((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8073 	    > conf->min_nr_stripes ||
8074 	    ((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8075 	    > conf->min_nr_stripes) {
8076 		pr_warn("md/raid:%s: reshape: not enough stripes.  Needed %lu\n",
8077 			mdname(mddev),
8078 			((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
8079 			 / RAID5_STRIPE_SIZE(conf))*4);
8080 		return 0;
8081 	}
8082 	return 1;
8083 }
8084 
8085 static int check_reshape(struct mddev *mddev)
8086 {
8087 	struct r5conf *conf = mddev->private;
8088 
8089 	if (raid5_has_log(conf) || raid5_has_ppl(conf))
8090 		return -EINVAL;
8091 	if (mddev->delta_disks == 0 &&
8092 	    mddev->new_layout == mddev->layout &&
8093 	    mddev->new_chunk_sectors == mddev->chunk_sectors)
8094 		return 0; /* nothing to do */
8095 	if (has_failed(conf))
8096 		return -EINVAL;
8097 	if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
8098 		/* We might be able to shrink, but the devices must
8099 		 * be made bigger first.
8100 		 * For raid6, 4 is the minimum size.
8101 		 * Otherwise 2 is the minimum
8102 		 */
8103 		int min = 2;
8104 		if (mddev->level == 6)
8105 			min = 4;
8106 		if (mddev->raid_disks + mddev->delta_disks < min)
8107 			return -EINVAL;
8108 	}
8109 
8110 	if (!check_stripe_cache(mddev))
8111 		return -ENOSPC;
8112 
8113 	if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
8114 	    mddev->delta_disks > 0)
8115 		if (resize_chunks(conf,
8116 				  conf->previous_raid_disks
8117 				  + max(0, mddev->delta_disks),
8118 				  max(mddev->new_chunk_sectors,
8119 				      mddev->chunk_sectors)
8120 			    ) < 0)
8121 			return -ENOMEM;
8122 
8123 	if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
8124 		return 0; /* never bother to shrink */
8125 	return resize_stripes(conf, (conf->previous_raid_disks
8126 				     + mddev->delta_disks));
8127 }
8128 
8129 static int raid5_start_reshape(struct mddev *mddev)
8130 {
8131 	struct r5conf *conf = mddev->private;
8132 	struct md_rdev *rdev;
8133 	int spares = 0;
8134 	unsigned long flags;
8135 
8136 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
8137 		return -EBUSY;
8138 
8139 	if (!check_stripe_cache(mddev))
8140 		return -ENOSPC;
8141 
8142 	if (has_failed(conf))
8143 		return -EINVAL;
8144 
8145 	rdev_for_each(rdev, mddev) {
8146 		if (!test_bit(In_sync, &rdev->flags)
8147 		    && !test_bit(Faulty, &rdev->flags))
8148 			spares++;
8149 	}
8150 
8151 	if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
8152 		/* Not enough devices even to make a degraded array
8153 		 * of that size
8154 		 */
8155 		return -EINVAL;
8156 
8157 	/* Refuse to reduce size of the array.  Any reductions in
8158 	 * array size must be through explicit setting of array_size
8159 	 * attribute.
8160 	 */
8161 	if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
8162 	    < mddev->array_sectors) {
8163 		pr_warn("md/raid:%s: array size must be reduced before number of disks\n",
8164 			mdname(mddev));
8165 		return -EINVAL;
8166 	}
8167 
8168 	atomic_set(&conf->reshape_stripes, 0);
8169 	spin_lock_irq(&conf->device_lock);
8170 	write_seqcount_begin(&conf->gen_lock);
8171 	conf->previous_raid_disks = conf->raid_disks;
8172 	conf->raid_disks += mddev->delta_disks;
8173 	conf->prev_chunk_sectors = conf->chunk_sectors;
8174 	conf->chunk_sectors = mddev->new_chunk_sectors;
8175 	conf->prev_algo = conf->algorithm;
8176 	conf->algorithm = mddev->new_layout;
8177 	conf->generation++;
8178 	/* Code that selects data_offset needs to see the generation update
8179 	 * if reshape_progress has been set - so a memory barrier needed.
8180 	 */
8181 	smp_mb();
8182 	if (mddev->reshape_backwards)
8183 		conf->reshape_progress = raid5_size(mddev, 0, 0);
8184 	else
8185 		conf->reshape_progress = 0;
8186 	conf->reshape_safe = conf->reshape_progress;
8187 	write_seqcount_end(&conf->gen_lock);
8188 	spin_unlock_irq(&conf->device_lock);
8189 
8190 	/* Now make sure any requests that proceeded on the assumption
8191 	 * the reshape wasn't running - like Discard or Read - have
8192 	 * completed.
8193 	 */
8194 	mddev_suspend(mddev);
8195 	mddev_resume(mddev);
8196 
8197 	/* Add some new drives, as many as will fit.
8198 	 * We know there are enough to make the newly sized array work.
8199 	 * Don't add devices if we are reducing the number of
8200 	 * devices in the array.  This is because it is not possible
8201 	 * to correctly record the "partially reconstructed" state of
8202 	 * such devices during the reshape and confusion could result.
8203 	 */
8204 	if (mddev->delta_disks >= 0) {
8205 		rdev_for_each(rdev, mddev)
8206 			if (rdev->raid_disk < 0 &&
8207 			    !test_bit(Faulty, &rdev->flags)) {
8208 				if (raid5_add_disk(mddev, rdev) == 0) {
8209 					if (rdev->raid_disk
8210 					    >= conf->previous_raid_disks)
8211 						set_bit(In_sync, &rdev->flags);
8212 					else
8213 						rdev->recovery_offset = 0;
8214 
8215 					/* Failure here is OK */
8216 					sysfs_link_rdev(mddev, rdev);
8217 				}
8218 			} else if (rdev->raid_disk >= conf->previous_raid_disks
8219 				   && !test_bit(Faulty, &rdev->flags)) {
8220 				/* This is a spare that was manually added */
8221 				set_bit(In_sync, &rdev->flags);
8222 			}
8223 
8224 		/* When a reshape changes the number of devices,
8225 		 * ->degraded is measured against the larger of the
8226 		 * pre and post number of devices.
8227 		 */
8228 		spin_lock_irqsave(&conf->device_lock, flags);
8229 		mddev->degraded = raid5_calc_degraded(conf);
8230 		spin_unlock_irqrestore(&conf->device_lock, flags);
8231 	}
8232 	mddev->raid_disks = conf->raid_disks;
8233 	mddev->reshape_position = conf->reshape_progress;
8234 	set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8235 
8236 	clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8237 	clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8238 	clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8239 	set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8240 	set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8241 	mddev->sync_thread = md_register_thread(md_do_sync, mddev,
8242 						"reshape");
8243 	if (!mddev->sync_thread) {
8244 		mddev->recovery = 0;
8245 		spin_lock_irq(&conf->device_lock);
8246 		write_seqcount_begin(&conf->gen_lock);
8247 		mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
8248 		mddev->new_chunk_sectors =
8249 			conf->chunk_sectors = conf->prev_chunk_sectors;
8250 		mddev->new_layout = conf->algorithm = conf->prev_algo;
8251 		rdev_for_each(rdev, mddev)
8252 			rdev->new_data_offset = rdev->data_offset;
8253 		smp_wmb();
8254 		conf->generation --;
8255 		conf->reshape_progress = MaxSector;
8256 		mddev->reshape_position = MaxSector;
8257 		write_seqcount_end(&conf->gen_lock);
8258 		spin_unlock_irq(&conf->device_lock);
8259 		return -EAGAIN;
8260 	}
8261 	conf->reshape_checkpoint = jiffies;
8262 	md_wakeup_thread(mddev->sync_thread);
8263 	md_new_event(mddev);
8264 	return 0;
8265 }
8266 
8267 /* This is called from the reshape thread and should make any
8268  * changes needed in 'conf'
8269  */
8270 static void end_reshape(struct r5conf *conf)
8271 {
8272 
8273 	if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
8274 		struct md_rdev *rdev;
8275 
8276 		spin_lock_irq(&conf->device_lock);
8277 		conf->previous_raid_disks = conf->raid_disks;
8278 		md_finish_reshape(conf->mddev);
8279 		smp_wmb();
8280 		conf->reshape_progress = MaxSector;
8281 		conf->mddev->reshape_position = MaxSector;
8282 		rdev_for_each(rdev, conf->mddev)
8283 			if (rdev->raid_disk >= 0 &&
8284 			    !test_bit(Journal, &rdev->flags) &&
8285 			    !test_bit(In_sync, &rdev->flags))
8286 				rdev->recovery_offset = MaxSector;
8287 		spin_unlock_irq(&conf->device_lock);
8288 		wake_up(&conf->wait_for_overlap);
8289 
8290 		if (conf->mddev->queue)
8291 			raid5_set_io_opt(conf);
8292 	}
8293 }
8294 
8295 /* This is called from the raid5d thread with mddev_lock held.
8296  * It makes config changes to the device.
8297  */
8298 static void raid5_finish_reshape(struct mddev *mddev)
8299 {
8300 	struct r5conf *conf = mddev->private;
8301 
8302 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8303 
8304 		if (mddev->delta_disks <= 0) {
8305 			int d;
8306 			spin_lock_irq(&conf->device_lock);
8307 			mddev->degraded = raid5_calc_degraded(conf);
8308 			spin_unlock_irq(&conf->device_lock);
8309 			for (d = conf->raid_disks ;
8310 			     d < conf->raid_disks - mddev->delta_disks;
8311 			     d++) {
8312 				struct md_rdev *rdev = conf->disks[d].rdev;
8313 				if (rdev)
8314 					clear_bit(In_sync, &rdev->flags);
8315 				rdev = conf->disks[d].replacement;
8316 				if (rdev)
8317 					clear_bit(In_sync, &rdev->flags);
8318 			}
8319 		}
8320 		mddev->layout = conf->algorithm;
8321 		mddev->chunk_sectors = conf->chunk_sectors;
8322 		mddev->reshape_position = MaxSector;
8323 		mddev->delta_disks = 0;
8324 		mddev->reshape_backwards = 0;
8325 	}
8326 }
8327 
8328 static void raid5_quiesce(struct mddev *mddev, int quiesce)
8329 {
8330 	struct r5conf *conf = mddev->private;
8331 
8332 	if (quiesce) {
8333 		/* stop all writes */
8334 		lock_all_device_hash_locks_irq(conf);
8335 		/* '2' tells resync/reshape to pause so that all
8336 		 * active stripes can drain
8337 		 */
8338 		r5c_flush_cache(conf, INT_MAX);
8339 		conf->quiesce = 2;
8340 		wait_event_cmd(conf->wait_for_quiescent,
8341 				    atomic_read(&conf->active_stripes) == 0 &&
8342 				    atomic_read(&conf->active_aligned_reads) == 0,
8343 				    unlock_all_device_hash_locks_irq(conf),
8344 				    lock_all_device_hash_locks_irq(conf));
8345 		conf->quiesce = 1;
8346 		unlock_all_device_hash_locks_irq(conf);
8347 		/* allow reshape to continue */
8348 		wake_up(&conf->wait_for_overlap);
8349 	} else {
8350 		/* re-enable writes */
8351 		lock_all_device_hash_locks_irq(conf);
8352 		conf->quiesce = 0;
8353 		wake_up(&conf->wait_for_quiescent);
8354 		wake_up(&conf->wait_for_overlap);
8355 		unlock_all_device_hash_locks_irq(conf);
8356 	}
8357 	log_quiesce(conf, quiesce);
8358 }
8359 
8360 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
8361 {
8362 	struct r0conf *raid0_conf = mddev->private;
8363 	sector_t sectors;
8364 
8365 	/* for raid0 takeover only one zone is supported */
8366 	if (raid0_conf->nr_strip_zones > 1) {
8367 		pr_warn("md/raid:%s: cannot takeover raid0 with more than one zone.\n",
8368 			mdname(mddev));
8369 		return ERR_PTR(-EINVAL);
8370 	}
8371 
8372 	sectors = raid0_conf->strip_zone[0].zone_end;
8373 	sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
8374 	mddev->dev_sectors = sectors;
8375 	mddev->new_level = level;
8376 	mddev->new_layout = ALGORITHM_PARITY_N;
8377 	mddev->new_chunk_sectors = mddev->chunk_sectors;
8378 	mddev->raid_disks += 1;
8379 	mddev->delta_disks = 1;
8380 	/* make sure it will be not marked as dirty */
8381 	mddev->recovery_cp = MaxSector;
8382 
8383 	return setup_conf(mddev);
8384 }
8385 
8386 static void *raid5_takeover_raid1(struct mddev *mddev)
8387 {
8388 	int chunksect;
8389 	void *ret;
8390 
8391 	if (mddev->raid_disks != 2 ||
8392 	    mddev->degraded > 1)
8393 		return ERR_PTR(-EINVAL);
8394 
8395 	/* Should check if there are write-behind devices? */
8396 
8397 	chunksect = 64*2; /* 64K by default */
8398 
8399 	/* The array must be an exact multiple of chunksize */
8400 	while (chunksect && (mddev->array_sectors & (chunksect-1)))
8401 		chunksect >>= 1;
8402 
8403 	if ((chunksect<<9) < RAID5_STRIPE_SIZE((struct r5conf *)mddev->private))
8404 		/* array size does not allow a suitable chunk size */
8405 		return ERR_PTR(-EINVAL);
8406 
8407 	mddev->new_level = 5;
8408 	mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
8409 	mddev->new_chunk_sectors = chunksect;
8410 
8411 	ret = setup_conf(mddev);
8412 	if (!IS_ERR(ret))
8413 		mddev_clear_unsupported_flags(mddev,
8414 			UNSUPPORTED_MDDEV_FLAGS);
8415 	return ret;
8416 }
8417 
8418 static void *raid5_takeover_raid6(struct mddev *mddev)
8419 {
8420 	int new_layout;
8421 
8422 	switch (mddev->layout) {
8423 	case ALGORITHM_LEFT_ASYMMETRIC_6:
8424 		new_layout = ALGORITHM_LEFT_ASYMMETRIC;
8425 		break;
8426 	case ALGORITHM_RIGHT_ASYMMETRIC_6:
8427 		new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
8428 		break;
8429 	case ALGORITHM_LEFT_SYMMETRIC_6:
8430 		new_layout = ALGORITHM_LEFT_SYMMETRIC;
8431 		break;
8432 	case ALGORITHM_RIGHT_SYMMETRIC_6:
8433 		new_layout = ALGORITHM_RIGHT_SYMMETRIC;
8434 		break;
8435 	case ALGORITHM_PARITY_0_6:
8436 		new_layout = ALGORITHM_PARITY_0;
8437 		break;
8438 	case ALGORITHM_PARITY_N:
8439 		new_layout = ALGORITHM_PARITY_N;
8440 		break;
8441 	default:
8442 		return ERR_PTR(-EINVAL);
8443 	}
8444 	mddev->new_level = 5;
8445 	mddev->new_layout = new_layout;
8446 	mddev->delta_disks = -1;
8447 	mddev->raid_disks -= 1;
8448 	return setup_conf(mddev);
8449 }
8450 
8451 static int raid5_check_reshape(struct mddev *mddev)
8452 {
8453 	/* For a 2-drive array, the layout and chunk size can be changed
8454 	 * immediately as not restriping is needed.
8455 	 * For larger arrays we record the new value - after validation
8456 	 * to be used by a reshape pass.
8457 	 */
8458 	struct r5conf *conf = mddev->private;
8459 	int new_chunk = mddev->new_chunk_sectors;
8460 
8461 	if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
8462 		return -EINVAL;
8463 	if (new_chunk > 0) {
8464 		if (!is_power_of_2(new_chunk))
8465 			return -EINVAL;
8466 		if (new_chunk < (PAGE_SIZE>>9))
8467 			return -EINVAL;
8468 		if (mddev->array_sectors & (new_chunk-1))
8469 			/* not factor of array size */
8470 			return -EINVAL;
8471 	}
8472 
8473 	/* They look valid */
8474 
8475 	if (mddev->raid_disks == 2) {
8476 		/* can make the change immediately */
8477 		if (mddev->new_layout >= 0) {
8478 			conf->algorithm = mddev->new_layout;
8479 			mddev->layout = mddev->new_layout;
8480 		}
8481 		if (new_chunk > 0) {
8482 			conf->chunk_sectors = new_chunk ;
8483 			mddev->chunk_sectors = new_chunk;
8484 		}
8485 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8486 		md_wakeup_thread(mddev->thread);
8487 	}
8488 	return check_reshape(mddev);
8489 }
8490 
8491 static int raid6_check_reshape(struct mddev *mddev)
8492 {
8493 	int new_chunk = mddev->new_chunk_sectors;
8494 
8495 	if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
8496 		return -EINVAL;
8497 	if (new_chunk > 0) {
8498 		if (!is_power_of_2(new_chunk))
8499 			return -EINVAL;
8500 		if (new_chunk < (PAGE_SIZE >> 9))
8501 			return -EINVAL;
8502 		if (mddev->array_sectors & (new_chunk-1))
8503 			/* not factor of array size */
8504 			return -EINVAL;
8505 	}
8506 
8507 	/* They look valid */
8508 	return check_reshape(mddev);
8509 }
8510 
8511 static void *raid5_takeover(struct mddev *mddev)
8512 {
8513 	/* raid5 can take over:
8514 	 *  raid0 - if there is only one strip zone - make it a raid4 layout
8515 	 *  raid1 - if there are two drives.  We need to know the chunk size
8516 	 *  raid4 - trivial - just use a raid4 layout.
8517 	 *  raid6 - Providing it is a *_6 layout
8518 	 */
8519 	if (mddev->level == 0)
8520 		return raid45_takeover_raid0(mddev, 5);
8521 	if (mddev->level == 1)
8522 		return raid5_takeover_raid1(mddev);
8523 	if (mddev->level == 4) {
8524 		mddev->new_layout = ALGORITHM_PARITY_N;
8525 		mddev->new_level = 5;
8526 		return setup_conf(mddev);
8527 	}
8528 	if (mddev->level == 6)
8529 		return raid5_takeover_raid6(mddev);
8530 
8531 	return ERR_PTR(-EINVAL);
8532 }
8533 
8534 static void *raid4_takeover(struct mddev *mddev)
8535 {
8536 	/* raid4 can take over:
8537 	 *  raid0 - if there is only one strip zone
8538 	 *  raid5 - if layout is right
8539 	 */
8540 	if (mddev->level == 0)
8541 		return raid45_takeover_raid0(mddev, 4);
8542 	if (mddev->level == 5 &&
8543 	    mddev->layout == ALGORITHM_PARITY_N) {
8544 		mddev->new_layout = 0;
8545 		mddev->new_level = 4;
8546 		return setup_conf(mddev);
8547 	}
8548 	return ERR_PTR(-EINVAL);
8549 }
8550 
8551 static struct md_personality raid5_personality;
8552 
8553 static void *raid6_takeover(struct mddev *mddev)
8554 {
8555 	/* Currently can only take over a raid5.  We map the
8556 	 * personality to an equivalent raid6 personality
8557 	 * with the Q block at the end.
8558 	 */
8559 	int new_layout;
8560 
8561 	if (mddev->pers != &raid5_personality)
8562 		return ERR_PTR(-EINVAL);
8563 	if (mddev->degraded > 1)
8564 		return ERR_PTR(-EINVAL);
8565 	if (mddev->raid_disks > 253)
8566 		return ERR_PTR(-EINVAL);
8567 	if (mddev->raid_disks < 3)
8568 		return ERR_PTR(-EINVAL);
8569 
8570 	switch (mddev->layout) {
8571 	case ALGORITHM_LEFT_ASYMMETRIC:
8572 		new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
8573 		break;
8574 	case ALGORITHM_RIGHT_ASYMMETRIC:
8575 		new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
8576 		break;
8577 	case ALGORITHM_LEFT_SYMMETRIC:
8578 		new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
8579 		break;
8580 	case ALGORITHM_RIGHT_SYMMETRIC:
8581 		new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
8582 		break;
8583 	case ALGORITHM_PARITY_0:
8584 		new_layout = ALGORITHM_PARITY_0_6;
8585 		break;
8586 	case ALGORITHM_PARITY_N:
8587 		new_layout = ALGORITHM_PARITY_N;
8588 		break;
8589 	default:
8590 		return ERR_PTR(-EINVAL);
8591 	}
8592 	mddev->new_level = 6;
8593 	mddev->new_layout = new_layout;
8594 	mddev->delta_disks = 1;
8595 	mddev->raid_disks += 1;
8596 	return setup_conf(mddev);
8597 }
8598 
8599 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
8600 {
8601 	struct r5conf *conf;
8602 	int err;
8603 
8604 	err = mddev_lock(mddev);
8605 	if (err)
8606 		return err;
8607 	conf = mddev->private;
8608 	if (!conf) {
8609 		mddev_unlock(mddev);
8610 		return -ENODEV;
8611 	}
8612 
8613 	if (strncmp(buf, "ppl", 3) == 0) {
8614 		/* ppl only works with RAID 5 */
8615 		if (!raid5_has_ppl(conf) && conf->level == 5) {
8616 			err = log_init(conf, NULL, true);
8617 			if (!err) {
8618 				err = resize_stripes(conf, conf->pool_size);
8619 				if (err)
8620 					log_exit(conf);
8621 			}
8622 		} else
8623 			err = -EINVAL;
8624 	} else if (strncmp(buf, "resync", 6) == 0) {
8625 		if (raid5_has_ppl(conf)) {
8626 			mddev_suspend(mddev);
8627 			log_exit(conf);
8628 			mddev_resume(mddev);
8629 			err = resize_stripes(conf, conf->pool_size);
8630 		} else if (test_bit(MD_HAS_JOURNAL, &conf->mddev->flags) &&
8631 			   r5l_log_disk_error(conf)) {
8632 			bool journal_dev_exists = false;
8633 			struct md_rdev *rdev;
8634 
8635 			rdev_for_each(rdev, mddev)
8636 				if (test_bit(Journal, &rdev->flags)) {
8637 					journal_dev_exists = true;
8638 					break;
8639 				}
8640 
8641 			if (!journal_dev_exists) {
8642 				mddev_suspend(mddev);
8643 				clear_bit(MD_HAS_JOURNAL, &mddev->flags);
8644 				mddev_resume(mddev);
8645 			} else  /* need remove journal device first */
8646 				err = -EBUSY;
8647 		} else
8648 			err = -EINVAL;
8649 	} else {
8650 		err = -EINVAL;
8651 	}
8652 
8653 	if (!err)
8654 		md_update_sb(mddev, 1);
8655 
8656 	mddev_unlock(mddev);
8657 
8658 	return err;
8659 }
8660 
8661 static int raid5_start(struct mddev *mddev)
8662 {
8663 	struct r5conf *conf = mddev->private;
8664 
8665 	return r5l_start(conf->log);
8666 }
8667 
8668 static struct md_personality raid6_personality =
8669 {
8670 	.name		= "raid6",
8671 	.level		= 6,
8672 	.owner		= THIS_MODULE,
8673 	.make_request	= raid5_make_request,
8674 	.run		= raid5_run,
8675 	.start		= raid5_start,
8676 	.free		= raid5_free,
8677 	.status		= raid5_status,
8678 	.error_handler	= raid5_error,
8679 	.hot_add_disk	= raid5_add_disk,
8680 	.hot_remove_disk= raid5_remove_disk,
8681 	.spare_active	= raid5_spare_active,
8682 	.sync_request	= raid5_sync_request,
8683 	.resize		= raid5_resize,
8684 	.size		= raid5_size,
8685 	.check_reshape	= raid6_check_reshape,
8686 	.start_reshape  = raid5_start_reshape,
8687 	.finish_reshape = raid5_finish_reshape,
8688 	.quiesce	= raid5_quiesce,
8689 	.takeover	= raid6_takeover,
8690 	.change_consistency_policy = raid5_change_consistency_policy,
8691 };
8692 static struct md_personality raid5_personality =
8693 {
8694 	.name		= "raid5",
8695 	.level		= 5,
8696 	.owner		= THIS_MODULE,
8697 	.make_request	= raid5_make_request,
8698 	.run		= raid5_run,
8699 	.start		= raid5_start,
8700 	.free		= raid5_free,
8701 	.status		= raid5_status,
8702 	.error_handler	= raid5_error,
8703 	.hot_add_disk	= raid5_add_disk,
8704 	.hot_remove_disk= raid5_remove_disk,
8705 	.spare_active	= raid5_spare_active,
8706 	.sync_request	= raid5_sync_request,
8707 	.resize		= raid5_resize,
8708 	.size		= raid5_size,
8709 	.check_reshape	= raid5_check_reshape,
8710 	.start_reshape  = raid5_start_reshape,
8711 	.finish_reshape = raid5_finish_reshape,
8712 	.quiesce	= raid5_quiesce,
8713 	.takeover	= raid5_takeover,
8714 	.change_consistency_policy = raid5_change_consistency_policy,
8715 };
8716 
8717 static struct md_personality raid4_personality =
8718 {
8719 	.name		= "raid4",
8720 	.level		= 4,
8721 	.owner		= THIS_MODULE,
8722 	.make_request	= raid5_make_request,
8723 	.run		= raid5_run,
8724 	.start		= raid5_start,
8725 	.free		= raid5_free,
8726 	.status		= raid5_status,
8727 	.error_handler	= raid5_error,
8728 	.hot_add_disk	= raid5_add_disk,
8729 	.hot_remove_disk= raid5_remove_disk,
8730 	.spare_active	= raid5_spare_active,
8731 	.sync_request	= raid5_sync_request,
8732 	.resize		= raid5_resize,
8733 	.size		= raid5_size,
8734 	.check_reshape	= raid5_check_reshape,
8735 	.start_reshape  = raid5_start_reshape,
8736 	.finish_reshape = raid5_finish_reshape,
8737 	.quiesce	= raid5_quiesce,
8738 	.takeover	= raid4_takeover,
8739 	.change_consistency_policy = raid5_change_consistency_policy,
8740 };
8741 
8742 static int __init raid5_init(void)
8743 {
8744 	int ret;
8745 
8746 	raid5_wq = alloc_workqueue("raid5wq",
8747 		WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
8748 	if (!raid5_wq)
8749 		return -ENOMEM;
8750 
8751 	ret = cpuhp_setup_state_multi(CPUHP_MD_RAID5_PREPARE,
8752 				      "md/raid5:prepare",
8753 				      raid456_cpu_up_prepare,
8754 				      raid456_cpu_dead);
8755 	if (ret) {
8756 		destroy_workqueue(raid5_wq);
8757 		return ret;
8758 	}
8759 	register_md_personality(&raid6_personality);
8760 	register_md_personality(&raid5_personality);
8761 	register_md_personality(&raid4_personality);
8762 	return 0;
8763 }
8764 
8765 static void raid5_exit(void)
8766 {
8767 	unregister_md_personality(&raid6_personality);
8768 	unregister_md_personality(&raid5_personality);
8769 	unregister_md_personality(&raid4_personality);
8770 	cpuhp_remove_multi_state(CPUHP_MD_RAID5_PREPARE);
8771 	destroy_workqueue(raid5_wq);
8772 }
8773 
8774 module_init(raid5_init);
8775 module_exit(raid5_exit);
8776 MODULE_LICENSE("GPL");
8777 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
8778 MODULE_ALIAS("md-personality-4"); /* RAID5 */
8779 MODULE_ALIAS("md-raid5");
8780 MODULE_ALIAS("md-raid4");
8781 MODULE_ALIAS("md-level-5");
8782 MODULE_ALIAS("md-level-4");
8783 MODULE_ALIAS("md-personality-8"); /* RAID6 */
8784 MODULE_ALIAS("md-raid6");
8785 MODULE_ALIAS("md-level-6");
8786 
8787 /* This used to be two separate modules, they were: */
8788 MODULE_ALIAS("raid5");
8789 MODULE_ALIAS("raid6");
8790