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