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