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