xref: /openbmc/linux/drivers/md/raid5.c (revision e15a5365)
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->bi_disk->queue,
1226 						      bi, 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->bi_disk->queue,
1276 						      rbi, 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_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 	int dd_idx;
5397 	struct bio* align_bi;
5398 	struct md_rdev *rdev;
5399 	sector_t end_sector;
5400 
5401 	if (!in_chunk_boundary(mddev, raid_bio)) {
5402 		pr_debug("%s: non aligned\n", __func__);
5403 		return 0;
5404 	}
5405 	/*
5406 	 * use bio_clone_fast to make a copy of the bio
5407 	 */
5408 	align_bi = bio_clone_fast(raid_bio, GFP_NOIO, &mddev->bio_set);
5409 	if (!align_bi)
5410 		return 0;
5411 	/*
5412 	 *   set bi_end_io to a new function, and set bi_private to the
5413 	 *     original bio.
5414 	 */
5415 	align_bi->bi_end_io  = raid5_align_endio;
5416 	align_bi->bi_private = raid_bio;
5417 	/*
5418 	 *	compute position
5419 	 */
5420 	align_bi->bi_iter.bi_sector =
5421 		raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
5422 				     0, &dd_idx, NULL);
5423 
5424 	end_sector = bio_end_sector(align_bi);
5425 	rcu_read_lock();
5426 	rdev = rcu_dereference(conf->disks[dd_idx].replacement);
5427 	if (!rdev || test_bit(Faulty, &rdev->flags) ||
5428 	    rdev->recovery_offset < end_sector) {
5429 		rdev = rcu_dereference(conf->disks[dd_idx].rdev);
5430 		if (rdev &&
5431 		    (test_bit(Faulty, &rdev->flags) ||
5432 		    !(test_bit(In_sync, &rdev->flags) ||
5433 		      rdev->recovery_offset >= end_sector)))
5434 			rdev = NULL;
5435 	}
5436 
5437 	if (r5c_big_stripe_cached(conf, align_bi->bi_iter.bi_sector)) {
5438 		rcu_read_unlock();
5439 		bio_put(align_bi);
5440 		return 0;
5441 	}
5442 
5443 	if (rdev) {
5444 		sector_t first_bad;
5445 		int bad_sectors;
5446 
5447 		atomic_inc(&rdev->nr_pending);
5448 		rcu_read_unlock();
5449 		raid_bio->bi_next = (void*)rdev;
5450 		bio_set_dev(align_bi, rdev->bdev);
5451 
5452 		if (is_badblock(rdev, align_bi->bi_iter.bi_sector,
5453 				bio_sectors(align_bi),
5454 				&first_bad, &bad_sectors)) {
5455 			bio_put(align_bi);
5456 			rdev_dec_pending(rdev, mddev);
5457 			return 0;
5458 		}
5459 
5460 		/* No reshape active, so we can trust rdev->data_offset */
5461 		align_bi->bi_iter.bi_sector += rdev->data_offset;
5462 
5463 		spin_lock_irq(&conf->device_lock);
5464 		wait_event_lock_irq(conf->wait_for_quiescent,
5465 				    conf->quiesce == 0,
5466 				    conf->device_lock);
5467 		atomic_inc(&conf->active_aligned_reads);
5468 		spin_unlock_irq(&conf->device_lock);
5469 
5470 		if (mddev->gendisk)
5471 			trace_block_bio_remap(align_bi->bi_disk->queue,
5472 					      align_bi, disk_devt(mddev->gendisk),
5473 					      raid_bio->bi_iter.bi_sector);
5474 		submit_bio_noacct(align_bi);
5475 		return 1;
5476 	} else {
5477 		rcu_read_unlock();
5478 		bio_put(align_bi);
5479 		return 0;
5480 	}
5481 }
5482 
5483 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
5484 {
5485 	struct bio *split;
5486 	sector_t sector = raid_bio->bi_iter.bi_sector;
5487 	unsigned chunk_sects = mddev->chunk_sectors;
5488 	unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
5489 
5490 	if (sectors < bio_sectors(raid_bio)) {
5491 		struct r5conf *conf = mddev->private;
5492 		split = bio_split(raid_bio, sectors, GFP_NOIO, &conf->bio_split);
5493 		bio_chain(split, raid_bio);
5494 		submit_bio_noacct(raid_bio);
5495 		raid_bio = split;
5496 	}
5497 
5498 	if (!raid5_read_one_chunk(mddev, raid_bio))
5499 		return raid_bio;
5500 
5501 	return NULL;
5502 }
5503 
5504 /* __get_priority_stripe - get the next stripe to process
5505  *
5506  * Full stripe writes are allowed to pass preread active stripes up until
5507  * the bypass_threshold is exceeded.  In general the bypass_count
5508  * increments when the handle_list is handled before the hold_list; however, it
5509  * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
5510  * stripe with in flight i/o.  The bypass_count will be reset when the
5511  * head of the hold_list has changed, i.e. the head was promoted to the
5512  * handle_list.
5513  */
5514 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
5515 {
5516 	struct stripe_head *sh, *tmp;
5517 	struct list_head *handle_list = NULL;
5518 	struct r5worker_group *wg;
5519 	bool second_try = !r5c_is_writeback(conf->log) &&
5520 		!r5l_log_disk_error(conf);
5521 	bool try_loprio = test_bit(R5C_LOG_TIGHT, &conf->cache_state) ||
5522 		r5l_log_disk_error(conf);
5523 
5524 again:
5525 	wg = NULL;
5526 	sh = NULL;
5527 	if (conf->worker_cnt_per_group == 0) {
5528 		handle_list = try_loprio ? &conf->loprio_list :
5529 					&conf->handle_list;
5530 	} else if (group != ANY_GROUP) {
5531 		handle_list = try_loprio ? &conf->worker_groups[group].loprio_list :
5532 				&conf->worker_groups[group].handle_list;
5533 		wg = &conf->worker_groups[group];
5534 	} else {
5535 		int i;
5536 		for (i = 0; i < conf->group_cnt; i++) {
5537 			handle_list = try_loprio ? &conf->worker_groups[i].loprio_list :
5538 				&conf->worker_groups[i].handle_list;
5539 			wg = &conf->worker_groups[i];
5540 			if (!list_empty(handle_list))
5541 				break;
5542 		}
5543 	}
5544 
5545 	pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
5546 		  __func__,
5547 		  list_empty(handle_list) ? "empty" : "busy",
5548 		  list_empty(&conf->hold_list) ? "empty" : "busy",
5549 		  atomic_read(&conf->pending_full_writes), conf->bypass_count);
5550 
5551 	if (!list_empty(handle_list)) {
5552 		sh = list_entry(handle_list->next, typeof(*sh), lru);
5553 
5554 		if (list_empty(&conf->hold_list))
5555 			conf->bypass_count = 0;
5556 		else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
5557 			if (conf->hold_list.next == conf->last_hold)
5558 				conf->bypass_count++;
5559 			else {
5560 				conf->last_hold = conf->hold_list.next;
5561 				conf->bypass_count -= conf->bypass_threshold;
5562 				if (conf->bypass_count < 0)
5563 					conf->bypass_count = 0;
5564 			}
5565 		}
5566 	} else if (!list_empty(&conf->hold_list) &&
5567 		   ((conf->bypass_threshold &&
5568 		     conf->bypass_count > conf->bypass_threshold) ||
5569 		    atomic_read(&conf->pending_full_writes) == 0)) {
5570 
5571 		list_for_each_entry(tmp, &conf->hold_list,  lru) {
5572 			if (conf->worker_cnt_per_group == 0 ||
5573 			    group == ANY_GROUP ||
5574 			    !cpu_online(tmp->cpu) ||
5575 			    cpu_to_group(tmp->cpu) == group) {
5576 				sh = tmp;
5577 				break;
5578 			}
5579 		}
5580 
5581 		if (sh) {
5582 			conf->bypass_count -= conf->bypass_threshold;
5583 			if (conf->bypass_count < 0)
5584 				conf->bypass_count = 0;
5585 		}
5586 		wg = NULL;
5587 	}
5588 
5589 	if (!sh) {
5590 		if (second_try)
5591 			return NULL;
5592 		second_try = true;
5593 		try_loprio = !try_loprio;
5594 		goto again;
5595 	}
5596 
5597 	if (wg) {
5598 		wg->stripes_cnt--;
5599 		sh->group = NULL;
5600 	}
5601 	list_del_init(&sh->lru);
5602 	BUG_ON(atomic_inc_return(&sh->count) != 1);
5603 	return sh;
5604 }
5605 
5606 struct raid5_plug_cb {
5607 	struct blk_plug_cb	cb;
5608 	struct list_head	list;
5609 	struct list_head	temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5610 };
5611 
5612 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5613 {
5614 	struct raid5_plug_cb *cb = container_of(
5615 		blk_cb, struct raid5_plug_cb, cb);
5616 	struct stripe_head *sh;
5617 	struct mddev *mddev = cb->cb.data;
5618 	struct r5conf *conf = mddev->private;
5619 	int cnt = 0;
5620 	int hash;
5621 
5622 	if (cb->list.next && !list_empty(&cb->list)) {
5623 		spin_lock_irq(&conf->device_lock);
5624 		while (!list_empty(&cb->list)) {
5625 			sh = list_first_entry(&cb->list, struct stripe_head, lru);
5626 			list_del_init(&sh->lru);
5627 			/*
5628 			 * avoid race release_stripe_plug() sees
5629 			 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5630 			 * is still in our list
5631 			 */
5632 			smp_mb__before_atomic();
5633 			clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5634 			/*
5635 			 * STRIPE_ON_RELEASE_LIST could be set here. In that
5636 			 * case, the count is always > 1 here
5637 			 */
5638 			hash = sh->hash_lock_index;
5639 			__release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5640 			cnt++;
5641 		}
5642 		spin_unlock_irq(&conf->device_lock);
5643 	}
5644 	release_inactive_stripe_list(conf, cb->temp_inactive_list,
5645 				     NR_STRIPE_HASH_LOCKS);
5646 	if (mddev->queue)
5647 		trace_block_unplug(mddev->queue, cnt, !from_schedule);
5648 	kfree(cb);
5649 }
5650 
5651 static void release_stripe_plug(struct mddev *mddev,
5652 				struct stripe_head *sh)
5653 {
5654 	struct blk_plug_cb *blk_cb = blk_check_plugged(
5655 		raid5_unplug, mddev,
5656 		sizeof(struct raid5_plug_cb));
5657 	struct raid5_plug_cb *cb;
5658 
5659 	if (!blk_cb) {
5660 		raid5_release_stripe(sh);
5661 		return;
5662 	}
5663 
5664 	cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5665 
5666 	if (cb->list.next == NULL) {
5667 		int i;
5668 		INIT_LIST_HEAD(&cb->list);
5669 		for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5670 			INIT_LIST_HEAD(cb->temp_inactive_list + i);
5671 	}
5672 
5673 	if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5674 		list_add_tail(&sh->lru, &cb->list);
5675 	else
5676 		raid5_release_stripe(sh);
5677 }
5678 
5679 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5680 {
5681 	struct r5conf *conf = mddev->private;
5682 	sector_t logical_sector, last_sector;
5683 	struct stripe_head *sh;
5684 	int stripe_sectors;
5685 
5686 	if (mddev->reshape_position != MaxSector)
5687 		/* Skip discard while reshape is happening */
5688 		return;
5689 
5690 	logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5691 	last_sector = bio_end_sector(bi);
5692 
5693 	bi->bi_next = NULL;
5694 
5695 	stripe_sectors = conf->chunk_sectors *
5696 		(conf->raid_disks - conf->max_degraded);
5697 	logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5698 					       stripe_sectors);
5699 	sector_div(last_sector, stripe_sectors);
5700 
5701 	logical_sector *= conf->chunk_sectors;
5702 	last_sector *= conf->chunk_sectors;
5703 
5704 	for (; logical_sector < last_sector;
5705 	     logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5706 		DEFINE_WAIT(w);
5707 		int d;
5708 	again:
5709 		sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5710 		prepare_to_wait(&conf->wait_for_overlap, &w,
5711 				TASK_UNINTERRUPTIBLE);
5712 		set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5713 		if (test_bit(STRIPE_SYNCING, &sh->state)) {
5714 			raid5_release_stripe(sh);
5715 			schedule();
5716 			goto again;
5717 		}
5718 		clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5719 		spin_lock_irq(&sh->stripe_lock);
5720 		for (d = 0; d < conf->raid_disks; d++) {
5721 			if (d == sh->pd_idx || d == sh->qd_idx)
5722 				continue;
5723 			if (sh->dev[d].towrite || sh->dev[d].toread) {
5724 				set_bit(R5_Overlap, &sh->dev[d].flags);
5725 				spin_unlock_irq(&sh->stripe_lock);
5726 				raid5_release_stripe(sh);
5727 				schedule();
5728 				goto again;
5729 			}
5730 		}
5731 		set_bit(STRIPE_DISCARD, &sh->state);
5732 		finish_wait(&conf->wait_for_overlap, &w);
5733 		sh->overwrite_disks = 0;
5734 		for (d = 0; d < conf->raid_disks; d++) {
5735 			if (d == sh->pd_idx || d == sh->qd_idx)
5736 				continue;
5737 			sh->dev[d].towrite = bi;
5738 			set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5739 			bio_inc_remaining(bi);
5740 			md_write_inc(mddev, bi);
5741 			sh->overwrite_disks++;
5742 		}
5743 		spin_unlock_irq(&sh->stripe_lock);
5744 		if (conf->mddev->bitmap) {
5745 			for (d = 0;
5746 			     d < conf->raid_disks - conf->max_degraded;
5747 			     d++)
5748 				md_bitmap_startwrite(mddev->bitmap,
5749 						     sh->sector,
5750 						     RAID5_STRIPE_SECTORS(conf),
5751 						     0);
5752 			sh->bm_seq = conf->seq_flush + 1;
5753 			set_bit(STRIPE_BIT_DELAY, &sh->state);
5754 		}
5755 
5756 		set_bit(STRIPE_HANDLE, &sh->state);
5757 		clear_bit(STRIPE_DELAYED, &sh->state);
5758 		if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5759 			atomic_inc(&conf->preread_active_stripes);
5760 		release_stripe_plug(mddev, sh);
5761 	}
5762 
5763 	bio_endio(bi);
5764 }
5765 
5766 static bool raid5_make_request(struct mddev *mddev, struct bio * bi)
5767 {
5768 	struct r5conf *conf = mddev->private;
5769 	int dd_idx;
5770 	sector_t new_sector;
5771 	sector_t logical_sector, last_sector;
5772 	struct stripe_head *sh;
5773 	const int rw = bio_data_dir(bi);
5774 	DEFINE_WAIT(w);
5775 	bool do_prepare;
5776 	bool do_flush = false;
5777 
5778 	if (unlikely(bi->bi_opf & REQ_PREFLUSH)) {
5779 		int ret = log_handle_flush_request(conf, bi);
5780 
5781 		if (ret == 0)
5782 			return true;
5783 		if (ret == -ENODEV) {
5784 			if (md_flush_request(mddev, bi))
5785 				return true;
5786 		}
5787 		/* ret == -EAGAIN, fallback */
5788 		/*
5789 		 * if r5l_handle_flush_request() didn't clear REQ_PREFLUSH,
5790 		 * we need to flush journal device
5791 		 */
5792 		do_flush = bi->bi_opf & REQ_PREFLUSH;
5793 	}
5794 
5795 	if (!md_write_start(mddev, bi))
5796 		return false;
5797 	/*
5798 	 * If array is degraded, better not do chunk aligned read because
5799 	 * later we might have to read it again in order to reconstruct
5800 	 * data on failed drives.
5801 	 */
5802 	if (rw == READ && mddev->degraded == 0 &&
5803 	    mddev->reshape_position == MaxSector) {
5804 		bi = chunk_aligned_read(mddev, bi);
5805 		if (!bi)
5806 			return true;
5807 	}
5808 
5809 	if (unlikely(bio_op(bi) == REQ_OP_DISCARD)) {
5810 		make_discard_request(mddev, bi);
5811 		md_write_end(mddev);
5812 		return true;
5813 	}
5814 
5815 	logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5816 	last_sector = bio_end_sector(bi);
5817 	bi->bi_next = NULL;
5818 
5819 	prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5820 	for (; logical_sector < last_sector; logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5821 		int previous;
5822 		int seq;
5823 
5824 		do_prepare = false;
5825 	retry:
5826 		seq = read_seqcount_begin(&conf->gen_lock);
5827 		previous = 0;
5828 		if (do_prepare)
5829 			prepare_to_wait(&conf->wait_for_overlap, &w,
5830 				TASK_UNINTERRUPTIBLE);
5831 		if (unlikely(conf->reshape_progress != MaxSector)) {
5832 			/* spinlock is needed as reshape_progress may be
5833 			 * 64bit on a 32bit platform, and so it might be
5834 			 * possible to see a half-updated value
5835 			 * Of course reshape_progress could change after
5836 			 * the lock is dropped, so once we get a reference
5837 			 * to the stripe that we think it is, we will have
5838 			 * to check again.
5839 			 */
5840 			spin_lock_irq(&conf->device_lock);
5841 			if (mddev->reshape_backwards
5842 			    ? logical_sector < conf->reshape_progress
5843 			    : logical_sector >= conf->reshape_progress) {
5844 				previous = 1;
5845 			} else {
5846 				if (mddev->reshape_backwards
5847 				    ? logical_sector < conf->reshape_safe
5848 				    : logical_sector >= conf->reshape_safe) {
5849 					spin_unlock_irq(&conf->device_lock);
5850 					schedule();
5851 					do_prepare = true;
5852 					goto retry;
5853 				}
5854 			}
5855 			spin_unlock_irq(&conf->device_lock);
5856 		}
5857 
5858 		new_sector = raid5_compute_sector(conf, logical_sector,
5859 						  previous,
5860 						  &dd_idx, NULL);
5861 		pr_debug("raid456: raid5_make_request, sector %llu logical %llu\n",
5862 			(unsigned long long)new_sector,
5863 			(unsigned long long)logical_sector);
5864 
5865 		sh = raid5_get_active_stripe(conf, new_sector, previous,
5866 				       (bi->bi_opf & REQ_RAHEAD), 0);
5867 		if (sh) {
5868 			if (unlikely(previous)) {
5869 				/* expansion might have moved on while waiting for a
5870 				 * stripe, so we must do the range check again.
5871 				 * Expansion could still move past after this
5872 				 * test, but as we are holding a reference to
5873 				 * 'sh', we know that if that happens,
5874 				 *  STRIPE_EXPANDING will get set and the expansion
5875 				 * won't proceed until we finish with the stripe.
5876 				 */
5877 				int must_retry = 0;
5878 				spin_lock_irq(&conf->device_lock);
5879 				if (mddev->reshape_backwards
5880 				    ? logical_sector >= conf->reshape_progress
5881 				    : logical_sector < conf->reshape_progress)
5882 					/* mismatch, need to try again */
5883 					must_retry = 1;
5884 				spin_unlock_irq(&conf->device_lock);
5885 				if (must_retry) {
5886 					raid5_release_stripe(sh);
5887 					schedule();
5888 					do_prepare = true;
5889 					goto retry;
5890 				}
5891 			}
5892 			if (read_seqcount_retry(&conf->gen_lock, seq)) {
5893 				/* Might have got the wrong stripe_head
5894 				 * by accident
5895 				 */
5896 				raid5_release_stripe(sh);
5897 				goto retry;
5898 			}
5899 
5900 			if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5901 			    !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5902 				/* Stripe is busy expanding or
5903 				 * add failed due to overlap.  Flush everything
5904 				 * and wait a while
5905 				 */
5906 				md_wakeup_thread(mddev->thread);
5907 				raid5_release_stripe(sh);
5908 				schedule();
5909 				do_prepare = true;
5910 				goto retry;
5911 			}
5912 			if (do_flush) {
5913 				set_bit(STRIPE_R5C_PREFLUSH, &sh->state);
5914 				/* we only need flush for one stripe */
5915 				do_flush = false;
5916 			}
5917 
5918 			set_bit(STRIPE_HANDLE, &sh->state);
5919 			clear_bit(STRIPE_DELAYED, &sh->state);
5920 			if ((!sh->batch_head || sh == sh->batch_head) &&
5921 			    (bi->bi_opf & REQ_SYNC) &&
5922 			    !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5923 				atomic_inc(&conf->preread_active_stripes);
5924 			release_stripe_plug(mddev, sh);
5925 		} else {
5926 			/* cannot get stripe for read-ahead, just give-up */
5927 			bi->bi_status = BLK_STS_IOERR;
5928 			break;
5929 		}
5930 	}
5931 	finish_wait(&conf->wait_for_overlap, &w);
5932 
5933 	if (rw == WRITE)
5934 		md_write_end(mddev);
5935 	bio_endio(bi);
5936 	return true;
5937 }
5938 
5939 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5940 
5941 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5942 {
5943 	/* reshaping is quite different to recovery/resync so it is
5944 	 * handled quite separately ... here.
5945 	 *
5946 	 * On each call to sync_request, we gather one chunk worth of
5947 	 * destination stripes and flag them as expanding.
5948 	 * Then we find all the source stripes and request reads.
5949 	 * As the reads complete, handle_stripe will copy the data
5950 	 * into the destination stripe and release that stripe.
5951 	 */
5952 	struct r5conf *conf = mddev->private;
5953 	struct stripe_head *sh;
5954 	struct md_rdev *rdev;
5955 	sector_t first_sector, last_sector;
5956 	int raid_disks = conf->previous_raid_disks;
5957 	int data_disks = raid_disks - conf->max_degraded;
5958 	int new_data_disks = conf->raid_disks - conf->max_degraded;
5959 	int i;
5960 	int dd_idx;
5961 	sector_t writepos, readpos, safepos;
5962 	sector_t stripe_addr;
5963 	int reshape_sectors;
5964 	struct list_head stripes;
5965 	sector_t retn;
5966 
5967 	if (sector_nr == 0) {
5968 		/* If restarting in the middle, skip the initial sectors */
5969 		if (mddev->reshape_backwards &&
5970 		    conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5971 			sector_nr = raid5_size(mddev, 0, 0)
5972 				- conf->reshape_progress;
5973 		} else if (mddev->reshape_backwards &&
5974 			   conf->reshape_progress == MaxSector) {
5975 			/* shouldn't happen, but just in case, finish up.*/
5976 			sector_nr = MaxSector;
5977 		} else if (!mddev->reshape_backwards &&
5978 			   conf->reshape_progress > 0)
5979 			sector_nr = conf->reshape_progress;
5980 		sector_div(sector_nr, new_data_disks);
5981 		if (sector_nr) {
5982 			mddev->curr_resync_completed = sector_nr;
5983 			sysfs_notify_dirent_safe(mddev->sysfs_completed);
5984 			*skipped = 1;
5985 			retn = sector_nr;
5986 			goto finish;
5987 		}
5988 	}
5989 
5990 	/* We need to process a full chunk at a time.
5991 	 * If old and new chunk sizes differ, we need to process the
5992 	 * largest of these
5993 	 */
5994 
5995 	reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5996 
5997 	/* We update the metadata at least every 10 seconds, or when
5998 	 * the data about to be copied would over-write the source of
5999 	 * the data at the front of the range.  i.e. one new_stripe
6000 	 * along from reshape_progress new_maps to after where
6001 	 * reshape_safe old_maps to
6002 	 */
6003 	writepos = conf->reshape_progress;
6004 	sector_div(writepos, new_data_disks);
6005 	readpos = conf->reshape_progress;
6006 	sector_div(readpos, data_disks);
6007 	safepos = conf->reshape_safe;
6008 	sector_div(safepos, data_disks);
6009 	if (mddev->reshape_backwards) {
6010 		BUG_ON(writepos < reshape_sectors);
6011 		writepos -= reshape_sectors;
6012 		readpos += reshape_sectors;
6013 		safepos += reshape_sectors;
6014 	} else {
6015 		writepos += reshape_sectors;
6016 		/* readpos and safepos are worst-case calculations.
6017 		 * A negative number is overly pessimistic, and causes
6018 		 * obvious problems for unsigned storage.  So clip to 0.
6019 		 */
6020 		readpos -= min_t(sector_t, reshape_sectors, readpos);
6021 		safepos -= min_t(sector_t, reshape_sectors, safepos);
6022 	}
6023 
6024 	/* Having calculated the 'writepos' possibly use it
6025 	 * to set 'stripe_addr' which is where we will write to.
6026 	 */
6027 	if (mddev->reshape_backwards) {
6028 		BUG_ON(conf->reshape_progress == 0);
6029 		stripe_addr = writepos;
6030 		BUG_ON((mddev->dev_sectors &
6031 			~((sector_t)reshape_sectors - 1))
6032 		       - reshape_sectors - stripe_addr
6033 		       != sector_nr);
6034 	} else {
6035 		BUG_ON(writepos != sector_nr + reshape_sectors);
6036 		stripe_addr = sector_nr;
6037 	}
6038 
6039 	/* 'writepos' is the most advanced device address we might write.
6040 	 * 'readpos' is the least advanced device address we might read.
6041 	 * 'safepos' is the least address recorded in the metadata as having
6042 	 *     been reshaped.
6043 	 * If there is a min_offset_diff, these are adjusted either by
6044 	 * increasing the safepos/readpos if diff is negative, or
6045 	 * increasing writepos if diff is positive.
6046 	 * If 'readpos' is then behind 'writepos', there is no way that we can
6047 	 * ensure safety in the face of a crash - that must be done by userspace
6048 	 * making a backup of the data.  So in that case there is no particular
6049 	 * rush to update metadata.
6050 	 * Otherwise if 'safepos' is behind 'writepos', then we really need to
6051 	 * update the metadata to advance 'safepos' to match 'readpos' so that
6052 	 * we can be safe in the event of a crash.
6053 	 * So we insist on updating metadata if safepos is behind writepos and
6054 	 * readpos is beyond writepos.
6055 	 * In any case, update the metadata every 10 seconds.
6056 	 * Maybe that number should be configurable, but I'm not sure it is
6057 	 * worth it.... maybe it could be a multiple of safemode_delay???
6058 	 */
6059 	if (conf->min_offset_diff < 0) {
6060 		safepos += -conf->min_offset_diff;
6061 		readpos += -conf->min_offset_diff;
6062 	} else
6063 		writepos += conf->min_offset_diff;
6064 
6065 	if ((mddev->reshape_backwards
6066 	     ? (safepos > writepos && readpos < writepos)
6067 	     : (safepos < writepos && readpos > writepos)) ||
6068 	    time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
6069 		/* Cannot proceed until we've updated the superblock... */
6070 		wait_event(conf->wait_for_overlap,
6071 			   atomic_read(&conf->reshape_stripes)==0
6072 			   || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6073 		if (atomic_read(&conf->reshape_stripes) != 0)
6074 			return 0;
6075 		mddev->reshape_position = conf->reshape_progress;
6076 		mddev->curr_resync_completed = sector_nr;
6077 		if (!mddev->reshape_backwards)
6078 			/* Can update recovery_offset */
6079 			rdev_for_each(rdev, mddev)
6080 				if (rdev->raid_disk >= 0 &&
6081 				    !test_bit(Journal, &rdev->flags) &&
6082 				    !test_bit(In_sync, &rdev->flags) &&
6083 				    rdev->recovery_offset < sector_nr)
6084 					rdev->recovery_offset = sector_nr;
6085 
6086 		conf->reshape_checkpoint = jiffies;
6087 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6088 		md_wakeup_thread(mddev->thread);
6089 		wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
6090 			   test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6091 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6092 			return 0;
6093 		spin_lock_irq(&conf->device_lock);
6094 		conf->reshape_safe = mddev->reshape_position;
6095 		spin_unlock_irq(&conf->device_lock);
6096 		wake_up(&conf->wait_for_overlap);
6097 		sysfs_notify_dirent_safe(mddev->sysfs_completed);
6098 	}
6099 
6100 	INIT_LIST_HEAD(&stripes);
6101 	for (i = 0; i < reshape_sectors; i += RAID5_STRIPE_SECTORS(conf)) {
6102 		int j;
6103 		int skipped_disk = 0;
6104 		sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
6105 		set_bit(STRIPE_EXPANDING, &sh->state);
6106 		atomic_inc(&conf->reshape_stripes);
6107 		/* If any of this stripe is beyond the end of the old
6108 		 * array, then we need to zero those blocks
6109 		 */
6110 		for (j=sh->disks; j--;) {
6111 			sector_t s;
6112 			if (j == sh->pd_idx)
6113 				continue;
6114 			if (conf->level == 6 &&
6115 			    j == sh->qd_idx)
6116 				continue;
6117 			s = raid5_compute_blocknr(sh, j, 0);
6118 			if (s < raid5_size(mddev, 0, 0)) {
6119 				skipped_disk = 1;
6120 				continue;
6121 			}
6122 			memset(page_address(sh->dev[j].page), 0, RAID5_STRIPE_SIZE(conf));
6123 			set_bit(R5_Expanded, &sh->dev[j].flags);
6124 			set_bit(R5_UPTODATE, &sh->dev[j].flags);
6125 		}
6126 		if (!skipped_disk) {
6127 			set_bit(STRIPE_EXPAND_READY, &sh->state);
6128 			set_bit(STRIPE_HANDLE, &sh->state);
6129 		}
6130 		list_add(&sh->lru, &stripes);
6131 	}
6132 	spin_lock_irq(&conf->device_lock);
6133 	if (mddev->reshape_backwards)
6134 		conf->reshape_progress -= reshape_sectors * new_data_disks;
6135 	else
6136 		conf->reshape_progress += reshape_sectors * new_data_disks;
6137 	spin_unlock_irq(&conf->device_lock);
6138 	/* Ok, those stripe are ready. We can start scheduling
6139 	 * reads on the source stripes.
6140 	 * The source stripes are determined by mapping the first and last
6141 	 * block on the destination stripes.
6142 	 */
6143 	first_sector =
6144 		raid5_compute_sector(conf, stripe_addr*(new_data_disks),
6145 				     1, &dd_idx, NULL);
6146 	last_sector =
6147 		raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
6148 					    * new_data_disks - 1),
6149 				     1, &dd_idx, NULL);
6150 	if (last_sector >= mddev->dev_sectors)
6151 		last_sector = mddev->dev_sectors - 1;
6152 	while (first_sector <= last_sector) {
6153 		sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
6154 		set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
6155 		set_bit(STRIPE_HANDLE, &sh->state);
6156 		raid5_release_stripe(sh);
6157 		first_sector += RAID5_STRIPE_SECTORS(conf);
6158 	}
6159 	/* Now that the sources are clearly marked, we can release
6160 	 * the destination stripes
6161 	 */
6162 	while (!list_empty(&stripes)) {
6163 		sh = list_entry(stripes.next, struct stripe_head, lru);
6164 		list_del_init(&sh->lru);
6165 		raid5_release_stripe(sh);
6166 	}
6167 	/* If this takes us to the resync_max point where we have to pause,
6168 	 * then we need to write out the superblock.
6169 	 */
6170 	sector_nr += reshape_sectors;
6171 	retn = reshape_sectors;
6172 finish:
6173 	if (mddev->curr_resync_completed > mddev->resync_max ||
6174 	    (sector_nr - mddev->curr_resync_completed) * 2
6175 	    >= mddev->resync_max - mddev->curr_resync_completed) {
6176 		/* Cannot proceed until we've updated the superblock... */
6177 		wait_event(conf->wait_for_overlap,
6178 			   atomic_read(&conf->reshape_stripes) == 0
6179 			   || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6180 		if (atomic_read(&conf->reshape_stripes) != 0)
6181 			goto ret;
6182 		mddev->reshape_position = conf->reshape_progress;
6183 		mddev->curr_resync_completed = sector_nr;
6184 		if (!mddev->reshape_backwards)
6185 			/* Can update recovery_offset */
6186 			rdev_for_each(rdev, mddev)
6187 				if (rdev->raid_disk >= 0 &&
6188 				    !test_bit(Journal, &rdev->flags) &&
6189 				    !test_bit(In_sync, &rdev->flags) &&
6190 				    rdev->recovery_offset < sector_nr)
6191 					rdev->recovery_offset = sector_nr;
6192 		conf->reshape_checkpoint = jiffies;
6193 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6194 		md_wakeup_thread(mddev->thread);
6195 		wait_event(mddev->sb_wait,
6196 			   !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)
6197 			   || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6198 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6199 			goto ret;
6200 		spin_lock_irq(&conf->device_lock);
6201 		conf->reshape_safe = mddev->reshape_position;
6202 		spin_unlock_irq(&conf->device_lock);
6203 		wake_up(&conf->wait_for_overlap);
6204 		sysfs_notify_dirent_safe(mddev->sysfs_completed);
6205 	}
6206 ret:
6207 	return retn;
6208 }
6209 
6210 static inline sector_t raid5_sync_request(struct mddev *mddev, sector_t sector_nr,
6211 					  int *skipped)
6212 {
6213 	struct r5conf *conf = mddev->private;
6214 	struct stripe_head *sh;
6215 	sector_t max_sector = mddev->dev_sectors;
6216 	sector_t sync_blocks;
6217 	int still_degraded = 0;
6218 	int i;
6219 
6220 	if (sector_nr >= max_sector) {
6221 		/* just being told to finish up .. nothing much to do */
6222 
6223 		if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
6224 			end_reshape(conf);
6225 			return 0;
6226 		}
6227 
6228 		if (mddev->curr_resync < max_sector) /* aborted */
6229 			md_bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
6230 					   &sync_blocks, 1);
6231 		else /* completed sync */
6232 			conf->fullsync = 0;
6233 		md_bitmap_close_sync(mddev->bitmap);
6234 
6235 		return 0;
6236 	}
6237 
6238 	/* Allow raid5_quiesce to complete */
6239 	wait_event(conf->wait_for_overlap, conf->quiesce != 2);
6240 
6241 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6242 		return reshape_request(mddev, sector_nr, skipped);
6243 
6244 	/* No need to check resync_max as we never do more than one
6245 	 * stripe, and as resync_max will always be on a chunk boundary,
6246 	 * if the check in md_do_sync didn't fire, there is no chance
6247 	 * of overstepping resync_max here
6248 	 */
6249 
6250 	/* if there is too many failed drives and we are trying
6251 	 * to resync, then assert that we are finished, because there is
6252 	 * nothing we can do.
6253 	 */
6254 	if (mddev->degraded >= conf->max_degraded &&
6255 	    test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6256 		sector_t rv = mddev->dev_sectors - sector_nr;
6257 		*skipped = 1;
6258 		return rv;
6259 	}
6260 	if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
6261 	    !conf->fullsync &&
6262 	    !md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
6263 	    sync_blocks >= RAID5_STRIPE_SECTORS(conf)) {
6264 		/* we can skip this block, and probably more */
6265 		do_div(sync_blocks, RAID5_STRIPE_SECTORS(conf));
6266 		*skipped = 1;
6267 		/* keep things rounded to whole stripes */
6268 		return sync_blocks * RAID5_STRIPE_SECTORS(conf);
6269 	}
6270 
6271 	md_bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
6272 
6273 	sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
6274 	if (sh == NULL) {
6275 		sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
6276 		/* make sure we don't swamp the stripe cache if someone else
6277 		 * is trying to get access
6278 		 */
6279 		schedule_timeout_uninterruptible(1);
6280 	}
6281 	/* Need to check if array will still be degraded after recovery/resync
6282 	 * Note in case of > 1 drive failures it's possible we're rebuilding
6283 	 * one drive while leaving another faulty drive in array.
6284 	 */
6285 	rcu_read_lock();
6286 	for (i = 0; i < conf->raid_disks; i++) {
6287 		struct md_rdev *rdev = READ_ONCE(conf->disks[i].rdev);
6288 
6289 		if (rdev == NULL || test_bit(Faulty, &rdev->flags))
6290 			still_degraded = 1;
6291 	}
6292 	rcu_read_unlock();
6293 
6294 	md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
6295 
6296 	set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
6297 	set_bit(STRIPE_HANDLE, &sh->state);
6298 
6299 	raid5_release_stripe(sh);
6300 
6301 	return RAID5_STRIPE_SECTORS(conf);
6302 }
6303 
6304 static int  retry_aligned_read(struct r5conf *conf, struct bio *raid_bio,
6305 			       unsigned int offset)
6306 {
6307 	/* We may not be able to submit a whole bio at once as there
6308 	 * may not be enough stripe_heads available.
6309 	 * We cannot pre-allocate enough stripe_heads as we may need
6310 	 * more than exist in the cache (if we allow ever large chunks).
6311 	 * So we do one stripe head at a time and record in
6312 	 * ->bi_hw_segments how many have been done.
6313 	 *
6314 	 * We *know* that this entire raid_bio is in one chunk, so
6315 	 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
6316 	 */
6317 	struct stripe_head *sh;
6318 	int dd_idx;
6319 	sector_t sector, logical_sector, last_sector;
6320 	int scnt = 0;
6321 	int handled = 0;
6322 
6323 	logical_sector = raid_bio->bi_iter.bi_sector &
6324 		~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
6325 	sector = raid5_compute_sector(conf, logical_sector,
6326 				      0, &dd_idx, NULL);
6327 	last_sector = bio_end_sector(raid_bio);
6328 
6329 	for (; logical_sector < last_sector;
6330 	     logical_sector += RAID5_STRIPE_SECTORS(conf),
6331 		     sector += RAID5_STRIPE_SECTORS(conf),
6332 		     scnt++) {
6333 
6334 		if (scnt < offset)
6335 			/* already done this stripe */
6336 			continue;
6337 
6338 		sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
6339 
6340 		if (!sh) {
6341 			/* failed to get a stripe - must wait */
6342 			conf->retry_read_aligned = raid_bio;
6343 			conf->retry_read_offset = scnt;
6344 			return handled;
6345 		}
6346 
6347 		if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
6348 			raid5_release_stripe(sh);
6349 			conf->retry_read_aligned = raid_bio;
6350 			conf->retry_read_offset = scnt;
6351 			return handled;
6352 		}
6353 
6354 		set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
6355 		handle_stripe(sh);
6356 		raid5_release_stripe(sh);
6357 		handled++;
6358 	}
6359 
6360 	bio_endio(raid_bio);
6361 
6362 	if (atomic_dec_and_test(&conf->active_aligned_reads))
6363 		wake_up(&conf->wait_for_quiescent);
6364 	return handled;
6365 }
6366 
6367 static int handle_active_stripes(struct r5conf *conf, int group,
6368 				 struct r5worker *worker,
6369 				 struct list_head *temp_inactive_list)
6370 		__releases(&conf->device_lock)
6371 		__acquires(&conf->device_lock)
6372 {
6373 	struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
6374 	int i, batch_size = 0, hash;
6375 	bool release_inactive = false;
6376 
6377 	while (batch_size < MAX_STRIPE_BATCH &&
6378 			(sh = __get_priority_stripe(conf, group)) != NULL)
6379 		batch[batch_size++] = sh;
6380 
6381 	if (batch_size == 0) {
6382 		for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6383 			if (!list_empty(temp_inactive_list + i))
6384 				break;
6385 		if (i == NR_STRIPE_HASH_LOCKS) {
6386 			spin_unlock_irq(&conf->device_lock);
6387 			log_flush_stripe_to_raid(conf);
6388 			spin_lock_irq(&conf->device_lock);
6389 			return batch_size;
6390 		}
6391 		release_inactive = true;
6392 	}
6393 	spin_unlock_irq(&conf->device_lock);
6394 
6395 	release_inactive_stripe_list(conf, temp_inactive_list,
6396 				     NR_STRIPE_HASH_LOCKS);
6397 
6398 	r5l_flush_stripe_to_raid(conf->log);
6399 	if (release_inactive) {
6400 		spin_lock_irq(&conf->device_lock);
6401 		return 0;
6402 	}
6403 
6404 	for (i = 0; i < batch_size; i++)
6405 		handle_stripe(batch[i]);
6406 	log_write_stripe_run(conf);
6407 
6408 	cond_resched();
6409 
6410 	spin_lock_irq(&conf->device_lock);
6411 	for (i = 0; i < batch_size; i++) {
6412 		hash = batch[i]->hash_lock_index;
6413 		__release_stripe(conf, batch[i], &temp_inactive_list[hash]);
6414 	}
6415 	return batch_size;
6416 }
6417 
6418 static void raid5_do_work(struct work_struct *work)
6419 {
6420 	struct r5worker *worker = container_of(work, struct r5worker, work);
6421 	struct r5worker_group *group = worker->group;
6422 	struct r5conf *conf = group->conf;
6423 	struct mddev *mddev = conf->mddev;
6424 	int group_id = group - conf->worker_groups;
6425 	int handled;
6426 	struct blk_plug plug;
6427 
6428 	pr_debug("+++ raid5worker active\n");
6429 
6430 	blk_start_plug(&plug);
6431 	handled = 0;
6432 	spin_lock_irq(&conf->device_lock);
6433 	while (1) {
6434 		int batch_size, released;
6435 
6436 		released = release_stripe_list(conf, worker->temp_inactive_list);
6437 
6438 		batch_size = handle_active_stripes(conf, group_id, worker,
6439 						   worker->temp_inactive_list);
6440 		worker->working = false;
6441 		if (!batch_size && !released)
6442 			break;
6443 		handled += batch_size;
6444 		wait_event_lock_irq(mddev->sb_wait,
6445 			!test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6446 			conf->device_lock);
6447 	}
6448 	pr_debug("%d stripes handled\n", handled);
6449 
6450 	spin_unlock_irq(&conf->device_lock);
6451 
6452 	flush_deferred_bios(conf);
6453 
6454 	r5l_flush_stripe_to_raid(conf->log);
6455 
6456 	async_tx_issue_pending_all();
6457 	blk_finish_plug(&plug);
6458 
6459 	pr_debug("--- raid5worker inactive\n");
6460 }
6461 
6462 /*
6463  * This is our raid5 kernel thread.
6464  *
6465  * We scan the hash table for stripes which can be handled now.
6466  * During the scan, completed stripes are saved for us by the interrupt
6467  * handler, so that they will not have to wait for our next wakeup.
6468  */
6469 static void raid5d(struct md_thread *thread)
6470 {
6471 	struct mddev *mddev = thread->mddev;
6472 	struct r5conf *conf = mddev->private;
6473 	int handled;
6474 	struct blk_plug plug;
6475 
6476 	pr_debug("+++ raid5d active\n");
6477 
6478 	md_check_recovery(mddev);
6479 
6480 	blk_start_plug(&plug);
6481 	handled = 0;
6482 	spin_lock_irq(&conf->device_lock);
6483 	while (1) {
6484 		struct bio *bio;
6485 		int batch_size, released;
6486 		unsigned int offset;
6487 
6488 		released = release_stripe_list(conf, conf->temp_inactive_list);
6489 		if (released)
6490 			clear_bit(R5_DID_ALLOC, &conf->cache_state);
6491 
6492 		if (
6493 		    !list_empty(&conf->bitmap_list)) {
6494 			/* Now is a good time to flush some bitmap updates */
6495 			conf->seq_flush++;
6496 			spin_unlock_irq(&conf->device_lock);
6497 			md_bitmap_unplug(mddev->bitmap);
6498 			spin_lock_irq(&conf->device_lock);
6499 			conf->seq_write = conf->seq_flush;
6500 			activate_bit_delay(conf, conf->temp_inactive_list);
6501 		}
6502 		raid5_activate_delayed(conf);
6503 
6504 		while ((bio = remove_bio_from_retry(conf, &offset))) {
6505 			int ok;
6506 			spin_unlock_irq(&conf->device_lock);
6507 			ok = retry_aligned_read(conf, bio, offset);
6508 			spin_lock_irq(&conf->device_lock);
6509 			if (!ok)
6510 				break;
6511 			handled++;
6512 		}
6513 
6514 		batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
6515 						   conf->temp_inactive_list);
6516 		if (!batch_size && !released)
6517 			break;
6518 		handled += batch_size;
6519 
6520 		if (mddev->sb_flags & ~(1 << MD_SB_CHANGE_PENDING)) {
6521 			spin_unlock_irq(&conf->device_lock);
6522 			md_check_recovery(mddev);
6523 			spin_lock_irq(&conf->device_lock);
6524 		}
6525 	}
6526 	pr_debug("%d stripes handled\n", handled);
6527 
6528 	spin_unlock_irq(&conf->device_lock);
6529 	if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
6530 	    mutex_trylock(&conf->cache_size_mutex)) {
6531 		grow_one_stripe(conf, __GFP_NOWARN);
6532 		/* Set flag even if allocation failed.  This helps
6533 		 * slow down allocation requests when mem is short
6534 		 */
6535 		set_bit(R5_DID_ALLOC, &conf->cache_state);
6536 		mutex_unlock(&conf->cache_size_mutex);
6537 	}
6538 
6539 	flush_deferred_bios(conf);
6540 
6541 	r5l_flush_stripe_to_raid(conf->log);
6542 
6543 	async_tx_issue_pending_all();
6544 	blk_finish_plug(&plug);
6545 
6546 	pr_debug("--- raid5d inactive\n");
6547 }
6548 
6549 static ssize_t
6550 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
6551 {
6552 	struct r5conf *conf;
6553 	int ret = 0;
6554 	spin_lock(&mddev->lock);
6555 	conf = mddev->private;
6556 	if (conf)
6557 		ret = sprintf(page, "%d\n", conf->min_nr_stripes);
6558 	spin_unlock(&mddev->lock);
6559 	return ret;
6560 }
6561 
6562 int
6563 raid5_set_cache_size(struct mddev *mddev, int size)
6564 {
6565 	int result = 0;
6566 	struct r5conf *conf = mddev->private;
6567 
6568 	if (size <= 16 || size > 32768)
6569 		return -EINVAL;
6570 
6571 	conf->min_nr_stripes = size;
6572 	mutex_lock(&conf->cache_size_mutex);
6573 	while (size < conf->max_nr_stripes &&
6574 	       drop_one_stripe(conf))
6575 		;
6576 	mutex_unlock(&conf->cache_size_mutex);
6577 
6578 	md_allow_write(mddev);
6579 
6580 	mutex_lock(&conf->cache_size_mutex);
6581 	while (size > conf->max_nr_stripes)
6582 		if (!grow_one_stripe(conf, GFP_KERNEL)) {
6583 			conf->min_nr_stripes = conf->max_nr_stripes;
6584 			result = -ENOMEM;
6585 			break;
6586 		}
6587 	mutex_unlock(&conf->cache_size_mutex);
6588 
6589 	return result;
6590 }
6591 EXPORT_SYMBOL(raid5_set_cache_size);
6592 
6593 static ssize_t
6594 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6595 {
6596 	struct r5conf *conf;
6597 	unsigned long new;
6598 	int err;
6599 
6600 	if (len >= PAGE_SIZE)
6601 		return -EINVAL;
6602 	if (kstrtoul(page, 10, &new))
6603 		return -EINVAL;
6604 	err = mddev_lock(mddev);
6605 	if (err)
6606 		return err;
6607 	conf = mddev->private;
6608 	if (!conf)
6609 		err = -ENODEV;
6610 	else
6611 		err = raid5_set_cache_size(mddev, new);
6612 	mddev_unlock(mddev);
6613 
6614 	return err ?: len;
6615 }
6616 
6617 static struct md_sysfs_entry
6618 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6619 				raid5_show_stripe_cache_size,
6620 				raid5_store_stripe_cache_size);
6621 
6622 static ssize_t
6623 raid5_show_rmw_level(struct mddev  *mddev, char *page)
6624 {
6625 	struct r5conf *conf = mddev->private;
6626 	if (conf)
6627 		return sprintf(page, "%d\n", conf->rmw_level);
6628 	else
6629 		return 0;
6630 }
6631 
6632 static ssize_t
6633 raid5_store_rmw_level(struct mddev  *mddev, const char *page, size_t len)
6634 {
6635 	struct r5conf *conf = mddev->private;
6636 	unsigned long new;
6637 
6638 	if (!conf)
6639 		return -ENODEV;
6640 
6641 	if (len >= PAGE_SIZE)
6642 		return -EINVAL;
6643 
6644 	if (kstrtoul(page, 10, &new))
6645 		return -EINVAL;
6646 
6647 	if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6648 		return -EINVAL;
6649 
6650 	if (new != PARITY_DISABLE_RMW &&
6651 	    new != PARITY_ENABLE_RMW &&
6652 	    new != PARITY_PREFER_RMW)
6653 		return -EINVAL;
6654 
6655 	conf->rmw_level = new;
6656 	return len;
6657 }
6658 
6659 static struct md_sysfs_entry
6660 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6661 			 raid5_show_rmw_level,
6662 			 raid5_store_rmw_level);
6663 
6664 static ssize_t
6665 raid5_show_stripe_size(struct mddev  *mddev, char *page)
6666 {
6667 	struct r5conf *conf;
6668 	int ret = 0;
6669 
6670 	spin_lock(&mddev->lock);
6671 	conf = mddev->private;
6672 	if (conf)
6673 		ret = sprintf(page, "%lu\n", RAID5_STRIPE_SIZE(conf));
6674 	spin_unlock(&mddev->lock);
6675 	return ret;
6676 }
6677 
6678 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
6679 static ssize_t
6680 raid5_store_stripe_size(struct mddev  *mddev, const char *page, size_t len)
6681 {
6682 	struct r5conf *conf;
6683 	unsigned long new;
6684 	int err;
6685 	int size;
6686 
6687 	if (len >= PAGE_SIZE)
6688 		return -EINVAL;
6689 	if (kstrtoul(page, 10, &new))
6690 		return -EINVAL;
6691 
6692 	/*
6693 	 * The value should not be bigger than PAGE_SIZE. It requires to
6694 	 * be multiple of DEFAULT_STRIPE_SIZE and the value should be power
6695 	 * of two.
6696 	 */
6697 	if (new % DEFAULT_STRIPE_SIZE != 0 ||
6698 			new > PAGE_SIZE || new == 0 ||
6699 			new != roundup_pow_of_two(new))
6700 		return -EINVAL;
6701 
6702 	err = mddev_lock(mddev);
6703 	if (err)
6704 		return err;
6705 
6706 	conf = mddev->private;
6707 	if (!conf) {
6708 		err = -ENODEV;
6709 		goto out_unlock;
6710 	}
6711 
6712 	if (new == conf->stripe_size)
6713 		goto out_unlock;
6714 
6715 	pr_debug("md/raid: change stripe_size from %lu to %lu\n",
6716 			conf->stripe_size, new);
6717 
6718 	if (mddev->sync_thread ||
6719 		test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6720 		mddev->reshape_position != MaxSector ||
6721 		mddev->sysfs_active) {
6722 		err = -EBUSY;
6723 		goto out_unlock;
6724 	}
6725 
6726 	mddev_suspend(mddev);
6727 	mutex_lock(&conf->cache_size_mutex);
6728 	size = conf->max_nr_stripes;
6729 
6730 	shrink_stripes(conf);
6731 
6732 	conf->stripe_size = new;
6733 	conf->stripe_shift = ilog2(new) - 9;
6734 	conf->stripe_sectors = new >> 9;
6735 	if (grow_stripes(conf, size)) {
6736 		pr_warn("md/raid:%s: couldn't allocate buffers\n",
6737 				mdname(mddev));
6738 		err = -ENOMEM;
6739 	}
6740 	mutex_unlock(&conf->cache_size_mutex);
6741 	mddev_resume(mddev);
6742 
6743 out_unlock:
6744 	mddev_unlock(mddev);
6745 	return err ?: len;
6746 }
6747 
6748 static struct md_sysfs_entry
6749 raid5_stripe_size = __ATTR(stripe_size, 0644,
6750 			 raid5_show_stripe_size,
6751 			 raid5_store_stripe_size);
6752 #else
6753 static struct md_sysfs_entry
6754 raid5_stripe_size = __ATTR(stripe_size, 0444,
6755 			 raid5_show_stripe_size,
6756 			 NULL);
6757 #endif
6758 
6759 static ssize_t
6760 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6761 {
6762 	struct r5conf *conf;
6763 	int ret = 0;
6764 	spin_lock(&mddev->lock);
6765 	conf = mddev->private;
6766 	if (conf)
6767 		ret = sprintf(page, "%d\n", conf->bypass_threshold);
6768 	spin_unlock(&mddev->lock);
6769 	return ret;
6770 }
6771 
6772 static ssize_t
6773 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6774 {
6775 	struct r5conf *conf;
6776 	unsigned long new;
6777 	int err;
6778 
6779 	if (len >= PAGE_SIZE)
6780 		return -EINVAL;
6781 	if (kstrtoul(page, 10, &new))
6782 		return -EINVAL;
6783 
6784 	err = mddev_lock(mddev);
6785 	if (err)
6786 		return err;
6787 	conf = mddev->private;
6788 	if (!conf)
6789 		err = -ENODEV;
6790 	else if (new > conf->min_nr_stripes)
6791 		err = -EINVAL;
6792 	else
6793 		conf->bypass_threshold = new;
6794 	mddev_unlock(mddev);
6795 	return err ?: len;
6796 }
6797 
6798 static struct md_sysfs_entry
6799 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6800 					S_IRUGO | S_IWUSR,
6801 					raid5_show_preread_threshold,
6802 					raid5_store_preread_threshold);
6803 
6804 static ssize_t
6805 raid5_show_skip_copy(struct mddev *mddev, char *page)
6806 {
6807 	struct r5conf *conf;
6808 	int ret = 0;
6809 	spin_lock(&mddev->lock);
6810 	conf = mddev->private;
6811 	if (conf)
6812 		ret = sprintf(page, "%d\n", conf->skip_copy);
6813 	spin_unlock(&mddev->lock);
6814 	return ret;
6815 }
6816 
6817 static ssize_t
6818 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6819 {
6820 	struct r5conf *conf;
6821 	unsigned long new;
6822 	int err;
6823 
6824 	if (len >= PAGE_SIZE)
6825 		return -EINVAL;
6826 	if (kstrtoul(page, 10, &new))
6827 		return -EINVAL;
6828 	new = !!new;
6829 
6830 	err = mddev_lock(mddev);
6831 	if (err)
6832 		return err;
6833 	conf = mddev->private;
6834 	if (!conf)
6835 		err = -ENODEV;
6836 	else if (new != conf->skip_copy) {
6837 		struct request_queue *q = mddev->queue;
6838 
6839 		mddev_suspend(mddev);
6840 		conf->skip_copy = new;
6841 		if (new)
6842 			blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, q);
6843 		else
6844 			blk_queue_flag_clear(QUEUE_FLAG_STABLE_WRITES, q);
6845 		mddev_resume(mddev);
6846 	}
6847 	mddev_unlock(mddev);
6848 	return err ?: len;
6849 }
6850 
6851 static struct md_sysfs_entry
6852 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6853 					raid5_show_skip_copy,
6854 					raid5_store_skip_copy);
6855 
6856 static ssize_t
6857 stripe_cache_active_show(struct mddev *mddev, char *page)
6858 {
6859 	struct r5conf *conf = mddev->private;
6860 	if (conf)
6861 		return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6862 	else
6863 		return 0;
6864 }
6865 
6866 static struct md_sysfs_entry
6867 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6868 
6869 static ssize_t
6870 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6871 {
6872 	struct r5conf *conf;
6873 	int ret = 0;
6874 	spin_lock(&mddev->lock);
6875 	conf = mddev->private;
6876 	if (conf)
6877 		ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6878 	spin_unlock(&mddev->lock);
6879 	return ret;
6880 }
6881 
6882 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6883 			       int *group_cnt,
6884 			       struct r5worker_group **worker_groups);
6885 static ssize_t
6886 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6887 {
6888 	struct r5conf *conf;
6889 	unsigned int new;
6890 	int err;
6891 	struct r5worker_group *new_groups, *old_groups;
6892 	int group_cnt;
6893 
6894 	if (len >= PAGE_SIZE)
6895 		return -EINVAL;
6896 	if (kstrtouint(page, 10, &new))
6897 		return -EINVAL;
6898 	/* 8192 should be big enough */
6899 	if (new > 8192)
6900 		return -EINVAL;
6901 
6902 	err = mddev_lock(mddev);
6903 	if (err)
6904 		return err;
6905 	conf = mddev->private;
6906 	if (!conf)
6907 		err = -ENODEV;
6908 	else if (new != conf->worker_cnt_per_group) {
6909 		mddev_suspend(mddev);
6910 
6911 		old_groups = conf->worker_groups;
6912 		if (old_groups)
6913 			flush_workqueue(raid5_wq);
6914 
6915 		err = alloc_thread_groups(conf, new, &group_cnt, &new_groups);
6916 		if (!err) {
6917 			spin_lock_irq(&conf->device_lock);
6918 			conf->group_cnt = group_cnt;
6919 			conf->worker_cnt_per_group = new;
6920 			conf->worker_groups = new_groups;
6921 			spin_unlock_irq(&conf->device_lock);
6922 
6923 			if (old_groups)
6924 				kfree(old_groups[0].workers);
6925 			kfree(old_groups);
6926 		}
6927 		mddev_resume(mddev);
6928 	}
6929 	mddev_unlock(mddev);
6930 
6931 	return err ?: len;
6932 }
6933 
6934 static struct md_sysfs_entry
6935 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6936 				raid5_show_group_thread_cnt,
6937 				raid5_store_group_thread_cnt);
6938 
6939 static struct attribute *raid5_attrs[] =  {
6940 	&raid5_stripecache_size.attr,
6941 	&raid5_stripecache_active.attr,
6942 	&raid5_preread_bypass_threshold.attr,
6943 	&raid5_group_thread_cnt.attr,
6944 	&raid5_skip_copy.attr,
6945 	&raid5_rmw_level.attr,
6946 	&raid5_stripe_size.attr,
6947 	&r5c_journal_mode.attr,
6948 	&ppl_write_hint.attr,
6949 	NULL,
6950 };
6951 static struct attribute_group raid5_attrs_group = {
6952 	.name = NULL,
6953 	.attrs = raid5_attrs,
6954 };
6955 
6956 static int alloc_thread_groups(struct r5conf *conf, int cnt, int *group_cnt,
6957 			       struct r5worker_group **worker_groups)
6958 {
6959 	int i, j, k;
6960 	ssize_t size;
6961 	struct r5worker *workers;
6962 
6963 	if (cnt == 0) {
6964 		*group_cnt = 0;
6965 		*worker_groups = NULL;
6966 		return 0;
6967 	}
6968 	*group_cnt = num_possible_nodes();
6969 	size = sizeof(struct r5worker) * cnt;
6970 	workers = kcalloc(size, *group_cnt, GFP_NOIO);
6971 	*worker_groups = kcalloc(*group_cnt, sizeof(struct r5worker_group),
6972 				 GFP_NOIO);
6973 	if (!*worker_groups || !workers) {
6974 		kfree(workers);
6975 		kfree(*worker_groups);
6976 		return -ENOMEM;
6977 	}
6978 
6979 	for (i = 0; i < *group_cnt; i++) {
6980 		struct r5worker_group *group;
6981 
6982 		group = &(*worker_groups)[i];
6983 		INIT_LIST_HEAD(&group->handle_list);
6984 		INIT_LIST_HEAD(&group->loprio_list);
6985 		group->conf = conf;
6986 		group->workers = workers + i * cnt;
6987 
6988 		for (j = 0; j < cnt; j++) {
6989 			struct r5worker *worker = group->workers + j;
6990 			worker->group = group;
6991 			INIT_WORK(&worker->work, raid5_do_work);
6992 
6993 			for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
6994 				INIT_LIST_HEAD(worker->temp_inactive_list + k);
6995 		}
6996 	}
6997 
6998 	return 0;
6999 }
7000 
7001 static void free_thread_groups(struct r5conf *conf)
7002 {
7003 	if (conf->worker_groups)
7004 		kfree(conf->worker_groups[0].workers);
7005 	kfree(conf->worker_groups);
7006 	conf->worker_groups = NULL;
7007 }
7008 
7009 static sector_t
7010 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
7011 {
7012 	struct r5conf *conf = mddev->private;
7013 
7014 	if (!sectors)
7015 		sectors = mddev->dev_sectors;
7016 	if (!raid_disks)
7017 		/* size is defined by the smallest of previous and new size */
7018 		raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
7019 
7020 	sectors &= ~((sector_t)conf->chunk_sectors - 1);
7021 	sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
7022 	return sectors * (raid_disks - conf->max_degraded);
7023 }
7024 
7025 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7026 {
7027 	safe_put_page(percpu->spare_page);
7028 	percpu->spare_page = NULL;
7029 	kvfree(percpu->scribble);
7030 	percpu->scribble = NULL;
7031 }
7032 
7033 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7034 {
7035 	if (conf->level == 6 && !percpu->spare_page) {
7036 		percpu->spare_page = alloc_page(GFP_KERNEL);
7037 		if (!percpu->spare_page)
7038 			return -ENOMEM;
7039 	}
7040 
7041 	if (scribble_alloc(percpu,
7042 			   max(conf->raid_disks,
7043 			       conf->previous_raid_disks),
7044 			   max(conf->chunk_sectors,
7045 			       conf->prev_chunk_sectors)
7046 			   / RAID5_STRIPE_SECTORS(conf))) {
7047 		free_scratch_buffer(conf, percpu);
7048 		return -ENOMEM;
7049 	}
7050 
7051 	return 0;
7052 }
7053 
7054 static int raid456_cpu_dead(unsigned int cpu, struct hlist_node *node)
7055 {
7056 	struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7057 
7058 	free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
7059 	return 0;
7060 }
7061 
7062 static void raid5_free_percpu(struct r5conf *conf)
7063 {
7064 	if (!conf->percpu)
7065 		return;
7066 
7067 	cpuhp_state_remove_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7068 	free_percpu(conf->percpu);
7069 }
7070 
7071 static void free_conf(struct r5conf *conf)
7072 {
7073 	int i;
7074 
7075 	log_exit(conf);
7076 
7077 	unregister_shrinker(&conf->shrinker);
7078 	free_thread_groups(conf);
7079 	shrink_stripes(conf);
7080 	raid5_free_percpu(conf);
7081 	for (i = 0; i < conf->pool_size; i++)
7082 		if (conf->disks[i].extra_page)
7083 			put_page(conf->disks[i].extra_page);
7084 	kfree(conf->disks);
7085 	bioset_exit(&conf->bio_split);
7086 	kfree(conf->stripe_hashtbl);
7087 	kfree(conf->pending_data);
7088 	kfree(conf);
7089 }
7090 
7091 static int raid456_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
7092 {
7093 	struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7094 	struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
7095 
7096 	if (alloc_scratch_buffer(conf, percpu)) {
7097 		pr_warn("%s: failed memory allocation for cpu%u\n",
7098 			__func__, cpu);
7099 		return -ENOMEM;
7100 	}
7101 	return 0;
7102 }
7103 
7104 static int raid5_alloc_percpu(struct r5conf *conf)
7105 {
7106 	int err = 0;
7107 
7108 	conf->percpu = alloc_percpu(struct raid5_percpu);
7109 	if (!conf->percpu)
7110 		return -ENOMEM;
7111 
7112 	err = cpuhp_state_add_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7113 	if (!err) {
7114 		conf->scribble_disks = max(conf->raid_disks,
7115 			conf->previous_raid_disks);
7116 		conf->scribble_sectors = max(conf->chunk_sectors,
7117 			conf->prev_chunk_sectors);
7118 	}
7119 	return err;
7120 }
7121 
7122 static unsigned long raid5_cache_scan(struct shrinker *shrink,
7123 				      struct shrink_control *sc)
7124 {
7125 	struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7126 	unsigned long ret = SHRINK_STOP;
7127 
7128 	if (mutex_trylock(&conf->cache_size_mutex)) {
7129 		ret= 0;
7130 		while (ret < sc->nr_to_scan &&
7131 		       conf->max_nr_stripes > conf->min_nr_stripes) {
7132 			if (drop_one_stripe(conf) == 0) {
7133 				ret = SHRINK_STOP;
7134 				break;
7135 			}
7136 			ret++;
7137 		}
7138 		mutex_unlock(&conf->cache_size_mutex);
7139 	}
7140 	return ret;
7141 }
7142 
7143 static unsigned long raid5_cache_count(struct shrinker *shrink,
7144 				       struct shrink_control *sc)
7145 {
7146 	struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7147 
7148 	if (conf->max_nr_stripes < conf->min_nr_stripes)
7149 		/* unlikely, but not impossible */
7150 		return 0;
7151 	return conf->max_nr_stripes - conf->min_nr_stripes;
7152 }
7153 
7154 static struct r5conf *setup_conf(struct mddev *mddev)
7155 {
7156 	struct r5conf *conf;
7157 	int raid_disk, memory, max_disks;
7158 	struct md_rdev *rdev;
7159 	struct disk_info *disk;
7160 	char pers_name[6];
7161 	int i;
7162 	int group_cnt;
7163 	struct r5worker_group *new_group;
7164 	int ret;
7165 
7166 	if (mddev->new_level != 5
7167 	    && mddev->new_level != 4
7168 	    && mddev->new_level != 6) {
7169 		pr_warn("md/raid:%s: raid level not set to 4/5/6 (%d)\n",
7170 			mdname(mddev), mddev->new_level);
7171 		return ERR_PTR(-EIO);
7172 	}
7173 	if ((mddev->new_level == 5
7174 	     && !algorithm_valid_raid5(mddev->new_layout)) ||
7175 	    (mddev->new_level == 6
7176 	     && !algorithm_valid_raid6(mddev->new_layout))) {
7177 		pr_warn("md/raid:%s: layout %d not supported\n",
7178 			mdname(mddev), mddev->new_layout);
7179 		return ERR_PTR(-EIO);
7180 	}
7181 	if (mddev->new_level == 6 && mddev->raid_disks < 4) {
7182 		pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n",
7183 			mdname(mddev), mddev->raid_disks);
7184 		return ERR_PTR(-EINVAL);
7185 	}
7186 
7187 	if (!mddev->new_chunk_sectors ||
7188 	    (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
7189 	    !is_power_of_2(mddev->new_chunk_sectors)) {
7190 		pr_warn("md/raid:%s: invalid chunk size %d\n",
7191 			mdname(mddev), mddev->new_chunk_sectors << 9);
7192 		return ERR_PTR(-EINVAL);
7193 	}
7194 
7195 	conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
7196 	if (conf == NULL)
7197 		goto abort;
7198 
7199 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
7200 	conf->stripe_size = DEFAULT_STRIPE_SIZE;
7201 	conf->stripe_shift = ilog2(DEFAULT_STRIPE_SIZE) - 9;
7202 	conf->stripe_sectors = DEFAULT_STRIPE_SIZE >> 9;
7203 #endif
7204 	INIT_LIST_HEAD(&conf->free_list);
7205 	INIT_LIST_HEAD(&conf->pending_list);
7206 	conf->pending_data = kcalloc(PENDING_IO_MAX,
7207 				     sizeof(struct r5pending_data),
7208 				     GFP_KERNEL);
7209 	if (!conf->pending_data)
7210 		goto abort;
7211 	for (i = 0; i < PENDING_IO_MAX; i++)
7212 		list_add(&conf->pending_data[i].sibling, &conf->free_list);
7213 	/* Don't enable multi-threading by default*/
7214 	if (!alloc_thread_groups(conf, 0, &group_cnt, &new_group)) {
7215 		conf->group_cnt = group_cnt;
7216 		conf->worker_cnt_per_group = 0;
7217 		conf->worker_groups = new_group;
7218 	} else
7219 		goto abort;
7220 	spin_lock_init(&conf->device_lock);
7221 	seqcount_spinlock_init(&conf->gen_lock, &conf->device_lock);
7222 	mutex_init(&conf->cache_size_mutex);
7223 	init_waitqueue_head(&conf->wait_for_quiescent);
7224 	init_waitqueue_head(&conf->wait_for_stripe);
7225 	init_waitqueue_head(&conf->wait_for_overlap);
7226 	INIT_LIST_HEAD(&conf->handle_list);
7227 	INIT_LIST_HEAD(&conf->loprio_list);
7228 	INIT_LIST_HEAD(&conf->hold_list);
7229 	INIT_LIST_HEAD(&conf->delayed_list);
7230 	INIT_LIST_HEAD(&conf->bitmap_list);
7231 	init_llist_head(&conf->released_stripes);
7232 	atomic_set(&conf->active_stripes, 0);
7233 	atomic_set(&conf->preread_active_stripes, 0);
7234 	atomic_set(&conf->active_aligned_reads, 0);
7235 	spin_lock_init(&conf->pending_bios_lock);
7236 	conf->batch_bio_dispatch = true;
7237 	rdev_for_each(rdev, mddev) {
7238 		if (test_bit(Journal, &rdev->flags))
7239 			continue;
7240 		if (blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
7241 			conf->batch_bio_dispatch = false;
7242 			break;
7243 		}
7244 	}
7245 
7246 	conf->bypass_threshold = BYPASS_THRESHOLD;
7247 	conf->recovery_disabled = mddev->recovery_disabled - 1;
7248 
7249 	conf->raid_disks = mddev->raid_disks;
7250 	if (mddev->reshape_position == MaxSector)
7251 		conf->previous_raid_disks = mddev->raid_disks;
7252 	else
7253 		conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
7254 	max_disks = max(conf->raid_disks, conf->previous_raid_disks);
7255 
7256 	conf->disks = kcalloc(max_disks, sizeof(struct disk_info),
7257 			      GFP_KERNEL);
7258 
7259 	if (!conf->disks)
7260 		goto abort;
7261 
7262 	for (i = 0; i < max_disks; i++) {
7263 		conf->disks[i].extra_page = alloc_page(GFP_KERNEL);
7264 		if (!conf->disks[i].extra_page)
7265 			goto abort;
7266 	}
7267 
7268 	ret = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
7269 	if (ret)
7270 		goto abort;
7271 	conf->mddev = mddev;
7272 
7273 	if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
7274 		goto abort;
7275 
7276 	/* We init hash_locks[0] separately to that it can be used
7277 	 * as the reference lock in the spin_lock_nest_lock() call
7278 	 * in lock_all_device_hash_locks_irq in order to convince
7279 	 * lockdep that we know what we are doing.
7280 	 */
7281 	spin_lock_init(conf->hash_locks);
7282 	for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
7283 		spin_lock_init(conf->hash_locks + i);
7284 
7285 	for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7286 		INIT_LIST_HEAD(conf->inactive_list + i);
7287 
7288 	for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7289 		INIT_LIST_HEAD(conf->temp_inactive_list + i);
7290 
7291 	atomic_set(&conf->r5c_cached_full_stripes, 0);
7292 	INIT_LIST_HEAD(&conf->r5c_full_stripe_list);
7293 	atomic_set(&conf->r5c_cached_partial_stripes, 0);
7294 	INIT_LIST_HEAD(&conf->r5c_partial_stripe_list);
7295 	atomic_set(&conf->r5c_flushing_full_stripes, 0);
7296 	atomic_set(&conf->r5c_flushing_partial_stripes, 0);
7297 
7298 	conf->level = mddev->new_level;
7299 	conf->chunk_sectors = mddev->new_chunk_sectors;
7300 	if (raid5_alloc_percpu(conf) != 0)
7301 		goto abort;
7302 
7303 	pr_debug("raid456: run(%s) called.\n", mdname(mddev));
7304 
7305 	rdev_for_each(rdev, mddev) {
7306 		raid_disk = rdev->raid_disk;
7307 		if (raid_disk >= max_disks
7308 		    || raid_disk < 0 || test_bit(Journal, &rdev->flags))
7309 			continue;
7310 		disk = conf->disks + raid_disk;
7311 
7312 		if (test_bit(Replacement, &rdev->flags)) {
7313 			if (disk->replacement)
7314 				goto abort;
7315 			disk->replacement = rdev;
7316 		} else {
7317 			if (disk->rdev)
7318 				goto abort;
7319 			disk->rdev = rdev;
7320 		}
7321 
7322 		if (test_bit(In_sync, &rdev->flags)) {
7323 			char b[BDEVNAME_SIZE];
7324 			pr_info("md/raid:%s: device %s operational as raid disk %d\n",
7325 				mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
7326 		} else if (rdev->saved_raid_disk != raid_disk)
7327 			/* Cannot rely on bitmap to complete recovery */
7328 			conf->fullsync = 1;
7329 	}
7330 
7331 	conf->level = mddev->new_level;
7332 	if (conf->level == 6) {
7333 		conf->max_degraded = 2;
7334 		if (raid6_call.xor_syndrome)
7335 			conf->rmw_level = PARITY_ENABLE_RMW;
7336 		else
7337 			conf->rmw_level = PARITY_DISABLE_RMW;
7338 	} else {
7339 		conf->max_degraded = 1;
7340 		conf->rmw_level = PARITY_ENABLE_RMW;
7341 	}
7342 	conf->algorithm = mddev->new_layout;
7343 	conf->reshape_progress = mddev->reshape_position;
7344 	if (conf->reshape_progress != MaxSector) {
7345 		conf->prev_chunk_sectors = mddev->chunk_sectors;
7346 		conf->prev_algo = mddev->layout;
7347 	} else {
7348 		conf->prev_chunk_sectors = conf->chunk_sectors;
7349 		conf->prev_algo = conf->algorithm;
7350 	}
7351 
7352 	conf->min_nr_stripes = NR_STRIPES;
7353 	if (mddev->reshape_position != MaxSector) {
7354 		int stripes = max_t(int,
7355 			((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4,
7356 			((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4);
7357 		conf->min_nr_stripes = max(NR_STRIPES, stripes);
7358 		if (conf->min_nr_stripes != NR_STRIPES)
7359 			pr_info("md/raid:%s: force stripe size %d for reshape\n",
7360 				mdname(mddev), conf->min_nr_stripes);
7361 	}
7362 	memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
7363 		 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
7364 	atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
7365 	if (grow_stripes(conf, conf->min_nr_stripes)) {
7366 		pr_warn("md/raid:%s: couldn't allocate %dkB for buffers\n",
7367 			mdname(mddev), memory);
7368 		goto abort;
7369 	} else
7370 		pr_debug("md/raid:%s: allocated %dkB\n", mdname(mddev), memory);
7371 	/*
7372 	 * Losing a stripe head costs more than the time to refill it,
7373 	 * it reduces the queue depth and so can hurt throughput.
7374 	 * So set it rather large, scaled by number of devices.
7375 	 */
7376 	conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
7377 	conf->shrinker.scan_objects = raid5_cache_scan;
7378 	conf->shrinker.count_objects = raid5_cache_count;
7379 	conf->shrinker.batch = 128;
7380 	conf->shrinker.flags = 0;
7381 	if (register_shrinker(&conf->shrinker)) {
7382 		pr_warn("md/raid:%s: couldn't register shrinker.\n",
7383 			mdname(mddev));
7384 		goto abort;
7385 	}
7386 
7387 	sprintf(pers_name, "raid%d", mddev->new_level);
7388 	conf->thread = md_register_thread(raid5d, mddev, pers_name);
7389 	if (!conf->thread) {
7390 		pr_warn("md/raid:%s: couldn't allocate thread.\n",
7391 			mdname(mddev));
7392 		goto abort;
7393 	}
7394 
7395 	return conf;
7396 
7397  abort:
7398 	if (conf) {
7399 		free_conf(conf);
7400 		return ERR_PTR(-EIO);
7401 	} else
7402 		return ERR_PTR(-ENOMEM);
7403 }
7404 
7405 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
7406 {
7407 	switch (algo) {
7408 	case ALGORITHM_PARITY_0:
7409 		if (raid_disk < max_degraded)
7410 			return 1;
7411 		break;
7412 	case ALGORITHM_PARITY_N:
7413 		if (raid_disk >= raid_disks - max_degraded)
7414 			return 1;
7415 		break;
7416 	case ALGORITHM_PARITY_0_6:
7417 		if (raid_disk == 0 ||
7418 		    raid_disk == raid_disks - 1)
7419 			return 1;
7420 		break;
7421 	case ALGORITHM_LEFT_ASYMMETRIC_6:
7422 	case ALGORITHM_RIGHT_ASYMMETRIC_6:
7423 	case ALGORITHM_LEFT_SYMMETRIC_6:
7424 	case ALGORITHM_RIGHT_SYMMETRIC_6:
7425 		if (raid_disk == raid_disks - 1)
7426 			return 1;
7427 	}
7428 	return 0;
7429 }
7430 
7431 static void raid5_set_io_opt(struct r5conf *conf)
7432 {
7433 	blk_queue_io_opt(conf->mddev->queue, (conf->chunk_sectors << 9) *
7434 			 (conf->raid_disks - conf->max_degraded));
7435 }
7436 
7437 static int raid5_run(struct mddev *mddev)
7438 {
7439 	struct r5conf *conf;
7440 	int working_disks = 0;
7441 	int dirty_parity_disks = 0;
7442 	struct md_rdev *rdev;
7443 	struct md_rdev *journal_dev = NULL;
7444 	sector_t reshape_offset = 0;
7445 	int i;
7446 	long long min_offset_diff = 0;
7447 	int first = 1;
7448 
7449 	if (mddev_init_writes_pending(mddev) < 0)
7450 		return -ENOMEM;
7451 
7452 	if (mddev->recovery_cp != MaxSector)
7453 		pr_notice("md/raid:%s: not clean -- starting background reconstruction\n",
7454 			  mdname(mddev));
7455 
7456 	rdev_for_each(rdev, mddev) {
7457 		long long diff;
7458 
7459 		if (test_bit(Journal, &rdev->flags)) {
7460 			journal_dev = rdev;
7461 			continue;
7462 		}
7463 		if (rdev->raid_disk < 0)
7464 			continue;
7465 		diff = (rdev->new_data_offset - rdev->data_offset);
7466 		if (first) {
7467 			min_offset_diff = diff;
7468 			first = 0;
7469 		} else if (mddev->reshape_backwards &&
7470 			 diff < min_offset_diff)
7471 			min_offset_diff = diff;
7472 		else if (!mddev->reshape_backwards &&
7473 			 diff > min_offset_diff)
7474 			min_offset_diff = diff;
7475 	}
7476 
7477 	if ((test_bit(MD_HAS_JOURNAL, &mddev->flags) || journal_dev) &&
7478 	    (mddev->bitmap_info.offset || mddev->bitmap_info.file)) {
7479 		pr_notice("md/raid:%s: array cannot have both journal and bitmap\n",
7480 			  mdname(mddev));
7481 		return -EINVAL;
7482 	}
7483 
7484 	if (mddev->reshape_position != MaxSector) {
7485 		/* Check that we can continue the reshape.
7486 		 * Difficulties arise if the stripe we would write to
7487 		 * next is at or after the stripe we would read from next.
7488 		 * For a reshape that changes the number of devices, this
7489 		 * is only possible for a very short time, and mdadm makes
7490 		 * sure that time appears to have past before assembling
7491 		 * the array.  So we fail if that time hasn't passed.
7492 		 * For a reshape that keeps the number of devices the same
7493 		 * mdadm must be monitoring the reshape can keeping the
7494 		 * critical areas read-only and backed up.  It will start
7495 		 * the array in read-only mode, so we check for that.
7496 		 */
7497 		sector_t here_new, here_old;
7498 		int old_disks;
7499 		int max_degraded = (mddev->level == 6 ? 2 : 1);
7500 		int chunk_sectors;
7501 		int new_data_disks;
7502 
7503 		if (journal_dev) {
7504 			pr_warn("md/raid:%s: don't support reshape with journal - aborting.\n",
7505 				mdname(mddev));
7506 			return -EINVAL;
7507 		}
7508 
7509 		if (mddev->new_level != mddev->level) {
7510 			pr_warn("md/raid:%s: unsupported reshape required - aborting.\n",
7511 				mdname(mddev));
7512 			return -EINVAL;
7513 		}
7514 		old_disks = mddev->raid_disks - mddev->delta_disks;
7515 		/* reshape_position must be on a new-stripe boundary, and one
7516 		 * further up in new geometry must map after here in old
7517 		 * geometry.
7518 		 * If the chunk sizes are different, then as we perform reshape
7519 		 * in units of the largest of the two, reshape_position needs
7520 		 * be a multiple of the largest chunk size times new data disks.
7521 		 */
7522 		here_new = mddev->reshape_position;
7523 		chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
7524 		new_data_disks = mddev->raid_disks - max_degraded;
7525 		if (sector_div(here_new, chunk_sectors * new_data_disks)) {
7526 			pr_warn("md/raid:%s: reshape_position not on a stripe boundary\n",
7527 				mdname(mddev));
7528 			return -EINVAL;
7529 		}
7530 		reshape_offset = here_new * chunk_sectors;
7531 		/* here_new is the stripe we will write to */
7532 		here_old = mddev->reshape_position;
7533 		sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
7534 		/* here_old is the first stripe that we might need to read
7535 		 * from */
7536 		if (mddev->delta_disks == 0) {
7537 			/* We cannot be sure it is safe to start an in-place
7538 			 * reshape.  It is only safe if user-space is monitoring
7539 			 * and taking constant backups.
7540 			 * mdadm always starts a situation like this in
7541 			 * readonly mode so it can take control before
7542 			 * allowing any writes.  So just check for that.
7543 			 */
7544 			if (abs(min_offset_diff) >= mddev->chunk_sectors &&
7545 			    abs(min_offset_diff) >= mddev->new_chunk_sectors)
7546 				/* not really in-place - so OK */;
7547 			else if (mddev->ro == 0) {
7548 				pr_warn("md/raid:%s: in-place reshape must be started in read-only mode - aborting\n",
7549 					mdname(mddev));
7550 				return -EINVAL;
7551 			}
7552 		} else if (mddev->reshape_backwards
7553 		    ? (here_new * chunk_sectors + min_offset_diff <=
7554 		       here_old * chunk_sectors)
7555 		    : (here_new * chunk_sectors >=
7556 		       here_old * chunk_sectors + (-min_offset_diff))) {
7557 			/* Reading from the same stripe as writing to - bad */
7558 			pr_warn("md/raid:%s: reshape_position too early for auto-recovery - aborting.\n",
7559 				mdname(mddev));
7560 			return -EINVAL;
7561 		}
7562 		pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev));
7563 		/* OK, we should be able to continue; */
7564 	} else {
7565 		BUG_ON(mddev->level != mddev->new_level);
7566 		BUG_ON(mddev->layout != mddev->new_layout);
7567 		BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
7568 		BUG_ON(mddev->delta_disks != 0);
7569 	}
7570 
7571 	if (test_bit(MD_HAS_JOURNAL, &mddev->flags) &&
7572 	    test_bit(MD_HAS_PPL, &mddev->flags)) {
7573 		pr_warn("md/raid:%s: using journal device and PPL not allowed - disabling PPL\n",
7574 			mdname(mddev));
7575 		clear_bit(MD_HAS_PPL, &mddev->flags);
7576 		clear_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags);
7577 	}
7578 
7579 	if (mddev->private == NULL)
7580 		conf = setup_conf(mddev);
7581 	else
7582 		conf = mddev->private;
7583 
7584 	if (IS_ERR(conf))
7585 		return PTR_ERR(conf);
7586 
7587 	if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
7588 		if (!journal_dev) {
7589 			pr_warn("md/raid:%s: journal disk is missing, force array readonly\n",
7590 				mdname(mddev));
7591 			mddev->ro = 1;
7592 			set_disk_ro(mddev->gendisk, 1);
7593 		} else if (mddev->recovery_cp == MaxSector)
7594 			set_bit(MD_JOURNAL_CLEAN, &mddev->flags);
7595 	}
7596 
7597 	conf->min_offset_diff = min_offset_diff;
7598 	mddev->thread = conf->thread;
7599 	conf->thread = NULL;
7600 	mddev->private = conf;
7601 
7602 	for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
7603 	     i++) {
7604 		rdev = conf->disks[i].rdev;
7605 		if (!rdev && conf->disks[i].replacement) {
7606 			/* The replacement is all we have yet */
7607 			rdev = conf->disks[i].replacement;
7608 			conf->disks[i].replacement = NULL;
7609 			clear_bit(Replacement, &rdev->flags);
7610 			conf->disks[i].rdev = rdev;
7611 		}
7612 		if (!rdev)
7613 			continue;
7614 		if (conf->disks[i].replacement &&
7615 		    conf->reshape_progress != MaxSector) {
7616 			/* replacements and reshape simply do not mix. */
7617 			pr_warn("md: cannot handle concurrent replacement and reshape.\n");
7618 			goto abort;
7619 		}
7620 		if (test_bit(In_sync, &rdev->flags)) {
7621 			working_disks++;
7622 			continue;
7623 		}
7624 		/* This disc is not fully in-sync.  However if it
7625 		 * just stored parity (beyond the recovery_offset),
7626 		 * when we don't need to be concerned about the
7627 		 * array being dirty.
7628 		 * When reshape goes 'backwards', we never have
7629 		 * partially completed devices, so we only need
7630 		 * to worry about reshape going forwards.
7631 		 */
7632 		/* Hack because v0.91 doesn't store recovery_offset properly. */
7633 		if (mddev->major_version == 0 &&
7634 		    mddev->minor_version > 90)
7635 			rdev->recovery_offset = reshape_offset;
7636 
7637 		if (rdev->recovery_offset < reshape_offset) {
7638 			/* We need to check old and new layout */
7639 			if (!only_parity(rdev->raid_disk,
7640 					 conf->algorithm,
7641 					 conf->raid_disks,
7642 					 conf->max_degraded))
7643 				continue;
7644 		}
7645 		if (!only_parity(rdev->raid_disk,
7646 				 conf->prev_algo,
7647 				 conf->previous_raid_disks,
7648 				 conf->max_degraded))
7649 			continue;
7650 		dirty_parity_disks++;
7651 	}
7652 
7653 	/*
7654 	 * 0 for a fully functional array, 1 or 2 for a degraded array.
7655 	 */
7656 	mddev->degraded = raid5_calc_degraded(conf);
7657 
7658 	if (has_failed(conf)) {
7659 		pr_crit("md/raid:%s: not enough operational devices (%d/%d failed)\n",
7660 			mdname(mddev), mddev->degraded, conf->raid_disks);
7661 		goto abort;
7662 	}
7663 
7664 	/* device size must be a multiple of chunk size */
7665 	mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
7666 	mddev->resync_max_sectors = mddev->dev_sectors;
7667 
7668 	if (mddev->degraded > dirty_parity_disks &&
7669 	    mddev->recovery_cp != MaxSector) {
7670 		if (test_bit(MD_HAS_PPL, &mddev->flags))
7671 			pr_crit("md/raid:%s: starting dirty degraded array with PPL.\n",
7672 				mdname(mddev));
7673 		else if (mddev->ok_start_degraded)
7674 			pr_crit("md/raid:%s: starting dirty degraded array - data corruption possible.\n",
7675 				mdname(mddev));
7676 		else {
7677 			pr_crit("md/raid:%s: cannot start dirty degraded array.\n",
7678 				mdname(mddev));
7679 			goto abort;
7680 		}
7681 	}
7682 
7683 	pr_info("md/raid:%s: raid level %d active with %d out of %d devices, algorithm %d\n",
7684 		mdname(mddev), conf->level,
7685 		mddev->raid_disks-mddev->degraded, mddev->raid_disks,
7686 		mddev->new_layout);
7687 
7688 	print_raid5_conf(conf);
7689 
7690 	if (conf->reshape_progress != MaxSector) {
7691 		conf->reshape_safe = conf->reshape_progress;
7692 		atomic_set(&conf->reshape_stripes, 0);
7693 		clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7694 		clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7695 		set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7696 		set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7697 		mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7698 							"reshape");
7699 		if (!mddev->sync_thread)
7700 			goto abort;
7701 	}
7702 
7703 	/* Ok, everything is just fine now */
7704 	if (mddev->to_remove == &raid5_attrs_group)
7705 		mddev->to_remove = NULL;
7706 	else if (mddev->kobj.sd &&
7707 	    sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
7708 		pr_warn("raid5: failed to create sysfs attributes for %s\n",
7709 			mdname(mddev));
7710 	md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7711 
7712 	if (mddev->queue) {
7713 		int chunk_size;
7714 		/* read-ahead size must cover two whole stripes, which
7715 		 * is 2 * (datadisks) * chunksize where 'n' is the
7716 		 * number of raid devices
7717 		 */
7718 		int data_disks = conf->previous_raid_disks - conf->max_degraded;
7719 		int stripe = data_disks *
7720 			((mddev->chunk_sectors << 9) / PAGE_SIZE);
7721 
7722 		chunk_size = mddev->chunk_sectors << 9;
7723 		blk_queue_io_min(mddev->queue, chunk_size);
7724 		raid5_set_io_opt(conf);
7725 		mddev->queue->limits.raid_partial_stripes_expensive = 1;
7726 		/*
7727 		 * We can only discard a whole stripe. It doesn't make sense to
7728 		 * discard data disk but write parity disk
7729 		 */
7730 		stripe = stripe * PAGE_SIZE;
7731 		/* Round up to power of 2, as discard handling
7732 		 * currently assumes that */
7733 		while ((stripe-1) & stripe)
7734 			stripe = (stripe | (stripe-1)) + 1;
7735 		mddev->queue->limits.discard_alignment = stripe;
7736 		mddev->queue->limits.discard_granularity = stripe;
7737 
7738 		blk_queue_max_write_same_sectors(mddev->queue, 0);
7739 		blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
7740 
7741 		rdev_for_each(rdev, mddev) {
7742 			disk_stack_limits(mddev->gendisk, rdev->bdev,
7743 					  rdev->data_offset << 9);
7744 			disk_stack_limits(mddev->gendisk, rdev->bdev,
7745 					  rdev->new_data_offset << 9);
7746 		}
7747 
7748 		/*
7749 		 * zeroing is required, otherwise data
7750 		 * could be lost. Consider a scenario: discard a stripe
7751 		 * (the stripe could be inconsistent if
7752 		 * discard_zeroes_data is 0); write one disk of the
7753 		 * stripe (the stripe could be inconsistent again
7754 		 * depending on which disks are used to calculate
7755 		 * parity); the disk is broken; The stripe data of this
7756 		 * disk is lost.
7757 		 *
7758 		 * We only allow DISCARD if the sysadmin has confirmed that
7759 		 * only safe devices are in use by setting a module parameter.
7760 		 * A better idea might be to turn DISCARD into WRITE_ZEROES
7761 		 * requests, as that is required to be safe.
7762 		 */
7763 		if (devices_handle_discard_safely &&
7764 		    mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7765 		    mddev->queue->limits.discard_granularity >= stripe)
7766 			blk_queue_flag_set(QUEUE_FLAG_DISCARD,
7767 						mddev->queue);
7768 		else
7769 			blk_queue_flag_clear(QUEUE_FLAG_DISCARD,
7770 						mddev->queue);
7771 
7772 		blk_queue_max_hw_sectors(mddev->queue, UINT_MAX);
7773 	}
7774 
7775 	if (log_init(conf, journal_dev, raid5_has_ppl(conf)))
7776 		goto abort;
7777 
7778 	return 0;
7779 abort:
7780 	md_unregister_thread(&mddev->thread);
7781 	print_raid5_conf(conf);
7782 	free_conf(conf);
7783 	mddev->private = NULL;
7784 	pr_warn("md/raid:%s: failed to run raid set.\n", mdname(mddev));
7785 	return -EIO;
7786 }
7787 
7788 static void raid5_free(struct mddev *mddev, void *priv)
7789 {
7790 	struct r5conf *conf = priv;
7791 
7792 	free_conf(conf);
7793 	mddev->to_remove = &raid5_attrs_group;
7794 }
7795 
7796 static void raid5_status(struct seq_file *seq, struct mddev *mddev)
7797 {
7798 	struct r5conf *conf = mddev->private;
7799 	int i;
7800 
7801 	seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7802 		conf->chunk_sectors / 2, mddev->layout);
7803 	seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7804 	rcu_read_lock();
7805 	for (i = 0; i < conf->raid_disks; i++) {
7806 		struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
7807 		seq_printf (seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
7808 	}
7809 	rcu_read_unlock();
7810 	seq_printf (seq, "]");
7811 }
7812 
7813 static void print_raid5_conf (struct r5conf *conf)
7814 {
7815 	int i;
7816 	struct disk_info *tmp;
7817 
7818 	pr_debug("RAID conf printout:\n");
7819 	if (!conf) {
7820 		pr_debug("(conf==NULL)\n");
7821 		return;
7822 	}
7823 	pr_debug(" --- level:%d rd:%d wd:%d\n", conf->level,
7824 	       conf->raid_disks,
7825 	       conf->raid_disks - conf->mddev->degraded);
7826 
7827 	for (i = 0; i < conf->raid_disks; i++) {
7828 		char b[BDEVNAME_SIZE];
7829 		tmp = conf->disks + i;
7830 		if (tmp->rdev)
7831 			pr_debug(" disk %d, o:%d, dev:%s\n",
7832 			       i, !test_bit(Faulty, &tmp->rdev->flags),
7833 			       bdevname(tmp->rdev->bdev, b));
7834 	}
7835 }
7836 
7837 static int raid5_spare_active(struct mddev *mddev)
7838 {
7839 	int i;
7840 	struct r5conf *conf = mddev->private;
7841 	struct disk_info *tmp;
7842 	int count = 0;
7843 	unsigned long flags;
7844 
7845 	for (i = 0; i < conf->raid_disks; i++) {
7846 		tmp = conf->disks + i;
7847 		if (tmp->replacement
7848 		    && tmp->replacement->recovery_offset == MaxSector
7849 		    && !test_bit(Faulty, &tmp->replacement->flags)
7850 		    && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7851 			/* Replacement has just become active. */
7852 			if (!tmp->rdev
7853 			    || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7854 				count++;
7855 			if (tmp->rdev) {
7856 				/* Replaced device not technically faulty,
7857 				 * but we need to be sure it gets removed
7858 				 * and never re-added.
7859 				 */
7860 				set_bit(Faulty, &tmp->rdev->flags);
7861 				sysfs_notify_dirent_safe(
7862 					tmp->rdev->sysfs_state);
7863 			}
7864 			sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7865 		} else if (tmp->rdev
7866 		    && tmp->rdev->recovery_offset == MaxSector
7867 		    && !test_bit(Faulty, &tmp->rdev->flags)
7868 		    && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7869 			count++;
7870 			sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7871 		}
7872 	}
7873 	spin_lock_irqsave(&conf->device_lock, flags);
7874 	mddev->degraded = raid5_calc_degraded(conf);
7875 	spin_unlock_irqrestore(&conf->device_lock, flags);
7876 	print_raid5_conf(conf);
7877 	return count;
7878 }
7879 
7880 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7881 {
7882 	struct r5conf *conf = mddev->private;
7883 	int err = 0;
7884 	int number = rdev->raid_disk;
7885 	struct md_rdev **rdevp;
7886 	struct disk_info *p = conf->disks + number;
7887 
7888 	print_raid5_conf(conf);
7889 	if (test_bit(Journal, &rdev->flags) && conf->log) {
7890 		/*
7891 		 * we can't wait pending write here, as this is called in
7892 		 * raid5d, wait will deadlock.
7893 		 * neilb: there is no locking about new writes here,
7894 		 * so this cannot be safe.
7895 		 */
7896 		if (atomic_read(&conf->active_stripes) ||
7897 		    atomic_read(&conf->r5c_cached_full_stripes) ||
7898 		    atomic_read(&conf->r5c_cached_partial_stripes)) {
7899 			return -EBUSY;
7900 		}
7901 		log_exit(conf);
7902 		return 0;
7903 	}
7904 	if (rdev == p->rdev)
7905 		rdevp = &p->rdev;
7906 	else if (rdev == p->replacement)
7907 		rdevp = &p->replacement;
7908 	else
7909 		return 0;
7910 
7911 	if (number >= conf->raid_disks &&
7912 	    conf->reshape_progress == MaxSector)
7913 		clear_bit(In_sync, &rdev->flags);
7914 
7915 	if (test_bit(In_sync, &rdev->flags) ||
7916 	    atomic_read(&rdev->nr_pending)) {
7917 		err = -EBUSY;
7918 		goto abort;
7919 	}
7920 	/* Only remove non-faulty devices if recovery
7921 	 * isn't possible.
7922 	 */
7923 	if (!test_bit(Faulty, &rdev->flags) &&
7924 	    mddev->recovery_disabled != conf->recovery_disabled &&
7925 	    !has_failed(conf) &&
7926 	    (!p->replacement || p->replacement == rdev) &&
7927 	    number < conf->raid_disks) {
7928 		err = -EBUSY;
7929 		goto abort;
7930 	}
7931 	*rdevp = NULL;
7932 	if (!test_bit(RemoveSynchronized, &rdev->flags)) {
7933 		synchronize_rcu();
7934 		if (atomic_read(&rdev->nr_pending)) {
7935 			/* lost the race, try later */
7936 			err = -EBUSY;
7937 			*rdevp = rdev;
7938 		}
7939 	}
7940 	if (!err) {
7941 		err = log_modify(conf, rdev, false);
7942 		if (err)
7943 			goto abort;
7944 	}
7945 	if (p->replacement) {
7946 		/* We must have just cleared 'rdev' */
7947 		p->rdev = p->replacement;
7948 		clear_bit(Replacement, &p->replacement->flags);
7949 		smp_mb(); /* Make sure other CPUs may see both as identical
7950 			   * but will never see neither - if they are careful
7951 			   */
7952 		p->replacement = NULL;
7953 
7954 		if (!err)
7955 			err = log_modify(conf, p->rdev, true);
7956 	}
7957 
7958 	clear_bit(WantReplacement, &rdev->flags);
7959 abort:
7960 
7961 	print_raid5_conf(conf);
7962 	return err;
7963 }
7964 
7965 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7966 {
7967 	struct r5conf *conf = mddev->private;
7968 	int ret, err = -EEXIST;
7969 	int disk;
7970 	struct disk_info *p;
7971 	int first = 0;
7972 	int last = conf->raid_disks - 1;
7973 
7974 	if (test_bit(Journal, &rdev->flags)) {
7975 		if (conf->log)
7976 			return -EBUSY;
7977 
7978 		rdev->raid_disk = 0;
7979 		/*
7980 		 * The array is in readonly mode if journal is missing, so no
7981 		 * write requests running. We should be safe
7982 		 */
7983 		ret = log_init(conf, rdev, false);
7984 		if (ret)
7985 			return ret;
7986 
7987 		ret = r5l_start(conf->log);
7988 		if (ret)
7989 			return ret;
7990 
7991 		return 0;
7992 	}
7993 	if (mddev->recovery_disabled == conf->recovery_disabled)
7994 		return -EBUSY;
7995 
7996 	if (rdev->saved_raid_disk < 0 && has_failed(conf))
7997 		/* no point adding a device */
7998 		return -EINVAL;
7999 
8000 	if (rdev->raid_disk >= 0)
8001 		first = last = rdev->raid_disk;
8002 
8003 	/*
8004 	 * find the disk ... but prefer rdev->saved_raid_disk
8005 	 * if possible.
8006 	 */
8007 	if (rdev->saved_raid_disk >= 0 &&
8008 	    rdev->saved_raid_disk >= first &&
8009 	    conf->disks[rdev->saved_raid_disk].rdev == NULL)
8010 		first = rdev->saved_raid_disk;
8011 
8012 	for (disk = first; disk <= last; disk++) {
8013 		p = conf->disks + disk;
8014 		if (p->rdev == NULL) {
8015 			clear_bit(In_sync, &rdev->flags);
8016 			rdev->raid_disk = disk;
8017 			if (rdev->saved_raid_disk != disk)
8018 				conf->fullsync = 1;
8019 			rcu_assign_pointer(p->rdev, rdev);
8020 
8021 			err = log_modify(conf, rdev, true);
8022 
8023 			goto out;
8024 		}
8025 	}
8026 	for (disk = first; disk <= last; disk++) {
8027 		p = conf->disks + disk;
8028 		if (test_bit(WantReplacement, &p->rdev->flags) &&
8029 		    p->replacement == NULL) {
8030 			clear_bit(In_sync, &rdev->flags);
8031 			set_bit(Replacement, &rdev->flags);
8032 			rdev->raid_disk = disk;
8033 			err = 0;
8034 			conf->fullsync = 1;
8035 			rcu_assign_pointer(p->replacement, rdev);
8036 			break;
8037 		}
8038 	}
8039 out:
8040 	print_raid5_conf(conf);
8041 	return err;
8042 }
8043 
8044 static int raid5_resize(struct mddev *mddev, sector_t sectors)
8045 {
8046 	/* no resync is happening, and there is enough space
8047 	 * on all devices, so we can resize.
8048 	 * We need to make sure resync covers any new space.
8049 	 * If the array is shrinking we should possibly wait until
8050 	 * any io in the removed space completes, but it hardly seems
8051 	 * worth it.
8052 	 */
8053 	sector_t newsize;
8054 	struct r5conf *conf = mddev->private;
8055 
8056 	if (raid5_has_log(conf) || raid5_has_ppl(conf))
8057 		return -EINVAL;
8058 	sectors &= ~((sector_t)conf->chunk_sectors - 1);
8059 	newsize = raid5_size(mddev, sectors, mddev->raid_disks);
8060 	if (mddev->external_size &&
8061 	    mddev->array_sectors > newsize)
8062 		return -EINVAL;
8063 	if (mddev->bitmap) {
8064 		int ret = md_bitmap_resize(mddev->bitmap, sectors, 0, 0);
8065 		if (ret)
8066 			return ret;
8067 	}
8068 	md_set_array_sectors(mddev, newsize);
8069 	if (sectors > mddev->dev_sectors &&
8070 	    mddev->recovery_cp > mddev->dev_sectors) {
8071 		mddev->recovery_cp = mddev->dev_sectors;
8072 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8073 	}
8074 	mddev->dev_sectors = sectors;
8075 	mddev->resync_max_sectors = sectors;
8076 	return 0;
8077 }
8078 
8079 static int check_stripe_cache(struct mddev *mddev)
8080 {
8081 	/* Can only proceed if there are plenty of stripe_heads.
8082 	 * We need a minimum of one full stripe,, and for sensible progress
8083 	 * it is best to have about 4 times that.
8084 	 * If we require 4 times, then the default 256 4K stripe_heads will
8085 	 * allow for chunk sizes up to 256K, which is probably OK.
8086 	 * If the chunk size is greater, user-space should request more
8087 	 * stripe_heads first.
8088 	 */
8089 	struct r5conf *conf = mddev->private;
8090 	if (((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8091 	    > conf->min_nr_stripes ||
8092 	    ((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8093 	    > conf->min_nr_stripes) {
8094 		pr_warn("md/raid:%s: reshape: not enough stripes.  Needed %lu\n",
8095 			mdname(mddev),
8096 			((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
8097 			 / RAID5_STRIPE_SIZE(conf))*4);
8098 		return 0;
8099 	}
8100 	return 1;
8101 }
8102 
8103 static int check_reshape(struct mddev *mddev)
8104 {
8105 	struct r5conf *conf = mddev->private;
8106 
8107 	if (raid5_has_log(conf) || raid5_has_ppl(conf))
8108 		return -EINVAL;
8109 	if (mddev->delta_disks == 0 &&
8110 	    mddev->new_layout == mddev->layout &&
8111 	    mddev->new_chunk_sectors == mddev->chunk_sectors)
8112 		return 0; /* nothing to do */
8113 	if (has_failed(conf))
8114 		return -EINVAL;
8115 	if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
8116 		/* We might be able to shrink, but the devices must
8117 		 * be made bigger first.
8118 		 * For raid6, 4 is the minimum size.
8119 		 * Otherwise 2 is the minimum
8120 		 */
8121 		int min = 2;
8122 		if (mddev->level == 6)
8123 			min = 4;
8124 		if (mddev->raid_disks + mddev->delta_disks < min)
8125 			return -EINVAL;
8126 	}
8127 
8128 	if (!check_stripe_cache(mddev))
8129 		return -ENOSPC;
8130 
8131 	if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
8132 	    mddev->delta_disks > 0)
8133 		if (resize_chunks(conf,
8134 				  conf->previous_raid_disks
8135 				  + max(0, mddev->delta_disks),
8136 				  max(mddev->new_chunk_sectors,
8137 				      mddev->chunk_sectors)
8138 			    ) < 0)
8139 			return -ENOMEM;
8140 
8141 	if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
8142 		return 0; /* never bother to shrink */
8143 	return resize_stripes(conf, (conf->previous_raid_disks
8144 				     + mddev->delta_disks));
8145 }
8146 
8147 static int raid5_start_reshape(struct mddev *mddev)
8148 {
8149 	struct r5conf *conf = mddev->private;
8150 	struct md_rdev *rdev;
8151 	int spares = 0;
8152 	unsigned long flags;
8153 
8154 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
8155 		return -EBUSY;
8156 
8157 	if (!check_stripe_cache(mddev))
8158 		return -ENOSPC;
8159 
8160 	if (has_failed(conf))
8161 		return -EINVAL;
8162 
8163 	rdev_for_each(rdev, mddev) {
8164 		if (!test_bit(In_sync, &rdev->flags)
8165 		    && !test_bit(Faulty, &rdev->flags))
8166 			spares++;
8167 	}
8168 
8169 	if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
8170 		/* Not enough devices even to make a degraded array
8171 		 * of that size
8172 		 */
8173 		return -EINVAL;
8174 
8175 	/* Refuse to reduce size of the array.  Any reductions in
8176 	 * array size must be through explicit setting of array_size
8177 	 * attribute.
8178 	 */
8179 	if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
8180 	    < mddev->array_sectors) {
8181 		pr_warn("md/raid:%s: array size must be reduced before number of disks\n",
8182 			mdname(mddev));
8183 		return -EINVAL;
8184 	}
8185 
8186 	atomic_set(&conf->reshape_stripes, 0);
8187 	spin_lock_irq(&conf->device_lock);
8188 	write_seqcount_begin(&conf->gen_lock);
8189 	conf->previous_raid_disks = conf->raid_disks;
8190 	conf->raid_disks += mddev->delta_disks;
8191 	conf->prev_chunk_sectors = conf->chunk_sectors;
8192 	conf->chunk_sectors = mddev->new_chunk_sectors;
8193 	conf->prev_algo = conf->algorithm;
8194 	conf->algorithm = mddev->new_layout;
8195 	conf->generation++;
8196 	/* Code that selects data_offset needs to see the generation update
8197 	 * if reshape_progress has been set - so a memory barrier needed.
8198 	 */
8199 	smp_mb();
8200 	if (mddev->reshape_backwards)
8201 		conf->reshape_progress = raid5_size(mddev, 0, 0);
8202 	else
8203 		conf->reshape_progress = 0;
8204 	conf->reshape_safe = conf->reshape_progress;
8205 	write_seqcount_end(&conf->gen_lock);
8206 	spin_unlock_irq(&conf->device_lock);
8207 
8208 	/* Now make sure any requests that proceeded on the assumption
8209 	 * the reshape wasn't running - like Discard or Read - have
8210 	 * completed.
8211 	 */
8212 	mddev_suspend(mddev);
8213 	mddev_resume(mddev);
8214 
8215 	/* Add some new drives, as many as will fit.
8216 	 * We know there are enough to make the newly sized array work.
8217 	 * Don't add devices if we are reducing the number of
8218 	 * devices in the array.  This is because it is not possible
8219 	 * to correctly record the "partially reconstructed" state of
8220 	 * such devices during the reshape and confusion could result.
8221 	 */
8222 	if (mddev->delta_disks >= 0) {
8223 		rdev_for_each(rdev, mddev)
8224 			if (rdev->raid_disk < 0 &&
8225 			    !test_bit(Faulty, &rdev->flags)) {
8226 				if (raid5_add_disk(mddev, rdev) == 0) {
8227 					if (rdev->raid_disk
8228 					    >= conf->previous_raid_disks)
8229 						set_bit(In_sync, &rdev->flags);
8230 					else
8231 						rdev->recovery_offset = 0;
8232 
8233 					/* Failure here is OK */
8234 					sysfs_link_rdev(mddev, rdev);
8235 				}
8236 			} else if (rdev->raid_disk >= conf->previous_raid_disks
8237 				   && !test_bit(Faulty, &rdev->flags)) {
8238 				/* This is a spare that was manually added */
8239 				set_bit(In_sync, &rdev->flags);
8240 			}
8241 
8242 		/* When a reshape changes the number of devices,
8243 		 * ->degraded is measured against the larger of the
8244 		 * pre and post number of devices.
8245 		 */
8246 		spin_lock_irqsave(&conf->device_lock, flags);
8247 		mddev->degraded = raid5_calc_degraded(conf);
8248 		spin_unlock_irqrestore(&conf->device_lock, flags);
8249 	}
8250 	mddev->raid_disks = conf->raid_disks;
8251 	mddev->reshape_position = conf->reshape_progress;
8252 	set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8253 
8254 	clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8255 	clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8256 	clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8257 	set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8258 	set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8259 	mddev->sync_thread = md_register_thread(md_do_sync, mddev,
8260 						"reshape");
8261 	if (!mddev->sync_thread) {
8262 		mddev->recovery = 0;
8263 		spin_lock_irq(&conf->device_lock);
8264 		write_seqcount_begin(&conf->gen_lock);
8265 		mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
8266 		mddev->new_chunk_sectors =
8267 			conf->chunk_sectors = conf->prev_chunk_sectors;
8268 		mddev->new_layout = conf->algorithm = conf->prev_algo;
8269 		rdev_for_each(rdev, mddev)
8270 			rdev->new_data_offset = rdev->data_offset;
8271 		smp_wmb();
8272 		conf->generation --;
8273 		conf->reshape_progress = MaxSector;
8274 		mddev->reshape_position = MaxSector;
8275 		write_seqcount_end(&conf->gen_lock);
8276 		spin_unlock_irq(&conf->device_lock);
8277 		return -EAGAIN;
8278 	}
8279 	conf->reshape_checkpoint = jiffies;
8280 	md_wakeup_thread(mddev->sync_thread);
8281 	md_new_event(mddev);
8282 	return 0;
8283 }
8284 
8285 /* This is called from the reshape thread and should make any
8286  * changes needed in 'conf'
8287  */
8288 static void end_reshape(struct r5conf *conf)
8289 {
8290 
8291 	if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
8292 		struct md_rdev *rdev;
8293 
8294 		spin_lock_irq(&conf->device_lock);
8295 		conf->previous_raid_disks = conf->raid_disks;
8296 		md_finish_reshape(conf->mddev);
8297 		smp_wmb();
8298 		conf->reshape_progress = MaxSector;
8299 		conf->mddev->reshape_position = MaxSector;
8300 		rdev_for_each(rdev, conf->mddev)
8301 			if (rdev->raid_disk >= 0 &&
8302 			    !test_bit(Journal, &rdev->flags) &&
8303 			    !test_bit(In_sync, &rdev->flags))
8304 				rdev->recovery_offset = MaxSector;
8305 		spin_unlock_irq(&conf->device_lock);
8306 		wake_up(&conf->wait_for_overlap);
8307 
8308 		if (conf->mddev->queue)
8309 			raid5_set_io_opt(conf);
8310 	}
8311 }
8312 
8313 /* This is called from the raid5d thread with mddev_lock held.
8314  * It makes config changes to the device.
8315  */
8316 static void raid5_finish_reshape(struct mddev *mddev)
8317 {
8318 	struct r5conf *conf = mddev->private;
8319 
8320 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8321 
8322 		if (mddev->delta_disks <= 0) {
8323 			int d;
8324 			spin_lock_irq(&conf->device_lock);
8325 			mddev->degraded = raid5_calc_degraded(conf);
8326 			spin_unlock_irq(&conf->device_lock);
8327 			for (d = conf->raid_disks ;
8328 			     d < conf->raid_disks - mddev->delta_disks;
8329 			     d++) {
8330 				struct md_rdev *rdev = conf->disks[d].rdev;
8331 				if (rdev)
8332 					clear_bit(In_sync, &rdev->flags);
8333 				rdev = conf->disks[d].replacement;
8334 				if (rdev)
8335 					clear_bit(In_sync, &rdev->flags);
8336 			}
8337 		}
8338 		mddev->layout = conf->algorithm;
8339 		mddev->chunk_sectors = conf->chunk_sectors;
8340 		mddev->reshape_position = MaxSector;
8341 		mddev->delta_disks = 0;
8342 		mddev->reshape_backwards = 0;
8343 	}
8344 }
8345 
8346 static void raid5_quiesce(struct mddev *mddev, int quiesce)
8347 {
8348 	struct r5conf *conf = mddev->private;
8349 
8350 	if (quiesce) {
8351 		/* stop all writes */
8352 		lock_all_device_hash_locks_irq(conf);
8353 		/* '2' tells resync/reshape to pause so that all
8354 		 * active stripes can drain
8355 		 */
8356 		r5c_flush_cache(conf, INT_MAX);
8357 		conf->quiesce = 2;
8358 		wait_event_cmd(conf->wait_for_quiescent,
8359 				    atomic_read(&conf->active_stripes) == 0 &&
8360 				    atomic_read(&conf->active_aligned_reads) == 0,
8361 				    unlock_all_device_hash_locks_irq(conf),
8362 				    lock_all_device_hash_locks_irq(conf));
8363 		conf->quiesce = 1;
8364 		unlock_all_device_hash_locks_irq(conf);
8365 		/* allow reshape to continue */
8366 		wake_up(&conf->wait_for_overlap);
8367 	} else {
8368 		/* re-enable writes */
8369 		lock_all_device_hash_locks_irq(conf);
8370 		conf->quiesce = 0;
8371 		wake_up(&conf->wait_for_quiescent);
8372 		wake_up(&conf->wait_for_overlap);
8373 		unlock_all_device_hash_locks_irq(conf);
8374 	}
8375 	log_quiesce(conf, quiesce);
8376 }
8377 
8378 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
8379 {
8380 	struct r0conf *raid0_conf = mddev->private;
8381 	sector_t sectors;
8382 
8383 	/* for raid0 takeover only one zone is supported */
8384 	if (raid0_conf->nr_strip_zones > 1) {
8385 		pr_warn("md/raid:%s: cannot takeover raid0 with more than one zone.\n",
8386 			mdname(mddev));
8387 		return ERR_PTR(-EINVAL);
8388 	}
8389 
8390 	sectors = raid0_conf->strip_zone[0].zone_end;
8391 	sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
8392 	mddev->dev_sectors = sectors;
8393 	mddev->new_level = level;
8394 	mddev->new_layout = ALGORITHM_PARITY_N;
8395 	mddev->new_chunk_sectors = mddev->chunk_sectors;
8396 	mddev->raid_disks += 1;
8397 	mddev->delta_disks = 1;
8398 	/* make sure it will be not marked as dirty */
8399 	mddev->recovery_cp = MaxSector;
8400 
8401 	return setup_conf(mddev);
8402 }
8403 
8404 static void *raid5_takeover_raid1(struct mddev *mddev)
8405 {
8406 	int chunksect;
8407 	void *ret;
8408 
8409 	if (mddev->raid_disks != 2 ||
8410 	    mddev->degraded > 1)
8411 		return ERR_PTR(-EINVAL);
8412 
8413 	/* Should check if there are write-behind devices? */
8414 
8415 	chunksect = 64*2; /* 64K by default */
8416 
8417 	/* The array must be an exact multiple of chunksize */
8418 	while (chunksect && (mddev->array_sectors & (chunksect-1)))
8419 		chunksect >>= 1;
8420 
8421 	if ((chunksect<<9) < RAID5_STRIPE_SIZE((struct r5conf *)mddev->private))
8422 		/* array size does not allow a suitable chunk size */
8423 		return ERR_PTR(-EINVAL);
8424 
8425 	mddev->new_level = 5;
8426 	mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
8427 	mddev->new_chunk_sectors = chunksect;
8428 
8429 	ret = setup_conf(mddev);
8430 	if (!IS_ERR(ret))
8431 		mddev_clear_unsupported_flags(mddev,
8432 			UNSUPPORTED_MDDEV_FLAGS);
8433 	return ret;
8434 }
8435 
8436 static void *raid5_takeover_raid6(struct mddev *mddev)
8437 {
8438 	int new_layout;
8439 
8440 	switch (mddev->layout) {
8441 	case ALGORITHM_LEFT_ASYMMETRIC_6:
8442 		new_layout = ALGORITHM_LEFT_ASYMMETRIC;
8443 		break;
8444 	case ALGORITHM_RIGHT_ASYMMETRIC_6:
8445 		new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
8446 		break;
8447 	case ALGORITHM_LEFT_SYMMETRIC_6:
8448 		new_layout = ALGORITHM_LEFT_SYMMETRIC;
8449 		break;
8450 	case ALGORITHM_RIGHT_SYMMETRIC_6:
8451 		new_layout = ALGORITHM_RIGHT_SYMMETRIC;
8452 		break;
8453 	case ALGORITHM_PARITY_0_6:
8454 		new_layout = ALGORITHM_PARITY_0;
8455 		break;
8456 	case ALGORITHM_PARITY_N:
8457 		new_layout = ALGORITHM_PARITY_N;
8458 		break;
8459 	default:
8460 		return ERR_PTR(-EINVAL);
8461 	}
8462 	mddev->new_level = 5;
8463 	mddev->new_layout = new_layout;
8464 	mddev->delta_disks = -1;
8465 	mddev->raid_disks -= 1;
8466 	return setup_conf(mddev);
8467 }
8468 
8469 static int raid5_check_reshape(struct mddev *mddev)
8470 {
8471 	/* For a 2-drive array, the layout and chunk size can be changed
8472 	 * immediately as not restriping is needed.
8473 	 * For larger arrays we record the new value - after validation
8474 	 * to be used by a reshape pass.
8475 	 */
8476 	struct r5conf *conf = mddev->private;
8477 	int new_chunk = mddev->new_chunk_sectors;
8478 
8479 	if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
8480 		return -EINVAL;
8481 	if (new_chunk > 0) {
8482 		if (!is_power_of_2(new_chunk))
8483 			return -EINVAL;
8484 		if (new_chunk < (PAGE_SIZE>>9))
8485 			return -EINVAL;
8486 		if (mddev->array_sectors & (new_chunk-1))
8487 			/* not factor of array size */
8488 			return -EINVAL;
8489 	}
8490 
8491 	/* They look valid */
8492 
8493 	if (mddev->raid_disks == 2) {
8494 		/* can make the change immediately */
8495 		if (mddev->new_layout >= 0) {
8496 			conf->algorithm = mddev->new_layout;
8497 			mddev->layout = mddev->new_layout;
8498 		}
8499 		if (new_chunk > 0) {
8500 			conf->chunk_sectors = new_chunk ;
8501 			mddev->chunk_sectors = new_chunk;
8502 		}
8503 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8504 		md_wakeup_thread(mddev->thread);
8505 	}
8506 	return check_reshape(mddev);
8507 }
8508 
8509 static int raid6_check_reshape(struct mddev *mddev)
8510 {
8511 	int new_chunk = mddev->new_chunk_sectors;
8512 
8513 	if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
8514 		return -EINVAL;
8515 	if (new_chunk > 0) {
8516 		if (!is_power_of_2(new_chunk))
8517 			return -EINVAL;
8518 		if (new_chunk < (PAGE_SIZE >> 9))
8519 			return -EINVAL;
8520 		if (mddev->array_sectors & (new_chunk-1))
8521 			/* not factor of array size */
8522 			return -EINVAL;
8523 	}
8524 
8525 	/* They look valid */
8526 	return check_reshape(mddev);
8527 }
8528 
8529 static void *raid5_takeover(struct mddev *mddev)
8530 {
8531 	/* raid5 can take over:
8532 	 *  raid0 - if there is only one strip zone - make it a raid4 layout
8533 	 *  raid1 - if there are two drives.  We need to know the chunk size
8534 	 *  raid4 - trivial - just use a raid4 layout.
8535 	 *  raid6 - Providing it is a *_6 layout
8536 	 */
8537 	if (mddev->level == 0)
8538 		return raid45_takeover_raid0(mddev, 5);
8539 	if (mddev->level == 1)
8540 		return raid5_takeover_raid1(mddev);
8541 	if (mddev->level == 4) {
8542 		mddev->new_layout = ALGORITHM_PARITY_N;
8543 		mddev->new_level = 5;
8544 		return setup_conf(mddev);
8545 	}
8546 	if (mddev->level == 6)
8547 		return raid5_takeover_raid6(mddev);
8548 
8549 	return ERR_PTR(-EINVAL);
8550 }
8551 
8552 static void *raid4_takeover(struct mddev *mddev)
8553 {
8554 	/* raid4 can take over:
8555 	 *  raid0 - if there is only one strip zone
8556 	 *  raid5 - if layout is right
8557 	 */
8558 	if (mddev->level == 0)
8559 		return raid45_takeover_raid0(mddev, 4);
8560 	if (mddev->level == 5 &&
8561 	    mddev->layout == ALGORITHM_PARITY_N) {
8562 		mddev->new_layout = 0;
8563 		mddev->new_level = 4;
8564 		return setup_conf(mddev);
8565 	}
8566 	return ERR_PTR(-EINVAL);
8567 }
8568 
8569 static struct md_personality raid5_personality;
8570 
8571 static void *raid6_takeover(struct mddev *mddev)
8572 {
8573 	/* Currently can only take over a raid5.  We map the
8574 	 * personality to an equivalent raid6 personality
8575 	 * with the Q block at the end.
8576 	 */
8577 	int new_layout;
8578 
8579 	if (mddev->pers != &raid5_personality)
8580 		return ERR_PTR(-EINVAL);
8581 	if (mddev->degraded > 1)
8582 		return ERR_PTR(-EINVAL);
8583 	if (mddev->raid_disks > 253)
8584 		return ERR_PTR(-EINVAL);
8585 	if (mddev->raid_disks < 3)
8586 		return ERR_PTR(-EINVAL);
8587 
8588 	switch (mddev->layout) {
8589 	case ALGORITHM_LEFT_ASYMMETRIC:
8590 		new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
8591 		break;
8592 	case ALGORITHM_RIGHT_ASYMMETRIC:
8593 		new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
8594 		break;
8595 	case ALGORITHM_LEFT_SYMMETRIC:
8596 		new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
8597 		break;
8598 	case ALGORITHM_RIGHT_SYMMETRIC:
8599 		new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
8600 		break;
8601 	case ALGORITHM_PARITY_0:
8602 		new_layout = ALGORITHM_PARITY_0_6;
8603 		break;
8604 	case ALGORITHM_PARITY_N:
8605 		new_layout = ALGORITHM_PARITY_N;
8606 		break;
8607 	default:
8608 		return ERR_PTR(-EINVAL);
8609 	}
8610 	mddev->new_level = 6;
8611 	mddev->new_layout = new_layout;
8612 	mddev->delta_disks = 1;
8613 	mddev->raid_disks += 1;
8614 	return setup_conf(mddev);
8615 }
8616 
8617 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
8618 {
8619 	struct r5conf *conf;
8620 	int err;
8621 
8622 	err = mddev_lock(mddev);
8623 	if (err)
8624 		return err;
8625 	conf = mddev->private;
8626 	if (!conf) {
8627 		mddev_unlock(mddev);
8628 		return -ENODEV;
8629 	}
8630 
8631 	if (strncmp(buf, "ppl", 3) == 0) {
8632 		/* ppl only works with RAID 5 */
8633 		if (!raid5_has_ppl(conf) && conf->level == 5) {
8634 			err = log_init(conf, NULL, true);
8635 			if (!err) {
8636 				err = resize_stripes(conf, conf->pool_size);
8637 				if (err)
8638 					log_exit(conf);
8639 			}
8640 		} else
8641 			err = -EINVAL;
8642 	} else if (strncmp(buf, "resync", 6) == 0) {
8643 		if (raid5_has_ppl(conf)) {
8644 			mddev_suspend(mddev);
8645 			log_exit(conf);
8646 			mddev_resume(mddev);
8647 			err = resize_stripes(conf, conf->pool_size);
8648 		} else if (test_bit(MD_HAS_JOURNAL, &conf->mddev->flags) &&
8649 			   r5l_log_disk_error(conf)) {
8650 			bool journal_dev_exists = false;
8651 			struct md_rdev *rdev;
8652 
8653 			rdev_for_each(rdev, mddev)
8654 				if (test_bit(Journal, &rdev->flags)) {
8655 					journal_dev_exists = true;
8656 					break;
8657 				}
8658 
8659 			if (!journal_dev_exists) {
8660 				mddev_suspend(mddev);
8661 				clear_bit(MD_HAS_JOURNAL, &mddev->flags);
8662 				mddev_resume(mddev);
8663 			} else  /* need remove journal device first */
8664 				err = -EBUSY;
8665 		} else
8666 			err = -EINVAL;
8667 	} else {
8668 		err = -EINVAL;
8669 	}
8670 
8671 	if (!err)
8672 		md_update_sb(mddev, 1);
8673 
8674 	mddev_unlock(mddev);
8675 
8676 	return err;
8677 }
8678 
8679 static int raid5_start(struct mddev *mddev)
8680 {
8681 	struct r5conf *conf = mddev->private;
8682 
8683 	return r5l_start(conf->log);
8684 }
8685 
8686 static struct md_personality raid6_personality =
8687 {
8688 	.name		= "raid6",
8689 	.level		= 6,
8690 	.owner		= THIS_MODULE,
8691 	.make_request	= raid5_make_request,
8692 	.run		= raid5_run,
8693 	.start		= raid5_start,
8694 	.free		= raid5_free,
8695 	.status		= raid5_status,
8696 	.error_handler	= raid5_error,
8697 	.hot_add_disk	= raid5_add_disk,
8698 	.hot_remove_disk= raid5_remove_disk,
8699 	.spare_active	= raid5_spare_active,
8700 	.sync_request	= raid5_sync_request,
8701 	.resize		= raid5_resize,
8702 	.size		= raid5_size,
8703 	.check_reshape	= raid6_check_reshape,
8704 	.start_reshape  = raid5_start_reshape,
8705 	.finish_reshape = raid5_finish_reshape,
8706 	.quiesce	= raid5_quiesce,
8707 	.takeover	= raid6_takeover,
8708 	.change_consistency_policy = raid5_change_consistency_policy,
8709 };
8710 static struct md_personality raid5_personality =
8711 {
8712 	.name		= "raid5",
8713 	.level		= 5,
8714 	.owner		= THIS_MODULE,
8715 	.make_request	= raid5_make_request,
8716 	.run		= raid5_run,
8717 	.start		= raid5_start,
8718 	.free		= raid5_free,
8719 	.status		= raid5_status,
8720 	.error_handler	= raid5_error,
8721 	.hot_add_disk	= raid5_add_disk,
8722 	.hot_remove_disk= raid5_remove_disk,
8723 	.spare_active	= raid5_spare_active,
8724 	.sync_request	= raid5_sync_request,
8725 	.resize		= raid5_resize,
8726 	.size		= raid5_size,
8727 	.check_reshape	= raid5_check_reshape,
8728 	.start_reshape  = raid5_start_reshape,
8729 	.finish_reshape = raid5_finish_reshape,
8730 	.quiesce	= raid5_quiesce,
8731 	.takeover	= raid5_takeover,
8732 	.change_consistency_policy = raid5_change_consistency_policy,
8733 };
8734 
8735 static struct md_personality raid4_personality =
8736 {
8737 	.name		= "raid4",
8738 	.level		= 4,
8739 	.owner		= THIS_MODULE,
8740 	.make_request	= raid5_make_request,
8741 	.run		= raid5_run,
8742 	.start		= raid5_start,
8743 	.free		= raid5_free,
8744 	.status		= raid5_status,
8745 	.error_handler	= raid5_error,
8746 	.hot_add_disk	= raid5_add_disk,
8747 	.hot_remove_disk= raid5_remove_disk,
8748 	.spare_active	= raid5_spare_active,
8749 	.sync_request	= raid5_sync_request,
8750 	.resize		= raid5_resize,
8751 	.size		= raid5_size,
8752 	.check_reshape	= raid5_check_reshape,
8753 	.start_reshape  = raid5_start_reshape,
8754 	.finish_reshape = raid5_finish_reshape,
8755 	.quiesce	= raid5_quiesce,
8756 	.takeover	= raid4_takeover,
8757 	.change_consistency_policy = raid5_change_consistency_policy,
8758 };
8759 
8760 static int __init raid5_init(void)
8761 {
8762 	int ret;
8763 
8764 	raid5_wq = alloc_workqueue("raid5wq",
8765 		WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
8766 	if (!raid5_wq)
8767 		return -ENOMEM;
8768 
8769 	ret = cpuhp_setup_state_multi(CPUHP_MD_RAID5_PREPARE,
8770 				      "md/raid5:prepare",
8771 				      raid456_cpu_up_prepare,
8772 				      raid456_cpu_dead);
8773 	if (ret) {
8774 		destroy_workqueue(raid5_wq);
8775 		return ret;
8776 	}
8777 	register_md_personality(&raid6_personality);
8778 	register_md_personality(&raid5_personality);
8779 	register_md_personality(&raid4_personality);
8780 	return 0;
8781 }
8782 
8783 static void raid5_exit(void)
8784 {
8785 	unregister_md_personality(&raid6_personality);
8786 	unregister_md_personality(&raid5_personality);
8787 	unregister_md_personality(&raid4_personality);
8788 	cpuhp_remove_multi_state(CPUHP_MD_RAID5_PREPARE);
8789 	destroy_workqueue(raid5_wq);
8790 }
8791 
8792 module_init(raid5_init);
8793 module_exit(raid5_exit);
8794 MODULE_LICENSE("GPL");
8795 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
8796 MODULE_ALIAS("md-personality-4"); /* RAID5 */
8797 MODULE_ALIAS("md-raid5");
8798 MODULE_ALIAS("md-raid4");
8799 MODULE_ALIAS("md-level-5");
8800 MODULE_ALIAS("md-level-4");
8801 MODULE_ALIAS("md-personality-8"); /* RAID6 */
8802 MODULE_ALIAS("md-raid6");
8803 MODULE_ALIAS("md-level-6");
8804 
8805 /* This used to be two separate modules, they were: */
8806 MODULE_ALIAS("raid5");
8807 MODULE_ALIAS("raid6");
8808