• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * raid5.c : Multiple Devices driver for Linux
3  *	   Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
4  *	   Copyright (C) 1999, 2000 Ingo Molnar
5  *	   Copyright (C) 2002, 2003 H. Peter Anvin
6  *
7  * RAID-4/5/6 management functions.
8  * Thanks to Penguin Computing for making the RAID-6 development possible
9  * by donating a test server!
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2, or (at your option)
14  * any later version.
15  *
16  * You should have received a copy of the GNU General Public License
17  * (for example /usr/src/linux/COPYING); if not, write to the Free
18  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20 
21 /*
22  * BITMAP UNPLUGGING:
23  *
24  * The sequencing for updating the bitmap reliably is a little
25  * subtle (and I got it wrong the first time) so it deserves some
26  * explanation.
27  *
28  * We group bitmap updates into batches.  Each batch has a number.
29  * We may write out several batches at once, but that isn't very important.
30  * conf->seq_write is the number of the last batch successfully written.
31  * conf->seq_flush is the number of the last batch that was closed to
32  *    new additions.
33  * When we discover that we will need to write to any block in a stripe
34  * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
35  * the number of the batch it will be in. This is seq_flush+1.
36  * When we are ready to do a write, if that batch hasn't been written yet,
37  *   we plug the array and queue the stripe for later.
38  * When an unplug happens, we increment bm_flush, thus closing the current
39  *   batch.
40  * When we notice that bm_flush > bm_write, we write out all pending updates
41  * to the bitmap, and advance bm_write to where bm_flush was.
42  * This may occasionally write a bit out twice, but is sure never to
43  * miss any bits.
44  */
45 
46 #include <linux/blkdev.h>
47 #include <linux/kthread.h>
48 #include <linux/raid/pq.h>
49 #include <linux/async_tx.h>
50 #include <linux/module.h>
51 #include <linux/async.h>
52 #include <linux/seq_file.h>
53 #include <linux/cpu.h>
54 #include <linux/slab.h>
55 #include <linux/ratelimit.h>
56 #include <linux/nodemask.h>
57 #include <trace/events/block.h>
58 
59 #include "md.h"
60 #include "raid5.h"
61 #include "raid0.h"
62 #include "bitmap.h"
63 
64 #define cpu_to_group(cpu) cpu_to_node(cpu)
65 #define ANY_GROUP NUMA_NO_NODE
66 
67 static bool devices_handle_discard_safely = false;
68 module_param(devices_handle_discard_safely, bool, 0644);
69 MODULE_PARM_DESC(devices_handle_discard_safely,
70 		 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
71 static struct workqueue_struct *raid5_wq;
72 /*
73  * Stripe cache
74  */
75 
76 #define NR_STRIPES		256
77 #define STRIPE_SIZE		PAGE_SIZE
78 #define STRIPE_SHIFT		(PAGE_SHIFT - 9)
79 #define STRIPE_SECTORS		(STRIPE_SIZE>>9)
80 #define	IO_THRESHOLD		1
81 #define BYPASS_THRESHOLD	1
82 #define NR_HASH			(PAGE_SIZE / sizeof(struct hlist_head))
83 #define HASH_MASK		(NR_HASH - 1)
84 #define MAX_STRIPE_BATCH	8
85 
stripe_hash(struct r5conf * conf,sector_t sect)86 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
87 {
88 	int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
89 	return &conf->stripe_hashtbl[hash];
90 }
91 
stripe_hash_locks_hash(sector_t sect)92 static inline int stripe_hash_locks_hash(sector_t sect)
93 {
94 	return (sect >> STRIPE_SHIFT) & STRIPE_HASH_LOCKS_MASK;
95 }
96 
lock_device_hash_lock(struct r5conf * conf,int hash)97 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
98 {
99 	spin_lock_irq(conf->hash_locks + hash);
100 	spin_lock(&conf->device_lock);
101 }
102 
unlock_device_hash_lock(struct r5conf * conf,int hash)103 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
104 {
105 	spin_unlock(&conf->device_lock);
106 	spin_unlock_irq(conf->hash_locks + hash);
107 }
108 
lock_all_device_hash_locks_irq(struct r5conf * conf)109 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
110 {
111 	int i;
112 	local_irq_disable();
113 	spin_lock(conf->hash_locks);
114 	for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
115 		spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
116 	spin_lock(&conf->device_lock);
117 }
118 
unlock_all_device_hash_locks_irq(struct r5conf * conf)119 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
120 {
121 	int i;
122 	spin_unlock(&conf->device_lock);
123 	for (i = NR_STRIPE_HASH_LOCKS; i; i--)
124 		spin_unlock(conf->hash_locks + i - 1);
125 	local_irq_enable();
126 }
127 
128 /* bio's attached to a stripe+device for I/O are linked together in bi_sector
129  * order without overlap.  There may be several bio's per stripe+device, and
130  * a bio could span several devices.
131  * When walking this list for a particular stripe+device, we must never proceed
132  * beyond a bio that extends past this device, as the next bio might no longer
133  * be valid.
134  * This function is used to determine the 'next' bio in the list, given the sector
135  * of the current stripe+device
136  */
r5_next_bio(struct bio * bio,sector_t sector)137 static inline struct bio *r5_next_bio(struct bio *bio, sector_t sector)
138 {
139 	int sectors = bio_sectors(bio);
140 	if (bio->bi_iter.bi_sector + sectors < sector + STRIPE_SECTORS)
141 		return bio->bi_next;
142 	else
143 		return NULL;
144 }
145 
146 /*
147  * We maintain a biased count of active stripes in the bottom 16 bits of
148  * bi_phys_segments, and a count of processed stripes in the upper 16 bits
149  */
raid5_bi_processed_stripes(struct bio * bio)150 static inline int raid5_bi_processed_stripes(struct bio *bio)
151 {
152 	atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
153 	return (atomic_read(segments) >> 16) & 0xffff;
154 }
155 
raid5_dec_bi_active_stripes(struct bio * bio)156 static inline int raid5_dec_bi_active_stripes(struct bio *bio)
157 {
158 	atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
159 	return atomic_sub_return(1, segments) & 0xffff;
160 }
161 
raid5_inc_bi_active_stripes(struct bio * bio)162 static inline void raid5_inc_bi_active_stripes(struct bio *bio)
163 {
164 	atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
165 	atomic_inc(segments);
166 }
167 
raid5_set_bi_processed_stripes(struct bio * bio,unsigned int cnt)168 static inline void raid5_set_bi_processed_stripes(struct bio *bio,
169 	unsigned int cnt)
170 {
171 	atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
172 	int old, new;
173 
174 	do {
175 		old = atomic_read(segments);
176 		new = (old & 0xffff) | (cnt << 16);
177 	} while (atomic_cmpxchg(segments, old, new) != old);
178 }
179 
raid5_set_bi_stripes(struct bio * bio,unsigned int cnt)180 static inline void raid5_set_bi_stripes(struct bio *bio, unsigned int cnt)
181 {
182 	atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
183 	atomic_set(segments, cnt);
184 }
185 
186 /* Find first data disk in a raid6 stripe */
raid6_d0(struct stripe_head * sh)187 static inline int raid6_d0(struct stripe_head *sh)
188 {
189 	if (sh->ddf_layout)
190 		/* ddf always start from first device */
191 		return 0;
192 	/* md starts just after Q block */
193 	if (sh->qd_idx == sh->disks - 1)
194 		return 0;
195 	else
196 		return sh->qd_idx + 1;
197 }
raid6_next_disk(int disk,int raid_disks)198 static inline int raid6_next_disk(int disk, int raid_disks)
199 {
200 	disk++;
201 	return (disk < raid_disks) ? disk : 0;
202 }
203 
204 /* When walking through the disks in a raid5, starting at raid6_d0,
205  * We need to map each disk to a 'slot', where the data disks are slot
206  * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
207  * is raid_disks-1.  This help does that mapping.
208  */
raid6_idx_to_slot(int idx,struct stripe_head * sh,int * count,int syndrome_disks)209 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
210 			     int *count, int syndrome_disks)
211 {
212 	int slot = *count;
213 
214 	if (sh->ddf_layout)
215 		(*count)++;
216 	if (idx == sh->pd_idx)
217 		return syndrome_disks;
218 	if (idx == sh->qd_idx)
219 		return syndrome_disks + 1;
220 	if (!sh->ddf_layout)
221 		(*count)++;
222 	return slot;
223 }
224 
return_io(struct bio * return_bi)225 static void return_io(struct bio *return_bi)
226 {
227 	struct bio *bi = return_bi;
228 	while (bi) {
229 
230 		return_bi = bi->bi_next;
231 		bi->bi_next = NULL;
232 		bi->bi_iter.bi_size = 0;
233 		trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
234 					 bi, 0);
235 		bio_endio(bi, 0);
236 		bi = return_bi;
237 	}
238 }
239 
240 static void print_raid5_conf (struct r5conf *conf);
241 
stripe_operations_active(struct stripe_head * sh)242 static int stripe_operations_active(struct stripe_head *sh)
243 {
244 	return sh->check_state || sh->reconstruct_state ||
245 	       test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
246 	       test_bit(STRIPE_COMPUTE_RUN, &sh->state);
247 }
248 
raid5_wakeup_stripe_thread(struct stripe_head * sh)249 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
250 {
251 	struct r5conf *conf = sh->raid_conf;
252 	struct r5worker_group *group;
253 	int thread_cnt;
254 	int i, cpu = sh->cpu;
255 
256 	if (!cpu_online(cpu)) {
257 		cpu = cpumask_any(cpu_online_mask);
258 		sh->cpu = cpu;
259 	}
260 
261 	if (list_empty(&sh->lru)) {
262 		struct r5worker_group *group;
263 		group = conf->worker_groups + cpu_to_group(cpu);
264 		list_add_tail(&sh->lru, &group->handle_list);
265 		group->stripes_cnt++;
266 		sh->group = group;
267 	}
268 
269 	if (conf->worker_cnt_per_group == 0) {
270 		md_wakeup_thread(conf->mddev->thread);
271 		return;
272 	}
273 
274 	group = conf->worker_groups + cpu_to_group(sh->cpu);
275 
276 	group->workers[0].working = true;
277 	/* at least one worker should run to avoid race */
278 	queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
279 
280 	thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
281 	/* wakeup more workers */
282 	for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
283 		if (group->workers[i].working == false) {
284 			group->workers[i].working = true;
285 			queue_work_on(sh->cpu, raid5_wq,
286 				      &group->workers[i].work);
287 			thread_cnt--;
288 		}
289 	}
290 }
291 
do_release_stripe(struct r5conf * conf,struct stripe_head * sh,struct list_head * temp_inactive_list)292 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
293 			      struct list_head *temp_inactive_list)
294 {
295 	BUG_ON(!list_empty(&sh->lru));
296 	BUG_ON(atomic_read(&conf->active_stripes)==0);
297 	if (test_bit(STRIPE_HANDLE, &sh->state)) {
298 		if (test_bit(STRIPE_DELAYED, &sh->state) &&
299 		    !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
300 			list_add_tail(&sh->lru, &conf->delayed_list);
301 			if (atomic_read(&conf->preread_active_stripes)
302 			    < IO_THRESHOLD)
303 				md_wakeup_thread(conf->mddev->thread);
304 		} else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
305 			   sh->bm_seq - conf->seq_write > 0)
306 			list_add_tail(&sh->lru, &conf->bitmap_list);
307 		else {
308 			clear_bit(STRIPE_DELAYED, &sh->state);
309 			clear_bit(STRIPE_BIT_DELAY, &sh->state);
310 			if (conf->worker_cnt_per_group == 0) {
311 				list_add_tail(&sh->lru, &conf->handle_list);
312 			} else {
313 				raid5_wakeup_stripe_thread(sh);
314 				return;
315 			}
316 		}
317 		md_wakeup_thread(conf->mddev->thread);
318 	} else {
319 		BUG_ON(stripe_operations_active(sh));
320 		if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
321 			if (atomic_dec_return(&conf->preread_active_stripes)
322 			    < IO_THRESHOLD)
323 				md_wakeup_thread(conf->mddev->thread);
324 		atomic_dec(&conf->active_stripes);
325 		if (!test_bit(STRIPE_EXPANDING, &sh->state))
326 			list_add_tail(&sh->lru, temp_inactive_list);
327 	}
328 }
329 
__release_stripe(struct r5conf * conf,struct stripe_head * sh,struct list_head * temp_inactive_list)330 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
331 			     struct list_head *temp_inactive_list)
332 {
333 	if (atomic_dec_and_test(&sh->count))
334 		do_release_stripe(conf, sh, temp_inactive_list);
335 }
336 
337 /*
338  * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
339  *
340  * Be careful: Only one task can add/delete stripes from temp_inactive_list at
341  * given time. Adding stripes only takes device lock, while deleting stripes
342  * only takes hash lock.
343  */
release_inactive_stripe_list(struct r5conf * conf,struct list_head * temp_inactive_list,int hash)344 static void release_inactive_stripe_list(struct r5conf *conf,
345 					 struct list_head *temp_inactive_list,
346 					 int hash)
347 {
348 	int size;
349 	bool do_wakeup = false;
350 	unsigned long flags;
351 
352 	if (hash == NR_STRIPE_HASH_LOCKS) {
353 		size = NR_STRIPE_HASH_LOCKS;
354 		hash = NR_STRIPE_HASH_LOCKS - 1;
355 	} else
356 		size = 1;
357 	while (size) {
358 		struct list_head *list = &temp_inactive_list[size - 1];
359 
360 		/*
361 		 * We don't hold any lock here yet, get_active_stripe() might
362 		 * remove stripes from the list
363 		 */
364 		if (!list_empty_careful(list)) {
365 			spin_lock_irqsave(conf->hash_locks + hash, flags);
366 			if (list_empty(conf->inactive_list + hash) &&
367 			    !list_empty(list))
368 				atomic_dec(&conf->empty_inactive_list_nr);
369 			list_splice_tail_init(list, conf->inactive_list + hash);
370 			do_wakeup = true;
371 			spin_unlock_irqrestore(conf->hash_locks + hash, flags);
372 		}
373 		size--;
374 		hash--;
375 	}
376 
377 	if (do_wakeup) {
378 		wake_up(&conf->wait_for_stripe);
379 		if (conf->retry_read_aligned)
380 			md_wakeup_thread(conf->mddev->thread);
381 	}
382 }
383 
384 /* should hold conf->device_lock already */
release_stripe_list(struct r5conf * conf,struct list_head * temp_inactive_list)385 static int release_stripe_list(struct r5conf *conf,
386 			       struct list_head *temp_inactive_list)
387 {
388 	struct stripe_head *sh;
389 	int count = 0;
390 	struct llist_node *head;
391 
392 	head = llist_del_all(&conf->released_stripes);
393 	head = llist_reverse_order(head);
394 	while (head) {
395 		int hash;
396 
397 		sh = llist_entry(head, struct stripe_head, release_list);
398 		head = llist_next(head);
399 		/* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
400 		smp_mb();
401 		clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
402 		/*
403 		 * Don't worry the bit is set here, because if the bit is set
404 		 * again, the count is always > 1. This is true for
405 		 * STRIPE_ON_UNPLUG_LIST bit too.
406 		 */
407 		hash = sh->hash_lock_index;
408 		__release_stripe(conf, sh, &temp_inactive_list[hash]);
409 		count++;
410 	}
411 
412 	return count;
413 }
414 
release_stripe(struct stripe_head * sh)415 static void release_stripe(struct stripe_head *sh)
416 {
417 	struct r5conf *conf = sh->raid_conf;
418 	unsigned long flags;
419 	struct list_head list;
420 	int hash;
421 	bool wakeup;
422 
423 	/* Avoid release_list until the last reference.
424 	 */
425 	if (atomic_add_unless(&sh->count, -1, 1))
426 		return;
427 
428 	if (unlikely(!conf->mddev->thread) ||
429 		test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
430 		goto slow_path;
431 	wakeup = llist_add(&sh->release_list, &conf->released_stripes);
432 	if (wakeup)
433 		md_wakeup_thread(conf->mddev->thread);
434 	return;
435 slow_path:
436 	local_irq_save(flags);
437 	/* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
438 	if (atomic_dec_and_lock(&sh->count, &conf->device_lock)) {
439 		INIT_LIST_HEAD(&list);
440 		hash = sh->hash_lock_index;
441 		do_release_stripe(conf, sh, &list);
442 		spin_unlock(&conf->device_lock);
443 		release_inactive_stripe_list(conf, &list, hash);
444 	}
445 	local_irq_restore(flags);
446 }
447 
remove_hash(struct stripe_head * sh)448 static inline void remove_hash(struct stripe_head *sh)
449 {
450 	pr_debug("remove_hash(), stripe %llu\n",
451 		(unsigned long long)sh->sector);
452 
453 	hlist_del_init(&sh->hash);
454 }
455 
insert_hash(struct r5conf * conf,struct stripe_head * sh)456 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
457 {
458 	struct hlist_head *hp = stripe_hash(conf, sh->sector);
459 
460 	pr_debug("insert_hash(), stripe %llu\n",
461 		(unsigned long long)sh->sector);
462 
463 	hlist_add_head(&sh->hash, hp);
464 }
465 
466 /* find an idle stripe, make sure it is unhashed, and return it. */
get_free_stripe(struct r5conf * conf,int hash)467 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
468 {
469 	struct stripe_head *sh = NULL;
470 	struct list_head *first;
471 
472 	if (list_empty(conf->inactive_list + hash))
473 		goto out;
474 	first = (conf->inactive_list + hash)->next;
475 	sh = list_entry(first, struct stripe_head, lru);
476 	list_del_init(first);
477 	remove_hash(sh);
478 	atomic_inc(&conf->active_stripes);
479 	BUG_ON(hash != sh->hash_lock_index);
480 	if (list_empty(conf->inactive_list + hash))
481 		atomic_inc(&conf->empty_inactive_list_nr);
482 out:
483 	return sh;
484 }
485 
shrink_buffers(struct stripe_head * sh)486 static void shrink_buffers(struct stripe_head *sh)
487 {
488 	struct page *p;
489 	int i;
490 	int num = sh->raid_conf->pool_size;
491 
492 	for (i = 0; i < num ; i++) {
493 		WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
494 		p = sh->dev[i].page;
495 		if (!p)
496 			continue;
497 		sh->dev[i].page = NULL;
498 		put_page(p);
499 	}
500 }
501 
grow_buffers(struct stripe_head * sh)502 static int grow_buffers(struct stripe_head *sh)
503 {
504 	int i;
505 	int num = sh->raid_conf->pool_size;
506 
507 	for (i = 0; i < num; i++) {
508 		struct page *page;
509 
510 		if (!(page = alloc_page(GFP_KERNEL))) {
511 			return 1;
512 		}
513 		sh->dev[i].page = page;
514 		sh->dev[i].orig_page = page;
515 	}
516 	return 0;
517 }
518 
519 static void raid5_build_block(struct stripe_head *sh, int i, int previous);
520 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
521 			    struct stripe_head *sh);
522 
init_stripe(struct stripe_head * sh,sector_t sector,int previous)523 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
524 {
525 	struct r5conf *conf = sh->raid_conf;
526 	int i, seq;
527 
528 	BUG_ON(atomic_read(&sh->count) != 0);
529 	BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
530 	BUG_ON(stripe_operations_active(sh));
531 
532 	pr_debug("init_stripe called, stripe %llu\n",
533 		(unsigned long long)sector);
534 retry:
535 	seq = read_seqcount_begin(&conf->gen_lock);
536 	sh->generation = conf->generation - previous;
537 	sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
538 	sh->sector = sector;
539 	stripe_set_idx(sector, conf, previous, sh);
540 	sh->state = 0;
541 
542 	for (i = sh->disks; i--; ) {
543 		struct r5dev *dev = &sh->dev[i];
544 
545 		if (dev->toread || dev->read || dev->towrite || dev->written ||
546 		    test_bit(R5_LOCKED, &dev->flags)) {
547 			printk(KERN_ERR "sector=%llx i=%d %p %p %p %p %d\n",
548 			       (unsigned long long)sh->sector, i, dev->toread,
549 			       dev->read, dev->towrite, dev->written,
550 			       test_bit(R5_LOCKED, &dev->flags));
551 			WARN_ON(1);
552 		}
553 		dev->flags = 0;
554 		raid5_build_block(sh, i, previous);
555 	}
556 	if (read_seqcount_retry(&conf->gen_lock, seq))
557 		goto retry;
558 	insert_hash(conf, sh);
559 	sh->cpu = smp_processor_id();
560 }
561 
__find_stripe(struct r5conf * conf,sector_t sector,short generation)562 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
563 					 short generation)
564 {
565 	struct stripe_head *sh;
566 
567 	pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
568 	hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
569 		if (sh->sector == sector && sh->generation == generation)
570 			return sh;
571 	pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
572 	return NULL;
573 }
574 
575 /*
576  * Need to check if array has failed when deciding whether to:
577  *  - start an array
578  *  - remove non-faulty devices
579  *  - add a spare
580  *  - allow a reshape
581  * This determination is simple when no reshape is happening.
582  * However if there is a reshape, we need to carefully check
583  * both the before and after sections.
584  * This is because some failed devices may only affect one
585  * of the two sections, and some non-in_sync devices may
586  * be insync in the section most affected by failed devices.
587  */
calc_degraded(struct r5conf * conf)588 static int calc_degraded(struct r5conf *conf)
589 {
590 	int degraded, degraded2;
591 	int i;
592 
593 	rcu_read_lock();
594 	degraded = 0;
595 	for (i = 0; i < conf->previous_raid_disks; i++) {
596 		struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
597 		if (rdev && test_bit(Faulty, &rdev->flags))
598 			rdev = rcu_dereference(conf->disks[i].replacement);
599 		if (!rdev || test_bit(Faulty, &rdev->flags))
600 			degraded++;
601 		else if (test_bit(In_sync, &rdev->flags))
602 			;
603 		else
604 			/* not in-sync or faulty.
605 			 * If the reshape increases the number of devices,
606 			 * this is being recovered by the reshape, so
607 			 * this 'previous' section is not in_sync.
608 			 * If the number of devices is being reduced however,
609 			 * the device can only be part of the array if
610 			 * we are reverting a reshape, so this section will
611 			 * be in-sync.
612 			 */
613 			if (conf->raid_disks >= conf->previous_raid_disks)
614 				degraded++;
615 	}
616 	rcu_read_unlock();
617 	if (conf->raid_disks == conf->previous_raid_disks)
618 		return degraded;
619 	rcu_read_lock();
620 	degraded2 = 0;
621 	for (i = 0; i < conf->raid_disks; i++) {
622 		struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
623 		if (rdev && test_bit(Faulty, &rdev->flags))
624 			rdev = rcu_dereference(conf->disks[i].replacement);
625 		if (!rdev || test_bit(Faulty, &rdev->flags))
626 			degraded2++;
627 		else if (test_bit(In_sync, &rdev->flags))
628 			;
629 		else
630 			/* not in-sync or faulty.
631 			 * If reshape increases the number of devices, this
632 			 * section has already been recovered, else it
633 			 * almost certainly hasn't.
634 			 */
635 			if (conf->raid_disks <= conf->previous_raid_disks)
636 				degraded2++;
637 	}
638 	rcu_read_unlock();
639 	if (degraded2 > degraded)
640 		return degraded2;
641 	return degraded;
642 }
643 
has_failed(struct r5conf * conf)644 static int has_failed(struct r5conf *conf)
645 {
646 	int degraded;
647 
648 	if (conf->mddev->reshape_position == MaxSector)
649 		return conf->mddev->degraded > conf->max_degraded;
650 
651 	degraded = calc_degraded(conf);
652 	if (degraded > conf->max_degraded)
653 		return 1;
654 	return 0;
655 }
656 
657 static struct stripe_head *
get_active_stripe(struct r5conf * conf,sector_t sector,int previous,int noblock,int noquiesce)658 get_active_stripe(struct r5conf *conf, sector_t sector,
659 		  int previous, int noblock, int noquiesce)
660 {
661 	struct stripe_head *sh;
662 	int hash = stripe_hash_locks_hash(sector);
663 
664 	pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
665 
666 	spin_lock_irq(conf->hash_locks + hash);
667 
668 	do {
669 		wait_event_lock_irq(conf->wait_for_stripe,
670 				    conf->quiesce == 0 || noquiesce,
671 				    *(conf->hash_locks + hash));
672 		sh = __find_stripe(conf, sector, conf->generation - previous);
673 		if (!sh) {
674 			if (!conf->inactive_blocked)
675 				sh = get_free_stripe(conf, hash);
676 			if (noblock && sh == NULL)
677 				break;
678 			if (!sh) {
679 				conf->inactive_blocked = 1;
680 				wait_event_lock_irq(
681 					conf->wait_for_stripe,
682 					!list_empty(conf->inactive_list + hash) &&
683 					(atomic_read(&conf->active_stripes)
684 					 < (conf->max_nr_stripes * 3 / 4)
685 					 || !conf->inactive_blocked),
686 					*(conf->hash_locks + hash));
687 				conf->inactive_blocked = 0;
688 			} else {
689 				init_stripe(sh, sector, previous);
690 				atomic_inc(&sh->count);
691 			}
692 		} else if (!atomic_inc_not_zero(&sh->count)) {
693 			spin_lock(&conf->device_lock);
694 			if (!atomic_read(&sh->count)) {
695 				if (!test_bit(STRIPE_HANDLE, &sh->state))
696 					atomic_inc(&conf->active_stripes);
697 				BUG_ON(list_empty(&sh->lru) &&
698 				       !test_bit(STRIPE_EXPANDING, &sh->state));
699 				list_del_init(&sh->lru);
700 				if (sh->group) {
701 					sh->group->stripes_cnt--;
702 					sh->group = NULL;
703 				}
704 			}
705 			atomic_inc(&sh->count);
706 			spin_unlock(&conf->device_lock);
707 		}
708 	} while (sh == NULL);
709 
710 	spin_unlock_irq(conf->hash_locks + hash);
711 	return sh;
712 }
713 
714 /* Determine if 'data_offset' or 'new_data_offset' should be used
715  * in this stripe_head.
716  */
use_new_offset(struct r5conf * conf,struct stripe_head * sh)717 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
718 {
719 	sector_t progress = conf->reshape_progress;
720 	/* Need a memory barrier to make sure we see the value
721 	 * of conf->generation, or ->data_offset that was set before
722 	 * reshape_progress was updated.
723 	 */
724 	smp_rmb();
725 	if (progress == MaxSector)
726 		return 0;
727 	if (sh->generation == conf->generation - 1)
728 		return 0;
729 	/* We are in a reshape, and this is a new-generation stripe,
730 	 * so use new_data_offset.
731 	 */
732 	return 1;
733 }
734 
735 static void
736 raid5_end_read_request(struct bio *bi, int error);
737 static void
738 raid5_end_write_request(struct bio *bi, int error);
739 
ops_run_io(struct stripe_head * sh,struct stripe_head_state * s)740 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
741 {
742 	struct r5conf *conf = sh->raid_conf;
743 	int i, disks = sh->disks;
744 
745 	might_sleep();
746 
747 	for (i = disks; i--; ) {
748 		int rw;
749 		int replace_only = 0;
750 		struct bio *bi, *rbi;
751 		struct md_rdev *rdev, *rrdev = NULL;
752 		if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
753 			if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
754 				rw = WRITE_FUA;
755 			else
756 				rw = WRITE;
757 			if (test_bit(R5_Discard, &sh->dev[i].flags))
758 				rw |= REQ_DISCARD;
759 		} else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
760 			rw = READ;
761 		else if (test_and_clear_bit(R5_WantReplace,
762 					    &sh->dev[i].flags)) {
763 			rw = WRITE;
764 			replace_only = 1;
765 		} else
766 			continue;
767 		if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
768 			rw |= REQ_SYNC;
769 
770 		bi = &sh->dev[i].req;
771 		rbi = &sh->dev[i].rreq; /* For writing to replacement */
772 
773 		rcu_read_lock();
774 		rrdev = rcu_dereference(conf->disks[i].replacement);
775 		smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
776 		rdev = rcu_dereference(conf->disks[i].rdev);
777 		if (!rdev) {
778 			rdev = rrdev;
779 			rrdev = NULL;
780 		}
781 		if (rw & WRITE) {
782 			if (replace_only)
783 				rdev = NULL;
784 			if (rdev == rrdev)
785 				/* We raced and saw duplicates */
786 				rrdev = NULL;
787 		} else {
788 			if (test_bit(R5_ReadRepl, &sh->dev[i].flags) && rrdev)
789 				rdev = rrdev;
790 			rrdev = NULL;
791 		}
792 
793 		if (rdev && test_bit(Faulty, &rdev->flags))
794 			rdev = NULL;
795 		if (rdev)
796 			atomic_inc(&rdev->nr_pending);
797 		if (rrdev && test_bit(Faulty, &rrdev->flags))
798 			rrdev = NULL;
799 		if (rrdev)
800 			atomic_inc(&rrdev->nr_pending);
801 		rcu_read_unlock();
802 
803 		/* We have already checked bad blocks for reads.  Now
804 		 * need to check for writes.  We never accept write errors
805 		 * on the replacement, so we don't to check rrdev.
806 		 */
807 		while ((rw & WRITE) && rdev &&
808 		       test_bit(WriteErrorSeen, &rdev->flags)) {
809 			sector_t first_bad;
810 			int bad_sectors;
811 			int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
812 					      &first_bad, &bad_sectors);
813 			if (!bad)
814 				break;
815 
816 			if (bad < 0) {
817 				set_bit(BlockedBadBlocks, &rdev->flags);
818 				if (!conf->mddev->external &&
819 				    conf->mddev->flags) {
820 					/* It is very unlikely, but we might
821 					 * still need to write out the
822 					 * bad block log - better give it
823 					 * a chance*/
824 					md_check_recovery(conf->mddev);
825 				}
826 				/*
827 				 * Because md_wait_for_blocked_rdev
828 				 * will dec nr_pending, we must
829 				 * increment it first.
830 				 */
831 				atomic_inc(&rdev->nr_pending);
832 				md_wait_for_blocked_rdev(rdev, conf->mddev);
833 			} else {
834 				/* Acknowledged bad block - skip the write */
835 				rdev_dec_pending(rdev, conf->mddev);
836 				rdev = NULL;
837 			}
838 		}
839 
840 		if (rdev) {
841 			if (s->syncing || s->expanding || s->expanded
842 			    || s->replacing)
843 				md_sync_acct(rdev->bdev, STRIPE_SECTORS);
844 
845 			set_bit(STRIPE_IO_STARTED, &sh->state);
846 
847 			bio_reset(bi);
848 			bi->bi_bdev = rdev->bdev;
849 			bi->bi_rw = rw;
850 			bi->bi_end_io = (rw & WRITE)
851 				? raid5_end_write_request
852 				: raid5_end_read_request;
853 			bi->bi_private = sh;
854 
855 			pr_debug("%s: for %llu schedule op %ld on disc %d\n",
856 				__func__, (unsigned long long)sh->sector,
857 				bi->bi_rw, i);
858 			atomic_inc(&sh->count);
859 			if (use_new_offset(conf, sh))
860 				bi->bi_iter.bi_sector = (sh->sector
861 						 + rdev->new_data_offset);
862 			else
863 				bi->bi_iter.bi_sector = (sh->sector
864 						 + rdev->data_offset);
865 			if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
866 				bi->bi_rw |= REQ_NOMERGE;
867 
868 			if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
869 				WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
870 			sh->dev[i].vec.bv_page = sh->dev[i].page;
871 			bi->bi_vcnt = 1;
872 			bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
873 			bi->bi_io_vec[0].bv_offset = 0;
874 			bi->bi_iter.bi_size = STRIPE_SIZE;
875 			/*
876 			 * If this is discard request, set bi_vcnt 0. We don't
877 			 * want to confuse SCSI because SCSI will replace payload
878 			 */
879 			if (rw & REQ_DISCARD)
880 				bi->bi_vcnt = 0;
881 			if (rrdev)
882 				set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
883 
884 			if (conf->mddev->gendisk)
885 				trace_block_bio_remap(bdev_get_queue(bi->bi_bdev),
886 						      bi, disk_devt(conf->mddev->gendisk),
887 						      sh->dev[i].sector);
888 			generic_make_request(bi);
889 		}
890 		if (rrdev) {
891 			if (s->syncing || s->expanding || s->expanded
892 			    || s->replacing)
893 				md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
894 
895 			set_bit(STRIPE_IO_STARTED, &sh->state);
896 
897 			bio_reset(rbi);
898 			rbi->bi_bdev = rrdev->bdev;
899 			rbi->bi_rw = rw;
900 			BUG_ON(!(rw & WRITE));
901 			rbi->bi_end_io = raid5_end_write_request;
902 			rbi->bi_private = sh;
903 
904 			pr_debug("%s: for %llu schedule op %ld on "
905 				 "replacement disc %d\n",
906 				__func__, (unsigned long long)sh->sector,
907 				rbi->bi_rw, i);
908 			atomic_inc(&sh->count);
909 			if (use_new_offset(conf, sh))
910 				rbi->bi_iter.bi_sector = (sh->sector
911 						  + rrdev->new_data_offset);
912 			else
913 				rbi->bi_iter.bi_sector = (sh->sector
914 						  + rrdev->data_offset);
915 			if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
916 				WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
917 			sh->dev[i].rvec.bv_page = sh->dev[i].page;
918 			rbi->bi_vcnt = 1;
919 			rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
920 			rbi->bi_io_vec[0].bv_offset = 0;
921 			rbi->bi_iter.bi_size = STRIPE_SIZE;
922 			/*
923 			 * If this is discard request, set bi_vcnt 0. We don't
924 			 * want to confuse SCSI because SCSI will replace payload
925 			 */
926 			if (rw & REQ_DISCARD)
927 				rbi->bi_vcnt = 0;
928 			if (conf->mddev->gendisk)
929 				trace_block_bio_remap(bdev_get_queue(rbi->bi_bdev),
930 						      rbi, disk_devt(conf->mddev->gendisk),
931 						      sh->dev[i].sector);
932 			generic_make_request(rbi);
933 		}
934 		if (!rdev && !rrdev) {
935 			if (rw & WRITE)
936 				set_bit(STRIPE_DEGRADED, &sh->state);
937 			pr_debug("skip op %ld on disc %d for sector %llu\n",
938 				bi->bi_rw, i, (unsigned long long)sh->sector);
939 			clear_bit(R5_LOCKED, &sh->dev[i].flags);
940 			set_bit(STRIPE_HANDLE, &sh->state);
941 		}
942 	}
943 }
944 
945 static struct dma_async_tx_descriptor *
async_copy_data(int frombio,struct bio * bio,struct page ** page,sector_t sector,struct dma_async_tx_descriptor * tx,struct stripe_head * sh)946 async_copy_data(int frombio, struct bio *bio, struct page **page,
947 	sector_t sector, struct dma_async_tx_descriptor *tx,
948 	struct stripe_head *sh)
949 {
950 	struct bio_vec bvl;
951 	struct bvec_iter iter;
952 	struct page *bio_page;
953 	int page_offset;
954 	struct async_submit_ctl submit;
955 	enum async_tx_flags flags = 0;
956 
957 	if (bio->bi_iter.bi_sector >= sector)
958 		page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
959 	else
960 		page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
961 
962 	if (frombio)
963 		flags |= ASYNC_TX_FENCE;
964 	init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
965 
966 	bio_for_each_segment(bvl, bio, iter) {
967 		int len = bvl.bv_len;
968 		int clen;
969 		int b_offset = 0;
970 
971 		if (page_offset < 0) {
972 			b_offset = -page_offset;
973 			page_offset += b_offset;
974 			len -= b_offset;
975 		}
976 
977 		if (len > 0 && page_offset + len > STRIPE_SIZE)
978 			clen = STRIPE_SIZE - page_offset;
979 		else
980 			clen = len;
981 
982 		if (clen > 0) {
983 			b_offset += bvl.bv_offset;
984 			bio_page = bvl.bv_page;
985 			if (frombio) {
986 				if (sh->raid_conf->skip_copy &&
987 				    b_offset == 0 && page_offset == 0 &&
988 				    clen == STRIPE_SIZE)
989 					*page = bio_page;
990 				else
991 					tx = async_memcpy(*page, bio_page, page_offset,
992 						  b_offset, clen, &submit);
993 			} else
994 				tx = async_memcpy(bio_page, *page, b_offset,
995 						  page_offset, clen, &submit);
996 		}
997 		/* chain the operations */
998 		submit.depend_tx = tx;
999 
1000 		if (clen < len) /* hit end of page */
1001 			break;
1002 		page_offset +=  len;
1003 	}
1004 
1005 	return tx;
1006 }
1007 
ops_complete_biofill(void * stripe_head_ref)1008 static void ops_complete_biofill(void *stripe_head_ref)
1009 {
1010 	struct stripe_head *sh = stripe_head_ref;
1011 	struct bio *return_bi = NULL;
1012 	int i;
1013 
1014 	pr_debug("%s: stripe %llu\n", __func__,
1015 		(unsigned long long)sh->sector);
1016 
1017 	/* clear completed biofills */
1018 	for (i = sh->disks; i--; ) {
1019 		struct r5dev *dev = &sh->dev[i];
1020 
1021 		/* acknowledge completion of a biofill operation */
1022 		/* and check if we need to reply to a read request,
1023 		 * new R5_Wantfill requests are held off until
1024 		 * !STRIPE_BIOFILL_RUN
1025 		 */
1026 		if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1027 			struct bio *rbi, *rbi2;
1028 
1029 			BUG_ON(!dev->read);
1030 			rbi = dev->read;
1031 			dev->read = NULL;
1032 			while (rbi && rbi->bi_iter.bi_sector <
1033 				dev->sector + STRIPE_SECTORS) {
1034 				rbi2 = r5_next_bio(rbi, dev->sector);
1035 				if (!raid5_dec_bi_active_stripes(rbi)) {
1036 					rbi->bi_next = return_bi;
1037 					return_bi = rbi;
1038 				}
1039 				rbi = rbi2;
1040 			}
1041 		}
1042 	}
1043 	clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1044 
1045 	return_io(return_bi);
1046 
1047 	set_bit(STRIPE_HANDLE, &sh->state);
1048 	release_stripe(sh);
1049 }
1050 
ops_run_biofill(struct stripe_head * sh)1051 static void ops_run_biofill(struct stripe_head *sh)
1052 {
1053 	struct dma_async_tx_descriptor *tx = NULL;
1054 	struct async_submit_ctl submit;
1055 	int i;
1056 
1057 	pr_debug("%s: stripe %llu\n", __func__,
1058 		(unsigned long long)sh->sector);
1059 
1060 	for (i = sh->disks; i--; ) {
1061 		struct r5dev *dev = &sh->dev[i];
1062 		if (test_bit(R5_Wantfill, &dev->flags)) {
1063 			struct bio *rbi;
1064 			spin_lock_irq(&sh->stripe_lock);
1065 			dev->read = rbi = dev->toread;
1066 			dev->toread = NULL;
1067 			spin_unlock_irq(&sh->stripe_lock);
1068 			while (rbi && rbi->bi_iter.bi_sector <
1069 				dev->sector + STRIPE_SECTORS) {
1070 				tx = async_copy_data(0, rbi, &dev->page,
1071 					dev->sector, tx, sh);
1072 				rbi = r5_next_bio(rbi, dev->sector);
1073 			}
1074 		}
1075 	}
1076 
1077 	atomic_inc(&sh->count);
1078 	init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1079 	async_trigger_callback(&submit);
1080 }
1081 
mark_target_uptodate(struct stripe_head * sh,int target)1082 static void mark_target_uptodate(struct stripe_head *sh, int target)
1083 {
1084 	struct r5dev *tgt;
1085 
1086 	if (target < 0)
1087 		return;
1088 
1089 	tgt = &sh->dev[target];
1090 	set_bit(R5_UPTODATE, &tgt->flags);
1091 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1092 	clear_bit(R5_Wantcompute, &tgt->flags);
1093 }
1094 
ops_complete_compute(void * stripe_head_ref)1095 static void ops_complete_compute(void *stripe_head_ref)
1096 {
1097 	struct stripe_head *sh = stripe_head_ref;
1098 
1099 	pr_debug("%s: stripe %llu\n", __func__,
1100 		(unsigned long long)sh->sector);
1101 
1102 	/* mark the computed target(s) as uptodate */
1103 	mark_target_uptodate(sh, sh->ops.target);
1104 	mark_target_uptodate(sh, sh->ops.target2);
1105 
1106 	clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1107 	if (sh->check_state == check_state_compute_run)
1108 		sh->check_state = check_state_compute_result;
1109 	set_bit(STRIPE_HANDLE, &sh->state);
1110 	release_stripe(sh);
1111 }
1112 
1113 /* return a pointer to the address conversion region of the scribble buffer */
to_addr_conv(struct stripe_head * sh,struct raid5_percpu * percpu)1114 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1115 				 struct raid5_percpu *percpu)
1116 {
1117 	return percpu->scribble + sizeof(struct page *) * (sh->disks + 2);
1118 }
1119 
1120 static struct dma_async_tx_descriptor *
ops_run_compute5(struct stripe_head * sh,struct raid5_percpu * percpu)1121 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1122 {
1123 	int disks = sh->disks;
1124 	struct page **xor_srcs = percpu->scribble;
1125 	int target = sh->ops.target;
1126 	struct r5dev *tgt = &sh->dev[target];
1127 	struct page *xor_dest = tgt->page;
1128 	int count = 0;
1129 	struct dma_async_tx_descriptor *tx;
1130 	struct async_submit_ctl submit;
1131 	int i;
1132 
1133 	pr_debug("%s: stripe %llu block: %d\n",
1134 		__func__, (unsigned long long)sh->sector, target);
1135 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1136 
1137 	for (i = disks; i--; )
1138 		if (i != target)
1139 			xor_srcs[count++] = sh->dev[i].page;
1140 
1141 	atomic_inc(&sh->count);
1142 
1143 	init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1144 			  ops_complete_compute, sh, to_addr_conv(sh, percpu));
1145 	if (unlikely(count == 1))
1146 		tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1147 	else
1148 		tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1149 
1150 	return tx;
1151 }
1152 
1153 /* set_syndrome_sources - populate source buffers for gen_syndrome
1154  * @srcs - (struct page *) array of size sh->disks
1155  * @sh - stripe_head to parse
1156  *
1157  * Populates srcs in proper layout order for the stripe and returns the
1158  * 'count' of sources to be used in a call to async_gen_syndrome.  The P
1159  * destination buffer is recorded in srcs[count] and the Q destination
1160  * is recorded in srcs[count+1]].
1161  */
set_syndrome_sources(struct page ** srcs,struct stripe_head * sh)1162 static int set_syndrome_sources(struct page **srcs, struct stripe_head *sh)
1163 {
1164 	int disks = sh->disks;
1165 	int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1166 	int d0_idx = raid6_d0(sh);
1167 	int count;
1168 	int i;
1169 
1170 	for (i = 0; i < disks; i++)
1171 		srcs[i] = NULL;
1172 
1173 	count = 0;
1174 	i = d0_idx;
1175 	do {
1176 		int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1177 
1178 		srcs[slot] = sh->dev[i].page;
1179 		i = raid6_next_disk(i, disks);
1180 	} while (i != d0_idx);
1181 
1182 	return syndrome_disks;
1183 }
1184 
1185 static struct dma_async_tx_descriptor *
ops_run_compute6_1(struct stripe_head * sh,struct raid5_percpu * percpu)1186 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1187 {
1188 	int disks = sh->disks;
1189 	struct page **blocks = percpu->scribble;
1190 	int target;
1191 	int qd_idx = sh->qd_idx;
1192 	struct dma_async_tx_descriptor *tx;
1193 	struct async_submit_ctl submit;
1194 	struct r5dev *tgt;
1195 	struct page *dest;
1196 	int i;
1197 	int count;
1198 
1199 	if (sh->ops.target < 0)
1200 		target = sh->ops.target2;
1201 	else if (sh->ops.target2 < 0)
1202 		target = sh->ops.target;
1203 	else
1204 		/* we should only have one valid target */
1205 		BUG();
1206 	BUG_ON(target < 0);
1207 	pr_debug("%s: stripe %llu block: %d\n",
1208 		__func__, (unsigned long long)sh->sector, target);
1209 
1210 	tgt = &sh->dev[target];
1211 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1212 	dest = tgt->page;
1213 
1214 	atomic_inc(&sh->count);
1215 
1216 	if (target == qd_idx) {
1217 		count = set_syndrome_sources(blocks, sh);
1218 		blocks[count] = NULL; /* regenerating p is not necessary */
1219 		BUG_ON(blocks[count+1] != dest); /* q should already be set */
1220 		init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1221 				  ops_complete_compute, sh,
1222 				  to_addr_conv(sh, percpu));
1223 		tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1224 	} else {
1225 		/* Compute any data- or p-drive using XOR */
1226 		count = 0;
1227 		for (i = disks; i-- ; ) {
1228 			if (i == target || i == qd_idx)
1229 				continue;
1230 			blocks[count++] = sh->dev[i].page;
1231 		}
1232 
1233 		init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1234 				  NULL, ops_complete_compute, sh,
1235 				  to_addr_conv(sh, percpu));
1236 		tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1237 	}
1238 
1239 	return tx;
1240 }
1241 
1242 static struct dma_async_tx_descriptor *
ops_run_compute6_2(struct stripe_head * sh,struct raid5_percpu * percpu)1243 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1244 {
1245 	int i, count, disks = sh->disks;
1246 	int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1247 	int d0_idx = raid6_d0(sh);
1248 	int faila = -1, failb = -1;
1249 	int target = sh->ops.target;
1250 	int target2 = sh->ops.target2;
1251 	struct r5dev *tgt = &sh->dev[target];
1252 	struct r5dev *tgt2 = &sh->dev[target2];
1253 	struct dma_async_tx_descriptor *tx;
1254 	struct page **blocks = percpu->scribble;
1255 	struct async_submit_ctl submit;
1256 
1257 	pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1258 		 __func__, (unsigned long long)sh->sector, target, target2);
1259 	BUG_ON(target < 0 || target2 < 0);
1260 	BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1261 	BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1262 
1263 	/* we need to open-code set_syndrome_sources to handle the
1264 	 * slot number conversion for 'faila' and 'failb'
1265 	 */
1266 	for (i = 0; i < disks ; i++)
1267 		blocks[i] = NULL;
1268 	count = 0;
1269 	i = d0_idx;
1270 	do {
1271 		int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1272 
1273 		blocks[slot] = sh->dev[i].page;
1274 
1275 		if (i == target)
1276 			faila = slot;
1277 		if (i == target2)
1278 			failb = slot;
1279 		i = raid6_next_disk(i, disks);
1280 	} while (i != d0_idx);
1281 
1282 	BUG_ON(faila == failb);
1283 	if (failb < faila)
1284 		swap(faila, failb);
1285 	pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1286 		 __func__, (unsigned long long)sh->sector, faila, failb);
1287 
1288 	atomic_inc(&sh->count);
1289 
1290 	if (failb == syndrome_disks+1) {
1291 		/* Q disk is one of the missing disks */
1292 		if (faila == syndrome_disks) {
1293 			/* Missing P+Q, just recompute */
1294 			init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1295 					  ops_complete_compute, sh,
1296 					  to_addr_conv(sh, percpu));
1297 			return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1298 						  STRIPE_SIZE, &submit);
1299 		} else {
1300 			struct page *dest;
1301 			int data_target;
1302 			int qd_idx = sh->qd_idx;
1303 
1304 			/* Missing D+Q: recompute D from P, then recompute Q */
1305 			if (target == qd_idx)
1306 				data_target = target2;
1307 			else
1308 				data_target = target;
1309 
1310 			count = 0;
1311 			for (i = disks; i-- ; ) {
1312 				if (i == data_target || i == qd_idx)
1313 					continue;
1314 				blocks[count++] = sh->dev[i].page;
1315 			}
1316 			dest = sh->dev[data_target].page;
1317 			init_async_submit(&submit,
1318 					  ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1319 					  NULL, NULL, NULL,
1320 					  to_addr_conv(sh, percpu));
1321 			tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1322 				       &submit);
1323 
1324 			count = set_syndrome_sources(blocks, sh);
1325 			init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1326 					  ops_complete_compute, sh,
1327 					  to_addr_conv(sh, percpu));
1328 			return async_gen_syndrome(blocks, 0, count+2,
1329 						  STRIPE_SIZE, &submit);
1330 		}
1331 	} else {
1332 		init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1333 				  ops_complete_compute, sh,
1334 				  to_addr_conv(sh, percpu));
1335 		if (failb == syndrome_disks) {
1336 			/* We're missing D+P. */
1337 			return async_raid6_datap_recov(syndrome_disks+2,
1338 						       STRIPE_SIZE, faila,
1339 						       blocks, &submit);
1340 		} else {
1341 			/* We're missing D+D. */
1342 			return async_raid6_2data_recov(syndrome_disks+2,
1343 						       STRIPE_SIZE, faila, failb,
1344 						       blocks, &submit);
1345 		}
1346 	}
1347 }
1348 
ops_complete_prexor(void * stripe_head_ref)1349 static void ops_complete_prexor(void *stripe_head_ref)
1350 {
1351 	struct stripe_head *sh = stripe_head_ref;
1352 
1353 	pr_debug("%s: stripe %llu\n", __func__,
1354 		(unsigned long long)sh->sector);
1355 }
1356 
1357 static struct dma_async_tx_descriptor *
ops_run_prexor(struct stripe_head * sh,struct raid5_percpu * percpu,struct dma_async_tx_descriptor * tx)1358 ops_run_prexor(struct stripe_head *sh, struct raid5_percpu *percpu,
1359 	       struct dma_async_tx_descriptor *tx)
1360 {
1361 	int disks = sh->disks;
1362 	struct page **xor_srcs = percpu->scribble;
1363 	int count = 0, pd_idx = sh->pd_idx, i;
1364 	struct async_submit_ctl submit;
1365 
1366 	/* existing parity data subtracted */
1367 	struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1368 
1369 	pr_debug("%s: stripe %llu\n", __func__,
1370 		(unsigned long long)sh->sector);
1371 
1372 	for (i = disks; i--; ) {
1373 		struct r5dev *dev = &sh->dev[i];
1374 		/* Only process blocks that are known to be uptodate */
1375 		if (test_bit(R5_Wantdrain, &dev->flags))
1376 			xor_srcs[count++] = dev->page;
1377 	}
1378 
1379 	init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1380 			  ops_complete_prexor, sh, to_addr_conv(sh, percpu));
1381 	tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1382 
1383 	return tx;
1384 }
1385 
1386 static struct dma_async_tx_descriptor *
ops_run_biodrain(struct stripe_head * sh,struct dma_async_tx_descriptor * tx)1387 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1388 {
1389 	int disks = sh->disks;
1390 	int i;
1391 
1392 	pr_debug("%s: stripe %llu\n", __func__,
1393 		(unsigned long long)sh->sector);
1394 
1395 	for (i = disks; i--; ) {
1396 		struct r5dev *dev = &sh->dev[i];
1397 		struct bio *chosen;
1398 
1399 		if (test_and_clear_bit(R5_Wantdrain, &dev->flags)) {
1400 			struct bio *wbi;
1401 
1402 			spin_lock_irq(&sh->stripe_lock);
1403 			chosen = dev->towrite;
1404 			dev->towrite = NULL;
1405 			BUG_ON(dev->written);
1406 			wbi = dev->written = chosen;
1407 			spin_unlock_irq(&sh->stripe_lock);
1408 			WARN_ON(dev->page != dev->orig_page);
1409 
1410 			while (wbi && wbi->bi_iter.bi_sector <
1411 				dev->sector + STRIPE_SECTORS) {
1412 				if (wbi->bi_rw & REQ_FUA)
1413 					set_bit(R5_WantFUA, &dev->flags);
1414 				if (wbi->bi_rw & REQ_SYNC)
1415 					set_bit(R5_SyncIO, &dev->flags);
1416 				if (wbi->bi_rw & REQ_DISCARD)
1417 					set_bit(R5_Discard, &dev->flags);
1418 				else {
1419 					tx = async_copy_data(1, wbi, &dev->page,
1420 						dev->sector, tx, sh);
1421 					if (dev->page != dev->orig_page) {
1422 						set_bit(R5_SkipCopy, &dev->flags);
1423 						clear_bit(R5_UPTODATE, &dev->flags);
1424 						clear_bit(R5_OVERWRITE, &dev->flags);
1425 					}
1426 				}
1427 				wbi = r5_next_bio(wbi, dev->sector);
1428 			}
1429 		}
1430 	}
1431 
1432 	return tx;
1433 }
1434 
ops_complete_reconstruct(void * stripe_head_ref)1435 static void ops_complete_reconstruct(void *stripe_head_ref)
1436 {
1437 	struct stripe_head *sh = stripe_head_ref;
1438 	int disks = sh->disks;
1439 	int pd_idx = sh->pd_idx;
1440 	int qd_idx = sh->qd_idx;
1441 	int i;
1442 	bool fua = false, sync = false, discard = false;
1443 
1444 	pr_debug("%s: stripe %llu\n", __func__,
1445 		(unsigned long long)sh->sector);
1446 
1447 	for (i = disks; i--; ) {
1448 		fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1449 		sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1450 		discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1451 	}
1452 
1453 	for (i = disks; i--; ) {
1454 		struct r5dev *dev = &sh->dev[i];
1455 
1456 		if (dev->written || i == pd_idx || i == qd_idx) {
1457 			if (!discard && !test_bit(R5_SkipCopy, &dev->flags)) {
1458 				set_bit(R5_UPTODATE, &dev->flags);
1459 				if (test_bit(STRIPE_EXPAND_READY, &sh->state))
1460 					set_bit(R5_Expanded, &dev->flags);
1461 			}
1462 			if (fua)
1463 				set_bit(R5_WantFUA, &dev->flags);
1464 			if (sync)
1465 				set_bit(R5_SyncIO, &dev->flags);
1466 		}
1467 	}
1468 
1469 	if (sh->reconstruct_state == reconstruct_state_drain_run)
1470 		sh->reconstruct_state = reconstruct_state_drain_result;
1471 	else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1472 		sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1473 	else {
1474 		BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1475 		sh->reconstruct_state = reconstruct_state_result;
1476 	}
1477 
1478 	set_bit(STRIPE_HANDLE, &sh->state);
1479 	release_stripe(sh);
1480 }
1481 
1482 static void
ops_run_reconstruct5(struct stripe_head * sh,struct raid5_percpu * percpu,struct dma_async_tx_descriptor * tx)1483 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1484 		     struct dma_async_tx_descriptor *tx)
1485 {
1486 	int disks = sh->disks;
1487 	struct page **xor_srcs = percpu->scribble;
1488 	struct async_submit_ctl submit;
1489 	int count = 0, pd_idx = sh->pd_idx, i;
1490 	struct page *xor_dest;
1491 	int prexor = 0;
1492 	unsigned long flags;
1493 
1494 	pr_debug("%s: stripe %llu\n", __func__,
1495 		(unsigned long long)sh->sector);
1496 
1497 	for (i = 0; i < sh->disks; i++) {
1498 		if (pd_idx == i)
1499 			continue;
1500 		if (!test_bit(R5_Discard, &sh->dev[i].flags))
1501 			break;
1502 	}
1503 	if (i >= sh->disks) {
1504 		atomic_inc(&sh->count);
1505 		set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1506 		ops_complete_reconstruct(sh);
1507 		return;
1508 	}
1509 	/* check if prexor is active which means only process blocks
1510 	 * that are part of a read-modify-write (written)
1511 	 */
1512 	if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1513 		prexor = 1;
1514 		xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1515 		for (i = disks; i--; ) {
1516 			struct r5dev *dev = &sh->dev[i];
1517 			if (dev->written)
1518 				xor_srcs[count++] = dev->page;
1519 		}
1520 	} else {
1521 		xor_dest = sh->dev[pd_idx].page;
1522 		for (i = disks; i--; ) {
1523 			struct r5dev *dev = &sh->dev[i];
1524 			if (i != pd_idx)
1525 				xor_srcs[count++] = dev->page;
1526 		}
1527 	}
1528 
1529 	/* 1/ if we prexor'd then the dest is reused as a source
1530 	 * 2/ if we did not prexor then we are redoing the parity
1531 	 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1532 	 * for the synchronous xor case
1533 	 */
1534 	flags = ASYNC_TX_ACK |
1535 		(prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1536 
1537 	atomic_inc(&sh->count);
1538 
1539 	init_async_submit(&submit, flags, tx, ops_complete_reconstruct, sh,
1540 			  to_addr_conv(sh, percpu));
1541 	if (unlikely(count == 1))
1542 		tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1543 	else
1544 		tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1545 }
1546 
1547 static void
ops_run_reconstruct6(struct stripe_head * sh,struct raid5_percpu * percpu,struct dma_async_tx_descriptor * tx)1548 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1549 		     struct dma_async_tx_descriptor *tx)
1550 {
1551 	struct async_submit_ctl submit;
1552 	struct page **blocks = percpu->scribble;
1553 	int count, i;
1554 
1555 	pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1556 
1557 	for (i = 0; i < sh->disks; i++) {
1558 		if (sh->pd_idx == i || sh->qd_idx == i)
1559 			continue;
1560 		if (!test_bit(R5_Discard, &sh->dev[i].flags))
1561 			break;
1562 	}
1563 	if (i >= sh->disks) {
1564 		atomic_inc(&sh->count);
1565 		set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1566 		set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1567 		ops_complete_reconstruct(sh);
1568 		return;
1569 	}
1570 
1571 	count = set_syndrome_sources(blocks, sh);
1572 
1573 	atomic_inc(&sh->count);
1574 
1575 	init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_reconstruct,
1576 			  sh, to_addr_conv(sh, percpu));
1577 	async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE,  &submit);
1578 }
1579 
ops_complete_check(void * stripe_head_ref)1580 static void ops_complete_check(void *stripe_head_ref)
1581 {
1582 	struct stripe_head *sh = stripe_head_ref;
1583 
1584 	pr_debug("%s: stripe %llu\n", __func__,
1585 		(unsigned long long)sh->sector);
1586 
1587 	sh->check_state = check_state_check_result;
1588 	set_bit(STRIPE_HANDLE, &sh->state);
1589 	release_stripe(sh);
1590 }
1591 
ops_run_check_p(struct stripe_head * sh,struct raid5_percpu * percpu)1592 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1593 {
1594 	int disks = sh->disks;
1595 	int pd_idx = sh->pd_idx;
1596 	int qd_idx = sh->qd_idx;
1597 	struct page *xor_dest;
1598 	struct page **xor_srcs = percpu->scribble;
1599 	struct dma_async_tx_descriptor *tx;
1600 	struct async_submit_ctl submit;
1601 	int count;
1602 	int i;
1603 
1604 	pr_debug("%s: stripe %llu\n", __func__,
1605 		(unsigned long long)sh->sector);
1606 
1607 	count = 0;
1608 	xor_dest = sh->dev[pd_idx].page;
1609 	xor_srcs[count++] = xor_dest;
1610 	for (i = disks; i--; ) {
1611 		if (i == pd_idx || i == qd_idx)
1612 			continue;
1613 		xor_srcs[count++] = sh->dev[i].page;
1614 	}
1615 
1616 	init_async_submit(&submit, 0, NULL, NULL, NULL,
1617 			  to_addr_conv(sh, percpu));
1618 	tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
1619 			   &sh->ops.zero_sum_result, &submit);
1620 
1621 	atomic_inc(&sh->count);
1622 	init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
1623 	tx = async_trigger_callback(&submit);
1624 }
1625 
ops_run_check_pq(struct stripe_head * sh,struct raid5_percpu * percpu,int checkp)1626 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
1627 {
1628 	struct page **srcs = percpu->scribble;
1629 	struct async_submit_ctl submit;
1630 	int count;
1631 
1632 	pr_debug("%s: stripe %llu checkp: %d\n", __func__,
1633 		(unsigned long long)sh->sector, checkp);
1634 
1635 	count = set_syndrome_sources(srcs, sh);
1636 	if (!checkp)
1637 		srcs[count] = NULL;
1638 
1639 	atomic_inc(&sh->count);
1640 	init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
1641 			  sh, to_addr_conv(sh, percpu));
1642 	async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
1643 			   &sh->ops.zero_sum_result, percpu->spare_page, &submit);
1644 }
1645 
raid_run_ops(struct stripe_head * sh,unsigned long ops_request)1646 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1647 {
1648 	int overlap_clear = 0, i, disks = sh->disks;
1649 	struct dma_async_tx_descriptor *tx = NULL;
1650 	struct r5conf *conf = sh->raid_conf;
1651 	int level = conf->level;
1652 	struct raid5_percpu *percpu;
1653 	unsigned long cpu;
1654 
1655 	cpu = get_cpu();
1656 	percpu = per_cpu_ptr(conf->percpu, cpu);
1657 	if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
1658 		ops_run_biofill(sh);
1659 		overlap_clear++;
1660 	}
1661 
1662 	if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
1663 		if (level < 6)
1664 			tx = ops_run_compute5(sh, percpu);
1665 		else {
1666 			if (sh->ops.target2 < 0 || sh->ops.target < 0)
1667 				tx = ops_run_compute6_1(sh, percpu);
1668 			else
1669 				tx = ops_run_compute6_2(sh, percpu);
1670 		}
1671 		/* terminate the chain if reconstruct is not set to be run */
1672 		if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
1673 			async_tx_ack(tx);
1674 	}
1675 
1676 	if (test_bit(STRIPE_OP_PREXOR, &ops_request))
1677 		tx = ops_run_prexor(sh, percpu, tx);
1678 
1679 	if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
1680 		tx = ops_run_biodrain(sh, tx);
1681 		overlap_clear++;
1682 	}
1683 
1684 	if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
1685 		if (level < 6)
1686 			ops_run_reconstruct5(sh, percpu, tx);
1687 		else
1688 			ops_run_reconstruct6(sh, percpu, tx);
1689 	}
1690 
1691 	if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
1692 		if (sh->check_state == check_state_run)
1693 			ops_run_check_p(sh, percpu);
1694 		else if (sh->check_state == check_state_run_q)
1695 			ops_run_check_pq(sh, percpu, 0);
1696 		else if (sh->check_state == check_state_run_pq)
1697 			ops_run_check_pq(sh, percpu, 1);
1698 		else
1699 			BUG();
1700 	}
1701 
1702 	if (overlap_clear)
1703 		for (i = disks; i--; ) {
1704 			struct r5dev *dev = &sh->dev[i];
1705 			if (test_and_clear_bit(R5_Overlap, &dev->flags))
1706 				wake_up(&sh->raid_conf->wait_for_overlap);
1707 		}
1708 	put_cpu();
1709 }
1710 
grow_one_stripe(struct r5conf * conf,int hash)1711 static int grow_one_stripe(struct r5conf *conf, int hash)
1712 {
1713 	struct stripe_head *sh;
1714 	sh = kmem_cache_zalloc(conf->slab_cache, GFP_KERNEL);
1715 	if (!sh)
1716 		return 0;
1717 
1718 	sh->raid_conf = conf;
1719 
1720 	spin_lock_init(&sh->stripe_lock);
1721 
1722 	if (grow_buffers(sh)) {
1723 		shrink_buffers(sh);
1724 		kmem_cache_free(conf->slab_cache, sh);
1725 		return 0;
1726 	}
1727 	sh->hash_lock_index = hash;
1728 	/* we just created an active stripe so... */
1729 	atomic_set(&sh->count, 1);
1730 	atomic_inc(&conf->active_stripes);
1731 	INIT_LIST_HEAD(&sh->lru);
1732 	release_stripe(sh);
1733 	return 1;
1734 }
1735 
grow_stripes(struct r5conf * conf,int num)1736 static int grow_stripes(struct r5conf *conf, int num)
1737 {
1738 	struct kmem_cache *sc;
1739 	int devs = max(conf->raid_disks, conf->previous_raid_disks);
1740 	int hash;
1741 
1742 	if (conf->mddev->gendisk)
1743 		sprintf(conf->cache_name[0],
1744 			"raid%d-%s", conf->level, mdname(conf->mddev));
1745 	else
1746 		sprintf(conf->cache_name[0],
1747 			"raid%d-%p", conf->level, conf->mddev);
1748 	sprintf(conf->cache_name[1], "%s-alt", conf->cache_name[0]);
1749 
1750 	conf->active_name = 0;
1751 	sc = kmem_cache_create(conf->cache_name[conf->active_name],
1752 			       sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
1753 			       0, 0, NULL);
1754 	if (!sc)
1755 		return 1;
1756 	conf->slab_cache = sc;
1757 	conf->pool_size = devs;
1758 	hash = conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
1759 	while (num--) {
1760 		if (!grow_one_stripe(conf, hash))
1761 			return 1;
1762 		conf->max_nr_stripes++;
1763 		hash = (hash + 1) % NR_STRIPE_HASH_LOCKS;
1764 	}
1765 	return 0;
1766 }
1767 
1768 /**
1769  * scribble_len - return the required size of the scribble region
1770  * @num - total number of disks in the array
1771  *
1772  * The size must be enough to contain:
1773  * 1/ a struct page pointer for each device in the array +2
1774  * 2/ room to convert each entry in (1) to its corresponding dma
1775  *    (dma_map_page()) or page (page_address()) address.
1776  *
1777  * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
1778  * calculate over all devices (not just the data blocks), using zeros in place
1779  * of the P and Q blocks.
1780  */
scribble_len(int num)1781 static size_t scribble_len(int num)
1782 {
1783 	size_t len;
1784 
1785 	len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
1786 
1787 	return len;
1788 }
1789 
resize_stripes(struct r5conf * conf,int newsize)1790 static int resize_stripes(struct r5conf *conf, int newsize)
1791 {
1792 	/* Make all the stripes able to hold 'newsize' devices.
1793 	 * New slots in each stripe get 'page' set to a new page.
1794 	 *
1795 	 * This happens in stages:
1796 	 * 1/ create a new kmem_cache and allocate the required number of
1797 	 *    stripe_heads.
1798 	 * 2/ gather all the old stripe_heads and transfer the pages across
1799 	 *    to the new stripe_heads.  This will have the side effect of
1800 	 *    freezing the array as once all stripe_heads have been collected,
1801 	 *    no IO will be possible.  Old stripe heads are freed once their
1802 	 *    pages have been transferred over, and the old kmem_cache is
1803 	 *    freed when all stripes are done.
1804 	 * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
1805 	 *    we simple return a failre status - no need to clean anything up.
1806 	 * 4/ allocate new pages for the new slots in the new stripe_heads.
1807 	 *    If this fails, we don't bother trying the shrink the
1808 	 *    stripe_heads down again, we just leave them as they are.
1809 	 *    As each stripe_head is processed the new one is released into
1810 	 *    active service.
1811 	 *
1812 	 * Once step2 is started, we cannot afford to wait for a write,
1813 	 * so we use GFP_NOIO allocations.
1814 	 */
1815 	struct stripe_head *osh, *nsh;
1816 	LIST_HEAD(newstripes);
1817 	struct disk_info *ndisks;
1818 	unsigned long cpu;
1819 	int err;
1820 	struct kmem_cache *sc;
1821 	int i;
1822 	int hash, cnt;
1823 
1824 	if (newsize <= conf->pool_size)
1825 		return 0; /* never bother to shrink */
1826 
1827 	err = md_allow_write(conf->mddev);
1828 	if (err)
1829 		return err;
1830 
1831 	/* Step 1 */
1832 	sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
1833 			       sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
1834 			       0, 0, NULL);
1835 	if (!sc)
1836 		return -ENOMEM;
1837 
1838 	for (i = conf->max_nr_stripes; i; i--) {
1839 		nsh = kmem_cache_zalloc(sc, GFP_KERNEL);
1840 		if (!nsh)
1841 			break;
1842 
1843 		nsh->raid_conf = conf;
1844 		spin_lock_init(&nsh->stripe_lock);
1845 
1846 		list_add(&nsh->lru, &newstripes);
1847 	}
1848 	if (i) {
1849 		/* didn't get enough, give up */
1850 		while (!list_empty(&newstripes)) {
1851 			nsh = list_entry(newstripes.next, struct stripe_head, lru);
1852 			list_del(&nsh->lru);
1853 			kmem_cache_free(sc, nsh);
1854 		}
1855 		kmem_cache_destroy(sc);
1856 		return -ENOMEM;
1857 	}
1858 	/* Step 2 - Must use GFP_NOIO now.
1859 	 * OK, we have enough stripes, start collecting inactive
1860 	 * stripes and copying them over
1861 	 */
1862 	hash = 0;
1863 	cnt = 0;
1864 	list_for_each_entry(nsh, &newstripes, lru) {
1865 		lock_device_hash_lock(conf, hash);
1866 		wait_event_cmd(conf->wait_for_stripe,
1867 				    !list_empty(conf->inactive_list + hash),
1868 				    unlock_device_hash_lock(conf, hash),
1869 				    lock_device_hash_lock(conf, hash));
1870 		osh = get_free_stripe(conf, hash);
1871 		unlock_device_hash_lock(conf, hash);
1872 		atomic_set(&nsh->count, 1);
1873 		for(i=0; i<conf->pool_size; i++) {
1874 			nsh->dev[i].page = osh->dev[i].page;
1875 			nsh->dev[i].orig_page = osh->dev[i].page;
1876 		}
1877 		for( ; i<newsize; i++)
1878 			nsh->dev[i].page = NULL;
1879 		nsh->hash_lock_index = hash;
1880 		kmem_cache_free(conf->slab_cache, osh);
1881 		cnt++;
1882 		if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
1883 		    !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
1884 			hash++;
1885 			cnt = 0;
1886 		}
1887 	}
1888 	kmem_cache_destroy(conf->slab_cache);
1889 
1890 	/* Step 3.
1891 	 * At this point, we are holding all the stripes so the array
1892 	 * is completely stalled, so now is a good time to resize
1893 	 * conf->disks and the scribble region
1894 	 */
1895 	ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
1896 	if (ndisks) {
1897 		for (i=0; i<conf->raid_disks; i++)
1898 			ndisks[i] = conf->disks[i];
1899 		kfree(conf->disks);
1900 		conf->disks = ndisks;
1901 	} else
1902 		err = -ENOMEM;
1903 
1904 	get_online_cpus();
1905 	conf->scribble_len = scribble_len(newsize);
1906 	for_each_present_cpu(cpu) {
1907 		struct raid5_percpu *percpu;
1908 		void *scribble;
1909 
1910 		percpu = per_cpu_ptr(conf->percpu, cpu);
1911 		scribble = kmalloc(conf->scribble_len, GFP_NOIO);
1912 
1913 		if (scribble) {
1914 			kfree(percpu->scribble);
1915 			percpu->scribble = scribble;
1916 		} else {
1917 			err = -ENOMEM;
1918 			break;
1919 		}
1920 	}
1921 	put_online_cpus();
1922 
1923 	/* Step 4, return new stripes to service */
1924 	while(!list_empty(&newstripes)) {
1925 		nsh = list_entry(newstripes.next, struct stripe_head, lru);
1926 		list_del_init(&nsh->lru);
1927 
1928 		for (i=conf->raid_disks; i < newsize; i++)
1929 			if (nsh->dev[i].page == NULL) {
1930 				struct page *p = alloc_page(GFP_NOIO);
1931 				nsh->dev[i].page = p;
1932 				nsh->dev[i].orig_page = p;
1933 				if (!p)
1934 					err = -ENOMEM;
1935 			}
1936 		release_stripe(nsh);
1937 	}
1938 	/* critical section pass, GFP_NOIO no longer needed */
1939 
1940 	conf->slab_cache = sc;
1941 	conf->active_name = 1-conf->active_name;
1942 	if (!err)
1943 		conf->pool_size = newsize;
1944 	return err;
1945 }
1946 
drop_one_stripe(struct r5conf * conf,int hash)1947 static int drop_one_stripe(struct r5conf *conf, int hash)
1948 {
1949 	struct stripe_head *sh;
1950 
1951 	spin_lock_irq(conf->hash_locks + hash);
1952 	sh = get_free_stripe(conf, hash);
1953 	spin_unlock_irq(conf->hash_locks + hash);
1954 	if (!sh)
1955 		return 0;
1956 	BUG_ON(atomic_read(&sh->count));
1957 	shrink_buffers(sh);
1958 	kmem_cache_free(conf->slab_cache, sh);
1959 	atomic_dec(&conf->active_stripes);
1960 	return 1;
1961 }
1962 
shrink_stripes(struct r5conf * conf)1963 static void shrink_stripes(struct r5conf *conf)
1964 {
1965 	int hash;
1966 	for (hash = 0; hash < NR_STRIPE_HASH_LOCKS; hash++)
1967 		while (drop_one_stripe(conf, hash))
1968 			;
1969 
1970 	if (conf->slab_cache)
1971 		kmem_cache_destroy(conf->slab_cache);
1972 	conf->slab_cache = NULL;
1973 }
1974 
raid5_end_read_request(struct bio * bi,int error)1975 static void raid5_end_read_request(struct bio * bi, int error)
1976 {
1977 	struct stripe_head *sh = bi->bi_private;
1978 	struct r5conf *conf = sh->raid_conf;
1979 	int disks = sh->disks, i;
1980 	int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1981 	char b[BDEVNAME_SIZE];
1982 	struct md_rdev *rdev = NULL;
1983 	sector_t s;
1984 
1985 	for (i=0 ; i<disks; i++)
1986 		if (bi == &sh->dev[i].req)
1987 			break;
1988 
1989 	pr_debug("end_read_request %llu/%d, count: %d, uptodate %d.\n",
1990 		(unsigned long long)sh->sector, i, atomic_read(&sh->count),
1991 		uptodate);
1992 	if (i == disks) {
1993 		BUG();
1994 		return;
1995 	}
1996 	if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
1997 		/* If replacement finished while this request was outstanding,
1998 		 * 'replacement' might be NULL already.
1999 		 * In that case it moved down to 'rdev'.
2000 		 * rdev is not removed until all requests are finished.
2001 		 */
2002 		rdev = conf->disks[i].replacement;
2003 	if (!rdev)
2004 		rdev = conf->disks[i].rdev;
2005 
2006 	if (use_new_offset(conf, sh))
2007 		s = sh->sector + rdev->new_data_offset;
2008 	else
2009 		s = sh->sector + rdev->data_offset;
2010 	if (uptodate) {
2011 		set_bit(R5_UPTODATE, &sh->dev[i].flags);
2012 		if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2013 			/* Note that this cannot happen on a
2014 			 * replacement device.  We just fail those on
2015 			 * any error
2016 			 */
2017 			printk_ratelimited(
2018 				KERN_INFO
2019 				"md/raid:%s: read error corrected"
2020 				" (%lu sectors at %llu on %s)\n",
2021 				mdname(conf->mddev), STRIPE_SECTORS,
2022 				(unsigned long long)s,
2023 				bdevname(rdev->bdev, b));
2024 			atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2025 			clear_bit(R5_ReadError, &sh->dev[i].flags);
2026 			clear_bit(R5_ReWrite, &sh->dev[i].flags);
2027 		} else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2028 			clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2029 
2030 		if (atomic_read(&rdev->read_errors))
2031 			atomic_set(&rdev->read_errors, 0);
2032 	} else {
2033 		const char *bdn = bdevname(rdev->bdev, b);
2034 		int retry = 0;
2035 		int set_bad = 0;
2036 
2037 		clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2038 		atomic_inc(&rdev->read_errors);
2039 		if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2040 			printk_ratelimited(
2041 				KERN_WARNING
2042 				"md/raid:%s: read error on replacement device "
2043 				"(sector %llu on %s).\n",
2044 				mdname(conf->mddev),
2045 				(unsigned long long)s,
2046 				bdn);
2047 		else if (conf->mddev->degraded >= conf->max_degraded) {
2048 			set_bad = 1;
2049 			printk_ratelimited(
2050 				KERN_WARNING
2051 				"md/raid:%s: read error not correctable "
2052 				"(sector %llu on %s).\n",
2053 				mdname(conf->mddev),
2054 				(unsigned long long)s,
2055 				bdn);
2056 		} else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2057 			/* Oh, no!!! */
2058 			set_bad = 1;
2059 			printk_ratelimited(
2060 				KERN_WARNING
2061 				"md/raid:%s: read error NOT corrected!! "
2062 				"(sector %llu on %s).\n",
2063 				mdname(conf->mddev),
2064 				(unsigned long long)s,
2065 				bdn);
2066 		} else if (atomic_read(&rdev->read_errors)
2067 			 > conf->max_nr_stripes)
2068 			printk(KERN_WARNING
2069 			       "md/raid:%s: Too many read errors, failing device %s.\n",
2070 			       mdname(conf->mddev), bdn);
2071 		else
2072 			retry = 1;
2073 		if (set_bad && test_bit(In_sync, &rdev->flags)
2074 		    && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2075 			retry = 1;
2076 		if (retry)
2077 			if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2078 				set_bit(R5_ReadError, &sh->dev[i].flags);
2079 				clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2080 			} else
2081 				set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2082 		else {
2083 			clear_bit(R5_ReadError, &sh->dev[i].flags);
2084 			clear_bit(R5_ReWrite, &sh->dev[i].flags);
2085 			if (!(set_bad
2086 			      && test_bit(In_sync, &rdev->flags)
2087 			      && rdev_set_badblocks(
2088 				      rdev, sh->sector, STRIPE_SECTORS, 0)))
2089 				md_error(conf->mddev, rdev);
2090 		}
2091 	}
2092 	rdev_dec_pending(rdev, conf->mddev);
2093 	clear_bit(R5_LOCKED, &sh->dev[i].flags);
2094 	set_bit(STRIPE_HANDLE, &sh->state);
2095 	release_stripe(sh);
2096 }
2097 
raid5_end_write_request(struct bio * bi,int error)2098 static void raid5_end_write_request(struct bio *bi, int error)
2099 {
2100 	struct stripe_head *sh = bi->bi_private;
2101 	struct r5conf *conf = sh->raid_conf;
2102 	int disks = sh->disks, i;
2103 	struct md_rdev *uninitialized_var(rdev);
2104 	int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
2105 	sector_t first_bad;
2106 	int bad_sectors;
2107 	int replacement = 0;
2108 
2109 	for (i = 0 ; i < disks; i++) {
2110 		if (bi == &sh->dev[i].req) {
2111 			rdev = conf->disks[i].rdev;
2112 			break;
2113 		}
2114 		if (bi == &sh->dev[i].rreq) {
2115 			rdev = conf->disks[i].replacement;
2116 			if (rdev)
2117 				replacement = 1;
2118 			else
2119 				/* rdev was removed and 'replacement'
2120 				 * replaced it.  rdev is not removed
2121 				 * until all requests are finished.
2122 				 */
2123 				rdev = conf->disks[i].rdev;
2124 			break;
2125 		}
2126 	}
2127 	pr_debug("end_write_request %llu/%d, count %d, uptodate: %d.\n",
2128 		(unsigned long long)sh->sector, i, atomic_read(&sh->count),
2129 		uptodate);
2130 	if (i == disks) {
2131 		BUG();
2132 		return;
2133 	}
2134 
2135 	if (replacement) {
2136 		if (!uptodate)
2137 			md_error(conf->mddev, rdev);
2138 		else if (is_badblock(rdev, sh->sector,
2139 				     STRIPE_SECTORS,
2140 				     &first_bad, &bad_sectors))
2141 			set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2142 	} else {
2143 		if (!uptodate) {
2144 			set_bit(STRIPE_DEGRADED, &sh->state);
2145 			set_bit(WriteErrorSeen, &rdev->flags);
2146 			set_bit(R5_WriteError, &sh->dev[i].flags);
2147 			if (!test_and_set_bit(WantReplacement, &rdev->flags))
2148 				set_bit(MD_RECOVERY_NEEDED,
2149 					&rdev->mddev->recovery);
2150 		} else if (is_badblock(rdev, sh->sector,
2151 				       STRIPE_SECTORS,
2152 				       &first_bad, &bad_sectors)) {
2153 			set_bit(R5_MadeGood, &sh->dev[i].flags);
2154 			if (test_bit(R5_ReadError, &sh->dev[i].flags))
2155 				/* That was a successful write so make
2156 				 * sure it looks like we already did
2157 				 * a re-write.
2158 				 */
2159 				set_bit(R5_ReWrite, &sh->dev[i].flags);
2160 		}
2161 	}
2162 	rdev_dec_pending(rdev, conf->mddev);
2163 
2164 	if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2165 		clear_bit(R5_LOCKED, &sh->dev[i].flags);
2166 	set_bit(STRIPE_HANDLE, &sh->state);
2167 	release_stripe(sh);
2168 }
2169 
2170 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous);
2171 
raid5_build_block(struct stripe_head * sh,int i,int previous)2172 static void raid5_build_block(struct stripe_head *sh, int i, int previous)
2173 {
2174 	struct r5dev *dev = &sh->dev[i];
2175 
2176 	bio_init(&dev->req);
2177 	dev->req.bi_io_vec = &dev->vec;
2178 	dev->req.bi_max_vecs = 1;
2179 	dev->req.bi_private = sh;
2180 
2181 	bio_init(&dev->rreq);
2182 	dev->rreq.bi_io_vec = &dev->rvec;
2183 	dev->rreq.bi_max_vecs = 1;
2184 	dev->rreq.bi_private = sh;
2185 
2186 	dev->flags = 0;
2187 	dev->sector = compute_blocknr(sh, i, previous);
2188 }
2189 
error(struct mddev * mddev,struct md_rdev * rdev)2190 static void error(struct mddev *mddev, struct md_rdev *rdev)
2191 {
2192 	char b[BDEVNAME_SIZE];
2193 	struct r5conf *conf = mddev->private;
2194 	unsigned long flags;
2195 	pr_debug("raid456: error called\n");
2196 
2197 	spin_lock_irqsave(&conf->device_lock, flags);
2198 	clear_bit(In_sync, &rdev->flags);
2199 	mddev->degraded = calc_degraded(conf);
2200 	spin_unlock_irqrestore(&conf->device_lock, flags);
2201 	set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2202 
2203 	set_bit(Blocked, &rdev->flags);
2204 	set_bit(Faulty, &rdev->flags);
2205 	set_bit(MD_CHANGE_DEVS, &mddev->flags);
2206 	printk(KERN_ALERT
2207 	       "md/raid:%s: Disk failure on %s, disabling device.\n"
2208 	       "md/raid:%s: Operation continuing on %d devices.\n",
2209 	       mdname(mddev),
2210 	       bdevname(rdev->bdev, b),
2211 	       mdname(mddev),
2212 	       conf->raid_disks - mddev->degraded);
2213 }
2214 
2215 /*
2216  * Input: a 'big' sector number,
2217  * Output: index of the data and parity disk, and the sector # in them.
2218  */
raid5_compute_sector(struct r5conf * conf,sector_t r_sector,int previous,int * dd_idx,struct stripe_head * sh)2219 static sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2220 				     int previous, int *dd_idx,
2221 				     struct stripe_head *sh)
2222 {
2223 	sector_t stripe, stripe2;
2224 	sector_t chunk_number;
2225 	unsigned int chunk_offset;
2226 	int pd_idx, qd_idx;
2227 	int ddf_layout = 0;
2228 	sector_t new_sector;
2229 	int algorithm = previous ? conf->prev_algo
2230 				 : conf->algorithm;
2231 	int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2232 					 : conf->chunk_sectors;
2233 	int raid_disks = previous ? conf->previous_raid_disks
2234 				  : conf->raid_disks;
2235 	int data_disks = raid_disks - conf->max_degraded;
2236 
2237 	/* First compute the information on this sector */
2238 
2239 	/*
2240 	 * Compute the chunk number and the sector offset inside the chunk
2241 	 */
2242 	chunk_offset = sector_div(r_sector, sectors_per_chunk);
2243 	chunk_number = r_sector;
2244 
2245 	/*
2246 	 * Compute the stripe number
2247 	 */
2248 	stripe = chunk_number;
2249 	*dd_idx = sector_div(stripe, data_disks);
2250 	stripe2 = stripe;
2251 	/*
2252 	 * Select the parity disk based on the user selected algorithm.
2253 	 */
2254 	pd_idx = qd_idx = -1;
2255 	switch(conf->level) {
2256 	case 4:
2257 		pd_idx = data_disks;
2258 		break;
2259 	case 5:
2260 		switch (algorithm) {
2261 		case ALGORITHM_LEFT_ASYMMETRIC:
2262 			pd_idx = data_disks - sector_div(stripe2, raid_disks);
2263 			if (*dd_idx >= pd_idx)
2264 				(*dd_idx)++;
2265 			break;
2266 		case ALGORITHM_RIGHT_ASYMMETRIC:
2267 			pd_idx = sector_div(stripe2, raid_disks);
2268 			if (*dd_idx >= pd_idx)
2269 				(*dd_idx)++;
2270 			break;
2271 		case ALGORITHM_LEFT_SYMMETRIC:
2272 			pd_idx = data_disks - sector_div(stripe2, raid_disks);
2273 			*dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2274 			break;
2275 		case ALGORITHM_RIGHT_SYMMETRIC:
2276 			pd_idx = sector_div(stripe2, raid_disks);
2277 			*dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2278 			break;
2279 		case ALGORITHM_PARITY_0:
2280 			pd_idx = 0;
2281 			(*dd_idx)++;
2282 			break;
2283 		case ALGORITHM_PARITY_N:
2284 			pd_idx = data_disks;
2285 			break;
2286 		default:
2287 			BUG();
2288 		}
2289 		break;
2290 	case 6:
2291 
2292 		switch (algorithm) {
2293 		case ALGORITHM_LEFT_ASYMMETRIC:
2294 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2295 			qd_idx = pd_idx + 1;
2296 			if (pd_idx == raid_disks-1) {
2297 				(*dd_idx)++;	/* Q D D D P */
2298 				qd_idx = 0;
2299 			} else if (*dd_idx >= pd_idx)
2300 				(*dd_idx) += 2; /* D D P Q D */
2301 			break;
2302 		case ALGORITHM_RIGHT_ASYMMETRIC:
2303 			pd_idx = sector_div(stripe2, raid_disks);
2304 			qd_idx = pd_idx + 1;
2305 			if (pd_idx == raid_disks-1) {
2306 				(*dd_idx)++;	/* Q D D D P */
2307 				qd_idx = 0;
2308 			} else if (*dd_idx >= pd_idx)
2309 				(*dd_idx) += 2; /* D D P Q D */
2310 			break;
2311 		case ALGORITHM_LEFT_SYMMETRIC:
2312 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2313 			qd_idx = (pd_idx + 1) % raid_disks;
2314 			*dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2315 			break;
2316 		case ALGORITHM_RIGHT_SYMMETRIC:
2317 			pd_idx = sector_div(stripe2, raid_disks);
2318 			qd_idx = (pd_idx + 1) % raid_disks;
2319 			*dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2320 			break;
2321 
2322 		case ALGORITHM_PARITY_0:
2323 			pd_idx = 0;
2324 			qd_idx = 1;
2325 			(*dd_idx) += 2;
2326 			break;
2327 		case ALGORITHM_PARITY_N:
2328 			pd_idx = data_disks;
2329 			qd_idx = data_disks + 1;
2330 			break;
2331 
2332 		case ALGORITHM_ROTATING_ZERO_RESTART:
2333 			/* Exactly the same as RIGHT_ASYMMETRIC, but or
2334 			 * of blocks for computing Q is different.
2335 			 */
2336 			pd_idx = sector_div(stripe2, raid_disks);
2337 			qd_idx = pd_idx + 1;
2338 			if (pd_idx == raid_disks-1) {
2339 				(*dd_idx)++;	/* Q D D D P */
2340 				qd_idx = 0;
2341 			} else if (*dd_idx >= pd_idx)
2342 				(*dd_idx) += 2; /* D D P Q D */
2343 			ddf_layout = 1;
2344 			break;
2345 
2346 		case ALGORITHM_ROTATING_N_RESTART:
2347 			/* Same a left_asymmetric, by first stripe is
2348 			 * D D D P Q  rather than
2349 			 * Q D D D P
2350 			 */
2351 			stripe2 += 1;
2352 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2353 			qd_idx = pd_idx + 1;
2354 			if (pd_idx == raid_disks-1) {
2355 				(*dd_idx)++;	/* Q D D D P */
2356 				qd_idx = 0;
2357 			} else if (*dd_idx >= pd_idx)
2358 				(*dd_idx) += 2; /* D D P Q D */
2359 			ddf_layout = 1;
2360 			break;
2361 
2362 		case ALGORITHM_ROTATING_N_CONTINUE:
2363 			/* Same as left_symmetric but Q is before P */
2364 			pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2365 			qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2366 			*dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2367 			ddf_layout = 1;
2368 			break;
2369 
2370 		case ALGORITHM_LEFT_ASYMMETRIC_6:
2371 			/* RAID5 left_asymmetric, with Q on last device */
2372 			pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2373 			if (*dd_idx >= pd_idx)
2374 				(*dd_idx)++;
2375 			qd_idx = raid_disks - 1;
2376 			break;
2377 
2378 		case ALGORITHM_RIGHT_ASYMMETRIC_6:
2379 			pd_idx = sector_div(stripe2, raid_disks-1);
2380 			if (*dd_idx >= pd_idx)
2381 				(*dd_idx)++;
2382 			qd_idx = raid_disks - 1;
2383 			break;
2384 
2385 		case ALGORITHM_LEFT_SYMMETRIC_6:
2386 			pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2387 			*dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2388 			qd_idx = raid_disks - 1;
2389 			break;
2390 
2391 		case ALGORITHM_RIGHT_SYMMETRIC_6:
2392 			pd_idx = sector_div(stripe2, raid_disks-1);
2393 			*dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2394 			qd_idx = raid_disks - 1;
2395 			break;
2396 
2397 		case ALGORITHM_PARITY_0_6:
2398 			pd_idx = 0;
2399 			(*dd_idx)++;
2400 			qd_idx = raid_disks - 1;
2401 			break;
2402 
2403 		default:
2404 			BUG();
2405 		}
2406 		break;
2407 	}
2408 
2409 	if (sh) {
2410 		sh->pd_idx = pd_idx;
2411 		sh->qd_idx = qd_idx;
2412 		sh->ddf_layout = ddf_layout;
2413 	}
2414 	/*
2415 	 * Finally, compute the new sector number
2416 	 */
2417 	new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2418 	return new_sector;
2419 }
2420 
compute_blocknr(struct stripe_head * sh,int i,int previous)2421 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous)
2422 {
2423 	struct r5conf *conf = sh->raid_conf;
2424 	int raid_disks = sh->disks;
2425 	int data_disks = raid_disks - conf->max_degraded;
2426 	sector_t new_sector = sh->sector, check;
2427 	int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2428 					 : conf->chunk_sectors;
2429 	int algorithm = previous ? conf->prev_algo
2430 				 : conf->algorithm;
2431 	sector_t stripe;
2432 	int chunk_offset;
2433 	sector_t chunk_number;
2434 	int dummy1, dd_idx = i;
2435 	sector_t r_sector;
2436 	struct stripe_head sh2;
2437 
2438 	chunk_offset = sector_div(new_sector, sectors_per_chunk);
2439 	stripe = new_sector;
2440 
2441 	if (i == sh->pd_idx)
2442 		return 0;
2443 	switch(conf->level) {
2444 	case 4: break;
2445 	case 5:
2446 		switch (algorithm) {
2447 		case ALGORITHM_LEFT_ASYMMETRIC:
2448 		case ALGORITHM_RIGHT_ASYMMETRIC:
2449 			if (i > sh->pd_idx)
2450 				i--;
2451 			break;
2452 		case ALGORITHM_LEFT_SYMMETRIC:
2453 		case ALGORITHM_RIGHT_SYMMETRIC:
2454 			if (i < sh->pd_idx)
2455 				i += raid_disks;
2456 			i -= (sh->pd_idx + 1);
2457 			break;
2458 		case ALGORITHM_PARITY_0:
2459 			i -= 1;
2460 			break;
2461 		case ALGORITHM_PARITY_N:
2462 			break;
2463 		default:
2464 			BUG();
2465 		}
2466 		break;
2467 	case 6:
2468 		if (i == sh->qd_idx)
2469 			return 0; /* It is the Q disk */
2470 		switch (algorithm) {
2471 		case ALGORITHM_LEFT_ASYMMETRIC:
2472 		case ALGORITHM_RIGHT_ASYMMETRIC:
2473 		case ALGORITHM_ROTATING_ZERO_RESTART:
2474 		case ALGORITHM_ROTATING_N_RESTART:
2475 			if (sh->pd_idx == raid_disks-1)
2476 				i--;	/* Q D D D P */
2477 			else if (i > sh->pd_idx)
2478 				i -= 2; /* D D P Q D */
2479 			break;
2480 		case ALGORITHM_LEFT_SYMMETRIC:
2481 		case ALGORITHM_RIGHT_SYMMETRIC:
2482 			if (sh->pd_idx == raid_disks-1)
2483 				i--; /* Q D D D P */
2484 			else {
2485 				/* D D P Q D */
2486 				if (i < sh->pd_idx)
2487 					i += raid_disks;
2488 				i -= (sh->pd_idx + 2);
2489 			}
2490 			break;
2491 		case ALGORITHM_PARITY_0:
2492 			i -= 2;
2493 			break;
2494 		case ALGORITHM_PARITY_N:
2495 			break;
2496 		case ALGORITHM_ROTATING_N_CONTINUE:
2497 			/* Like left_symmetric, but P is before Q */
2498 			if (sh->pd_idx == 0)
2499 				i--;	/* P D D D Q */
2500 			else {
2501 				/* D D Q P D */
2502 				if (i < sh->pd_idx)
2503 					i += raid_disks;
2504 				i -= (sh->pd_idx + 1);
2505 			}
2506 			break;
2507 		case ALGORITHM_LEFT_ASYMMETRIC_6:
2508 		case ALGORITHM_RIGHT_ASYMMETRIC_6:
2509 			if (i > sh->pd_idx)
2510 				i--;
2511 			break;
2512 		case ALGORITHM_LEFT_SYMMETRIC_6:
2513 		case ALGORITHM_RIGHT_SYMMETRIC_6:
2514 			if (i < sh->pd_idx)
2515 				i += data_disks + 1;
2516 			i -= (sh->pd_idx + 1);
2517 			break;
2518 		case ALGORITHM_PARITY_0_6:
2519 			i -= 1;
2520 			break;
2521 		default:
2522 			BUG();
2523 		}
2524 		break;
2525 	}
2526 
2527 	chunk_number = stripe * data_disks + i;
2528 	r_sector = chunk_number * sectors_per_chunk + chunk_offset;
2529 
2530 	check = raid5_compute_sector(conf, r_sector,
2531 				     previous, &dummy1, &sh2);
2532 	if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
2533 		|| sh2.qd_idx != sh->qd_idx) {
2534 		printk(KERN_ERR "md/raid:%s: compute_blocknr: map not correct\n",
2535 		       mdname(conf->mddev));
2536 		return 0;
2537 	}
2538 	return r_sector;
2539 }
2540 
2541 static void
schedule_reconstruction(struct stripe_head * sh,struct stripe_head_state * s,int rcw,int expand)2542 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
2543 			 int rcw, int expand)
2544 {
2545 	int i, pd_idx = sh->pd_idx, disks = sh->disks;
2546 	struct r5conf *conf = sh->raid_conf;
2547 	int level = conf->level;
2548 
2549 	if (rcw) {
2550 
2551 		for (i = disks; i--; ) {
2552 			struct r5dev *dev = &sh->dev[i];
2553 
2554 			if (dev->towrite) {
2555 				set_bit(R5_LOCKED, &dev->flags);
2556 				set_bit(R5_Wantdrain, &dev->flags);
2557 				if (!expand)
2558 					clear_bit(R5_UPTODATE, &dev->flags);
2559 				s->locked++;
2560 			}
2561 		}
2562 		/* if we are not expanding this is a proper write request, and
2563 		 * there will be bios with new data to be drained into the
2564 		 * stripe cache
2565 		 */
2566 		if (!expand) {
2567 			if (!s->locked)
2568 				/* False alarm, nothing to do */
2569 				return;
2570 			sh->reconstruct_state = reconstruct_state_drain_run;
2571 			set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2572 		} else
2573 			sh->reconstruct_state = reconstruct_state_run;
2574 
2575 		set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2576 
2577 		if (s->locked + conf->max_degraded == disks)
2578 			if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
2579 				atomic_inc(&conf->pending_full_writes);
2580 	} else {
2581 		BUG_ON(level == 6);
2582 		BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
2583 			test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
2584 
2585 		for (i = disks; i--; ) {
2586 			struct r5dev *dev = &sh->dev[i];
2587 			if (i == pd_idx)
2588 				continue;
2589 
2590 			if (dev->towrite &&
2591 			    (test_bit(R5_UPTODATE, &dev->flags) ||
2592 			     test_bit(R5_Wantcompute, &dev->flags))) {
2593 				set_bit(R5_Wantdrain, &dev->flags);
2594 				set_bit(R5_LOCKED, &dev->flags);
2595 				clear_bit(R5_UPTODATE, &dev->flags);
2596 				s->locked++;
2597 			}
2598 		}
2599 		if (!s->locked)
2600 			/* False alarm - nothing to do */
2601 			return;
2602 		sh->reconstruct_state = reconstruct_state_prexor_drain_run;
2603 		set_bit(STRIPE_OP_PREXOR, &s->ops_request);
2604 		set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2605 		set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2606 	}
2607 
2608 	/* keep the parity disk(s) locked while asynchronous operations
2609 	 * are in flight
2610 	 */
2611 	set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
2612 	clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2613 	s->locked++;
2614 
2615 	if (level == 6) {
2616 		int qd_idx = sh->qd_idx;
2617 		struct r5dev *dev = &sh->dev[qd_idx];
2618 
2619 		set_bit(R5_LOCKED, &dev->flags);
2620 		clear_bit(R5_UPTODATE, &dev->flags);
2621 		s->locked++;
2622 	}
2623 
2624 	pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2625 		__func__, (unsigned long long)sh->sector,
2626 		s->locked, s->ops_request);
2627 }
2628 
2629 /*
2630  * Each stripe/dev can have one or more bion attached.
2631  * toread/towrite point to the first in a chain.
2632  * The bi_next chain must be in order.
2633  */
add_stripe_bio(struct stripe_head * sh,struct bio * bi,int dd_idx,int forwrite)2634 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx, int forwrite)
2635 {
2636 	struct bio **bip;
2637 	struct r5conf *conf = sh->raid_conf;
2638 	int firstwrite=0;
2639 
2640 	pr_debug("adding bi b#%llu to stripe s#%llu\n",
2641 		(unsigned long long)bi->bi_iter.bi_sector,
2642 		(unsigned long long)sh->sector);
2643 
2644 	/*
2645 	 * If several bio share a stripe. The bio bi_phys_segments acts as a
2646 	 * reference count to avoid race. The reference count should already be
2647 	 * increased before this function is called (for example, in
2648 	 * make_request()), so other bio sharing this stripe will not free the
2649 	 * stripe. If a stripe is owned by one stripe, the stripe lock will
2650 	 * protect it.
2651 	 */
2652 	spin_lock_irq(&sh->stripe_lock);
2653 	if (forwrite) {
2654 		bip = &sh->dev[dd_idx].towrite;
2655 		if (*bip == NULL)
2656 			firstwrite = 1;
2657 	} else
2658 		bip = &sh->dev[dd_idx].toread;
2659 	while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
2660 		if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
2661 			goto overlap;
2662 		bip = & (*bip)->bi_next;
2663 	}
2664 	if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
2665 		goto overlap;
2666 
2667 	BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
2668 	if (*bip)
2669 		bi->bi_next = *bip;
2670 	*bip = bi;
2671 	raid5_inc_bi_active_stripes(bi);
2672 
2673 	if (forwrite) {
2674 		/* check if page is covered */
2675 		sector_t sector = sh->dev[dd_idx].sector;
2676 		for (bi=sh->dev[dd_idx].towrite;
2677 		     sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
2678 			     bi && bi->bi_iter.bi_sector <= sector;
2679 		     bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
2680 			if (bio_end_sector(bi) >= sector)
2681 				sector = bio_end_sector(bi);
2682 		}
2683 		if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
2684 			set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags);
2685 	}
2686 
2687 	pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
2688 		(unsigned long long)(*bip)->bi_iter.bi_sector,
2689 		(unsigned long long)sh->sector, dd_idx);
2690 	spin_unlock_irq(&sh->stripe_lock);
2691 
2692 	if (conf->mddev->bitmap && firstwrite) {
2693 		bitmap_startwrite(conf->mddev->bitmap, sh->sector,
2694 				  STRIPE_SECTORS, 0);
2695 		sh->bm_seq = conf->seq_flush+1;
2696 		set_bit(STRIPE_BIT_DELAY, &sh->state);
2697 	}
2698 	return 1;
2699 
2700  overlap:
2701 	set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
2702 	spin_unlock_irq(&sh->stripe_lock);
2703 	return 0;
2704 }
2705 
2706 static void end_reshape(struct r5conf *conf);
2707 
stripe_set_idx(sector_t stripe,struct r5conf * conf,int previous,struct stripe_head * sh)2708 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
2709 			    struct stripe_head *sh)
2710 {
2711 	int sectors_per_chunk =
2712 		previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
2713 	int dd_idx;
2714 	int chunk_offset = sector_div(stripe, sectors_per_chunk);
2715 	int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
2716 
2717 	raid5_compute_sector(conf,
2718 			     stripe * (disks - conf->max_degraded)
2719 			     *sectors_per_chunk + chunk_offset,
2720 			     previous,
2721 			     &dd_idx, sh);
2722 }
2723 
2724 static void
handle_failed_stripe(struct r5conf * conf,struct stripe_head * sh,struct stripe_head_state * s,int disks,struct bio ** return_bi)2725 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
2726 				struct stripe_head_state *s, int disks,
2727 				struct bio **return_bi)
2728 {
2729 	int i;
2730 	for (i = disks; i--; ) {
2731 		struct bio *bi;
2732 		int bitmap_end = 0;
2733 
2734 		if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2735 			struct md_rdev *rdev;
2736 			rcu_read_lock();
2737 			rdev = rcu_dereference(conf->disks[i].rdev);
2738 			if (rdev && test_bit(In_sync, &rdev->flags))
2739 				atomic_inc(&rdev->nr_pending);
2740 			else
2741 				rdev = NULL;
2742 			rcu_read_unlock();
2743 			if (rdev) {
2744 				if (!rdev_set_badblocks(
2745 					    rdev,
2746 					    sh->sector,
2747 					    STRIPE_SECTORS, 0))
2748 					md_error(conf->mddev, rdev);
2749 				rdev_dec_pending(rdev, conf->mddev);
2750 			}
2751 		}
2752 		spin_lock_irq(&sh->stripe_lock);
2753 		/* fail all writes first */
2754 		bi = sh->dev[i].towrite;
2755 		sh->dev[i].towrite = NULL;
2756 		spin_unlock_irq(&sh->stripe_lock);
2757 		if (bi)
2758 			bitmap_end = 1;
2759 
2760 		if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2761 			wake_up(&conf->wait_for_overlap);
2762 
2763 		while (bi && bi->bi_iter.bi_sector <
2764 			sh->dev[i].sector + STRIPE_SECTORS) {
2765 			struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
2766 			clear_bit(BIO_UPTODATE, &bi->bi_flags);
2767 			if (!raid5_dec_bi_active_stripes(bi)) {
2768 				md_write_end(conf->mddev);
2769 				bi->bi_next = *return_bi;
2770 				*return_bi = bi;
2771 			}
2772 			bi = nextbi;
2773 		}
2774 		if (bitmap_end)
2775 			bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2776 				STRIPE_SECTORS, 0, 0);
2777 		bitmap_end = 0;
2778 		/* and fail all 'written' */
2779 		bi = sh->dev[i].written;
2780 		sh->dev[i].written = NULL;
2781 		if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
2782 			WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
2783 			sh->dev[i].page = sh->dev[i].orig_page;
2784 		}
2785 
2786 		if (bi) bitmap_end = 1;
2787 		while (bi && bi->bi_iter.bi_sector <
2788 		       sh->dev[i].sector + STRIPE_SECTORS) {
2789 			struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
2790 			clear_bit(BIO_UPTODATE, &bi->bi_flags);
2791 			if (!raid5_dec_bi_active_stripes(bi)) {
2792 				md_write_end(conf->mddev);
2793 				bi->bi_next = *return_bi;
2794 				*return_bi = bi;
2795 			}
2796 			bi = bi2;
2797 		}
2798 
2799 		/* fail any reads if this device is non-operational and
2800 		 * the data has not reached the cache yet.
2801 		 */
2802 		if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
2803 		    (!test_bit(R5_Insync, &sh->dev[i].flags) ||
2804 		      test_bit(R5_ReadError, &sh->dev[i].flags))) {
2805 			spin_lock_irq(&sh->stripe_lock);
2806 			bi = sh->dev[i].toread;
2807 			sh->dev[i].toread = NULL;
2808 			spin_unlock_irq(&sh->stripe_lock);
2809 			if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2810 				wake_up(&conf->wait_for_overlap);
2811 			while (bi && bi->bi_iter.bi_sector <
2812 			       sh->dev[i].sector + STRIPE_SECTORS) {
2813 				struct bio *nextbi =
2814 					r5_next_bio(bi, sh->dev[i].sector);
2815 				clear_bit(BIO_UPTODATE, &bi->bi_flags);
2816 				if (!raid5_dec_bi_active_stripes(bi)) {
2817 					bi->bi_next = *return_bi;
2818 					*return_bi = bi;
2819 				}
2820 				bi = nextbi;
2821 			}
2822 		}
2823 		if (bitmap_end)
2824 			bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2825 					STRIPE_SECTORS, 0, 0);
2826 		/* If we were in the middle of a write the parity block might
2827 		 * still be locked - so just clear all R5_LOCKED flags
2828 		 */
2829 		clear_bit(R5_LOCKED, &sh->dev[i].flags);
2830 	}
2831 
2832 	if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2833 		if (atomic_dec_and_test(&conf->pending_full_writes))
2834 			md_wakeup_thread(conf->mddev->thread);
2835 }
2836 
2837 static void
handle_failed_sync(struct r5conf * conf,struct stripe_head * sh,struct stripe_head_state * s)2838 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
2839 		   struct stripe_head_state *s)
2840 {
2841 	int abort = 0;
2842 	int i;
2843 
2844 	clear_bit(STRIPE_SYNCING, &sh->state);
2845 	if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
2846 		wake_up(&conf->wait_for_overlap);
2847 	s->syncing = 0;
2848 	s->replacing = 0;
2849 	/* There is nothing more to do for sync/check/repair.
2850 	 * Don't even need to abort as that is handled elsewhere
2851 	 * if needed, and not always wanted e.g. if there is a known
2852 	 * bad block here.
2853 	 * For recover/replace we need to record a bad block on all
2854 	 * non-sync devices, or abort the recovery
2855 	 */
2856 	if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
2857 		/* During recovery devices cannot be removed, so
2858 		 * locking and refcounting of rdevs is not needed
2859 		 */
2860 		for (i = 0; i < conf->raid_disks; i++) {
2861 			struct md_rdev *rdev = conf->disks[i].rdev;
2862 			if (rdev
2863 			    && !test_bit(Faulty, &rdev->flags)
2864 			    && !test_bit(In_sync, &rdev->flags)
2865 			    && !rdev_set_badblocks(rdev, sh->sector,
2866 						   STRIPE_SECTORS, 0))
2867 				abort = 1;
2868 			rdev = conf->disks[i].replacement;
2869 			if (rdev
2870 			    && !test_bit(Faulty, &rdev->flags)
2871 			    && !test_bit(In_sync, &rdev->flags)
2872 			    && !rdev_set_badblocks(rdev, sh->sector,
2873 						   STRIPE_SECTORS, 0))
2874 				abort = 1;
2875 		}
2876 		if (abort)
2877 			conf->recovery_disabled =
2878 				conf->mddev->recovery_disabled;
2879 	}
2880 	md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
2881 }
2882 
want_replace(struct stripe_head * sh,int disk_idx)2883 static int want_replace(struct stripe_head *sh, int disk_idx)
2884 {
2885 	struct md_rdev *rdev;
2886 	int rv = 0;
2887 	/* Doing recovery so rcu locking not required */
2888 	rdev = sh->raid_conf->disks[disk_idx].replacement;
2889 	if (rdev
2890 	    && !test_bit(Faulty, &rdev->flags)
2891 	    && !test_bit(In_sync, &rdev->flags)
2892 	    && (rdev->recovery_offset <= sh->sector
2893 		|| rdev->mddev->recovery_cp <= sh->sector))
2894 		rv = 1;
2895 
2896 	return rv;
2897 }
2898 
2899 /* fetch_block - checks the given member device to see if its data needs
2900  * to be read or computed to satisfy a request.
2901  *
2902  * Returns 1 when no more member devices need to be checked, otherwise returns
2903  * 0 to tell the loop in handle_stripe_fill to continue
2904  */
fetch_block(struct stripe_head * sh,struct stripe_head_state * s,int disk_idx,int disks)2905 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
2906 		       int disk_idx, int disks)
2907 {
2908 	struct r5dev *dev = &sh->dev[disk_idx];
2909 	struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
2910 				  &sh->dev[s->failed_num[1]] };
2911 
2912 	/* is the data in this block needed, and can we get it? */
2913 	if (!test_bit(R5_LOCKED, &dev->flags) &&
2914 	    !test_bit(R5_UPTODATE, &dev->flags) &&
2915 	    (dev->toread ||
2916 	     (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
2917 	     s->syncing || s->expanding ||
2918 	     (s->replacing && want_replace(sh, disk_idx)) ||
2919 	     (s->failed >= 1 && fdev[0]->toread) ||
2920 	     (s->failed >= 2 && fdev[1]->toread) ||
2921 	     (sh->raid_conf->level <= 5 && s->failed && fdev[0]->towrite &&
2922 	      (!test_bit(R5_Insync, &dev->flags) || test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) &&
2923 	      !test_bit(R5_OVERWRITE, &fdev[0]->flags)) ||
2924 	     ((sh->raid_conf->level == 6 ||
2925 	       sh->sector >= sh->raid_conf->mddev->recovery_cp)
2926 	      && s->failed && s->to_write &&
2927 	      (s->to_write - s->non_overwrite <
2928 	       sh->raid_conf->raid_disks - sh->raid_conf->max_degraded) &&
2929 	      (!test_bit(R5_Insync, &dev->flags) || test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))))) {
2930 		/* we would like to get this block, possibly by computing it,
2931 		 * otherwise read it if the backing disk is insync
2932 		 */
2933 		BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
2934 		BUG_ON(test_bit(R5_Wantread, &dev->flags));
2935 		if ((s->uptodate == disks - 1) &&
2936 		    (s->failed && (disk_idx == s->failed_num[0] ||
2937 				   disk_idx == s->failed_num[1]))) {
2938 			/* have disk failed, and we're requested to fetch it;
2939 			 * do compute it
2940 			 */
2941 			pr_debug("Computing stripe %llu block %d\n",
2942 			       (unsigned long long)sh->sector, disk_idx);
2943 			set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2944 			set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2945 			set_bit(R5_Wantcompute, &dev->flags);
2946 			sh->ops.target = disk_idx;
2947 			sh->ops.target2 = -1; /* no 2nd target */
2948 			s->req_compute = 1;
2949 			/* Careful: from this point on 'uptodate' is in the eye
2950 			 * of raid_run_ops which services 'compute' operations
2951 			 * before writes. R5_Wantcompute flags a block that will
2952 			 * be R5_UPTODATE by the time it is needed for a
2953 			 * subsequent operation.
2954 			 */
2955 			s->uptodate++;
2956 			return 1;
2957 		} else if (s->uptodate == disks-2 && s->failed >= 2) {
2958 			/* Computing 2-failure is *very* expensive; only
2959 			 * do it if failed >= 2
2960 			 */
2961 			int other;
2962 			for (other = disks; other--; ) {
2963 				if (other == disk_idx)
2964 					continue;
2965 				if (!test_bit(R5_UPTODATE,
2966 				      &sh->dev[other].flags))
2967 					break;
2968 			}
2969 			BUG_ON(other < 0);
2970 			pr_debug("Computing stripe %llu blocks %d,%d\n",
2971 			       (unsigned long long)sh->sector,
2972 			       disk_idx, other);
2973 			set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2974 			set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2975 			set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
2976 			set_bit(R5_Wantcompute, &sh->dev[other].flags);
2977 			sh->ops.target = disk_idx;
2978 			sh->ops.target2 = other;
2979 			s->uptodate += 2;
2980 			s->req_compute = 1;
2981 			return 1;
2982 		} else if (test_bit(R5_Insync, &dev->flags)) {
2983 			set_bit(R5_LOCKED, &dev->flags);
2984 			set_bit(R5_Wantread, &dev->flags);
2985 			s->locked++;
2986 			pr_debug("Reading block %d (sync=%d)\n",
2987 				disk_idx, s->syncing);
2988 		}
2989 	}
2990 
2991 	return 0;
2992 }
2993 
2994 /**
2995  * handle_stripe_fill - read or compute data to satisfy pending requests.
2996  */
handle_stripe_fill(struct stripe_head * sh,struct stripe_head_state * s,int disks)2997 static void handle_stripe_fill(struct stripe_head *sh,
2998 			       struct stripe_head_state *s,
2999 			       int disks)
3000 {
3001 	int i;
3002 
3003 	/* look for blocks to read/compute, skip this if a compute
3004 	 * is already in flight, or if the stripe contents are in the
3005 	 * midst of changing due to a write
3006 	 */
3007 	if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3008 	    !sh->reconstruct_state)
3009 		for (i = disks; i--; )
3010 			if (fetch_block(sh, s, i, disks))
3011 				break;
3012 	set_bit(STRIPE_HANDLE, &sh->state);
3013 }
3014 
3015 /* handle_stripe_clean_event
3016  * any written block on an uptodate or failed drive can be returned.
3017  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3018  * never LOCKED, so we don't need to test 'failed' directly.
3019  */
handle_stripe_clean_event(struct r5conf * conf,struct stripe_head * sh,int disks,struct bio ** return_bi)3020 static void handle_stripe_clean_event(struct r5conf *conf,
3021 	struct stripe_head *sh, int disks, struct bio **return_bi)
3022 {
3023 	int i;
3024 	struct r5dev *dev;
3025 	int discard_pending = 0;
3026 
3027 	for (i = disks; i--; )
3028 		if (sh->dev[i].written) {
3029 			dev = &sh->dev[i];
3030 			if (!test_bit(R5_LOCKED, &dev->flags) &&
3031 			    (test_bit(R5_UPTODATE, &dev->flags) ||
3032 			     test_bit(R5_Discard, &dev->flags) ||
3033 			     test_bit(R5_SkipCopy, &dev->flags))) {
3034 				/* We can return any write requests */
3035 				struct bio *wbi, *wbi2;
3036 				pr_debug("Return write for disc %d\n", i);
3037 				if (test_and_clear_bit(R5_Discard, &dev->flags))
3038 					clear_bit(R5_UPTODATE, &dev->flags);
3039 				if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3040 					WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3041 					dev->page = dev->orig_page;
3042 				}
3043 				wbi = dev->written;
3044 				dev->written = NULL;
3045 				while (wbi && wbi->bi_iter.bi_sector <
3046 					dev->sector + STRIPE_SECTORS) {
3047 					wbi2 = r5_next_bio(wbi, dev->sector);
3048 					if (!raid5_dec_bi_active_stripes(wbi)) {
3049 						md_write_end(conf->mddev);
3050 						wbi->bi_next = *return_bi;
3051 						*return_bi = wbi;
3052 					}
3053 					wbi = wbi2;
3054 				}
3055 				bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3056 						STRIPE_SECTORS,
3057 					 !test_bit(STRIPE_DEGRADED, &sh->state),
3058 						0);
3059 			} else if (test_bit(R5_Discard, &dev->flags))
3060 				discard_pending = 1;
3061 			WARN_ON(test_bit(R5_SkipCopy, &dev->flags));
3062 			WARN_ON(dev->page != dev->orig_page);
3063 		}
3064 	if (!discard_pending &&
3065 	    test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
3066 		int hash = sh->hash_lock_index;
3067 
3068 		clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
3069 		clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3070 		if (sh->qd_idx >= 0) {
3071 			clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
3072 			clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
3073 		}
3074 		/* now that discard is done we can proceed with any sync */
3075 		clear_bit(STRIPE_DISCARD, &sh->state);
3076 		/*
3077 		 * SCSI discard will change some bio fields and the stripe has
3078 		 * no updated data, so remove it from hash list and the stripe
3079 		 * will be reinitialized
3080 		 */
3081 		spin_lock_irq(conf->hash_locks + hash);
3082 		remove_hash(sh);
3083 		spin_unlock_irq(conf->hash_locks + hash);
3084 		if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
3085 			set_bit(STRIPE_HANDLE, &sh->state);
3086 
3087 	}
3088 
3089 	if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3090 		if (atomic_dec_and_test(&conf->pending_full_writes))
3091 			md_wakeup_thread(conf->mddev->thread);
3092 }
3093 
handle_stripe_dirtying(struct r5conf * conf,struct stripe_head * sh,struct stripe_head_state * s,int disks)3094 static void handle_stripe_dirtying(struct r5conf *conf,
3095 				   struct stripe_head *sh,
3096 				   struct stripe_head_state *s,
3097 				   int disks)
3098 {
3099 	int rmw = 0, rcw = 0, i;
3100 	sector_t recovery_cp = conf->mddev->recovery_cp;
3101 
3102 	/* RAID6 requires 'rcw' in current implementation.
3103 	 * Otherwise, check whether resync is now happening or should start.
3104 	 * If yes, then the array is dirty (after unclean shutdown or
3105 	 * initial creation), so parity in some stripes might be inconsistent.
3106 	 * In this case, we need to always do reconstruct-write, to ensure
3107 	 * that in case of drive failure or read-error correction, we
3108 	 * generate correct data from the parity.
3109 	 */
3110 	if (conf->max_degraded == 2 ||
3111 	    (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
3112 	     s->failed == 0)) {
3113 		/* Calculate the real rcw later - for now make it
3114 		 * look like rcw is cheaper
3115 		 */
3116 		rcw = 1; rmw = 2;
3117 		pr_debug("force RCW max_degraded=%u, recovery_cp=%llu sh->sector=%llu\n",
3118 			 conf->max_degraded, (unsigned long long)recovery_cp,
3119 			 (unsigned long long)sh->sector);
3120 	} else for (i = disks; i--; ) {
3121 		/* would I have to read this buffer for read_modify_write */
3122 		struct r5dev *dev = &sh->dev[i];
3123 		if ((dev->towrite || i == sh->pd_idx) &&
3124 		    !test_bit(R5_LOCKED, &dev->flags) &&
3125 		    !(test_bit(R5_UPTODATE, &dev->flags) ||
3126 		      test_bit(R5_Wantcompute, &dev->flags))) {
3127 			if (test_bit(R5_Insync, &dev->flags))
3128 				rmw++;
3129 			else
3130 				rmw += 2*disks;  /* cannot read it */
3131 		}
3132 		/* Would I have to read this buffer for reconstruct_write */
3133 		if (!test_bit(R5_OVERWRITE, &dev->flags) && i != sh->pd_idx &&
3134 		    !test_bit(R5_LOCKED, &dev->flags) &&
3135 		    !(test_bit(R5_UPTODATE, &dev->flags) ||
3136 		    test_bit(R5_Wantcompute, &dev->flags))) {
3137 			if (test_bit(R5_Insync, &dev->flags))
3138 				rcw++;
3139 			else
3140 				rcw += 2*disks;
3141 		}
3142 	}
3143 	pr_debug("for sector %llu, rmw=%d rcw=%d\n",
3144 		(unsigned long long)sh->sector, rmw, rcw);
3145 	set_bit(STRIPE_HANDLE, &sh->state);
3146 	if (rmw < rcw && rmw > 0) {
3147 		/* prefer read-modify-write, but need to get some data */
3148 		if (conf->mddev->queue)
3149 			blk_add_trace_msg(conf->mddev->queue,
3150 					  "raid5 rmw %llu %d",
3151 					  (unsigned long long)sh->sector, rmw);
3152 		for (i = disks; i--; ) {
3153 			struct r5dev *dev = &sh->dev[i];
3154 			if ((dev->towrite || i == sh->pd_idx) &&
3155 			    !test_bit(R5_LOCKED, &dev->flags) &&
3156 			    !(test_bit(R5_UPTODATE, &dev->flags) ||
3157 			    test_bit(R5_Wantcompute, &dev->flags)) &&
3158 			    test_bit(R5_Insync, &dev->flags)) {
3159 				if (test_bit(STRIPE_PREREAD_ACTIVE,
3160 					     &sh->state)) {
3161 					pr_debug("Read_old block %d for r-m-w\n",
3162 						 i);
3163 					set_bit(R5_LOCKED, &dev->flags);
3164 					set_bit(R5_Wantread, &dev->flags);
3165 					s->locked++;
3166 				} else {
3167 					set_bit(STRIPE_DELAYED, &sh->state);
3168 					set_bit(STRIPE_HANDLE, &sh->state);
3169 				}
3170 			}
3171 		}
3172 	}
3173 	if (rcw <= rmw && rcw > 0) {
3174 		/* want reconstruct write, but need to get some data */
3175 		int qread =0;
3176 		rcw = 0;
3177 		for (i = disks; i--; ) {
3178 			struct r5dev *dev = &sh->dev[i];
3179 			if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3180 			    i != sh->pd_idx && i != sh->qd_idx &&
3181 			    !test_bit(R5_LOCKED, &dev->flags) &&
3182 			    !(test_bit(R5_UPTODATE, &dev->flags) ||
3183 			      test_bit(R5_Wantcompute, &dev->flags))) {
3184 				rcw++;
3185 				if (test_bit(R5_Insync, &dev->flags) &&
3186 				    test_bit(STRIPE_PREREAD_ACTIVE,
3187 					     &sh->state)) {
3188 					pr_debug("Read_old block "
3189 						"%d for Reconstruct\n", i);
3190 					set_bit(R5_LOCKED, &dev->flags);
3191 					set_bit(R5_Wantread, &dev->flags);
3192 					s->locked++;
3193 					qread++;
3194 				} else {
3195 					set_bit(STRIPE_DELAYED, &sh->state);
3196 					set_bit(STRIPE_HANDLE, &sh->state);
3197 				}
3198 			}
3199 		}
3200 		if (rcw && conf->mddev->queue)
3201 			blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
3202 					  (unsigned long long)sh->sector,
3203 					  rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
3204 	}
3205 
3206 	if (rcw > disks && rmw > disks &&
3207 	    !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3208 		set_bit(STRIPE_DELAYED, &sh->state);
3209 
3210 	/* now if nothing is locked, and if we have enough data,
3211 	 * we can start a write request
3212 	 */
3213 	/* since handle_stripe can be called at any time we need to handle the
3214 	 * case where a compute block operation has been submitted and then a
3215 	 * subsequent call wants to start a write request.  raid_run_ops only
3216 	 * handles the case where compute block and reconstruct are requested
3217 	 * simultaneously.  If this is not the case then new writes need to be
3218 	 * held off until the compute completes.
3219 	 */
3220 	if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
3221 	    (s->locked == 0 && (rcw == 0 || rmw == 0) &&
3222 	    !test_bit(STRIPE_BIT_DELAY, &sh->state)))
3223 		schedule_reconstruction(sh, s, rcw == 0, 0);
3224 }
3225 
handle_parity_checks5(struct r5conf * conf,struct stripe_head * sh,struct stripe_head_state * s,int disks)3226 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
3227 				struct stripe_head_state *s, int disks)
3228 {
3229 	struct r5dev *dev = NULL;
3230 
3231 	set_bit(STRIPE_HANDLE, &sh->state);
3232 
3233 	switch (sh->check_state) {
3234 	case check_state_idle:
3235 		/* start a new check operation if there are no failures */
3236 		if (s->failed == 0) {
3237 			BUG_ON(s->uptodate != disks);
3238 			sh->check_state = check_state_run;
3239 			set_bit(STRIPE_OP_CHECK, &s->ops_request);
3240 			clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3241 			s->uptodate--;
3242 			break;
3243 		}
3244 		dev = &sh->dev[s->failed_num[0]];
3245 		/* fall through */
3246 	case check_state_compute_result:
3247 		sh->check_state = check_state_idle;
3248 		if (!dev)
3249 			dev = &sh->dev[sh->pd_idx];
3250 
3251 		/* check that a write has not made the stripe insync */
3252 		if (test_bit(STRIPE_INSYNC, &sh->state))
3253 			break;
3254 
3255 		/* either failed parity check, or recovery is happening */
3256 		BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
3257 		BUG_ON(s->uptodate != disks);
3258 
3259 		set_bit(R5_LOCKED, &dev->flags);
3260 		s->locked++;
3261 		set_bit(R5_Wantwrite, &dev->flags);
3262 
3263 		clear_bit(STRIPE_DEGRADED, &sh->state);
3264 		set_bit(STRIPE_INSYNC, &sh->state);
3265 		break;
3266 	case check_state_run:
3267 		break; /* we will be called again upon completion */
3268 	case check_state_check_result:
3269 		sh->check_state = check_state_idle;
3270 
3271 		/* if a failure occurred during the check operation, leave
3272 		 * STRIPE_INSYNC not set and let the stripe be handled again
3273 		 */
3274 		if (s->failed)
3275 			break;
3276 
3277 		/* handle a successful check operation, if parity is correct
3278 		 * we are done.  Otherwise update the mismatch count and repair
3279 		 * parity if !MD_RECOVERY_CHECK
3280 		 */
3281 		if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
3282 			/* parity is correct (on disc,
3283 			 * not in buffer any more)
3284 			 */
3285 			set_bit(STRIPE_INSYNC, &sh->state);
3286 		else {
3287 			atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3288 			if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3289 				/* don't try to repair!! */
3290 				set_bit(STRIPE_INSYNC, &sh->state);
3291 			else {
3292 				sh->check_state = check_state_compute_run;
3293 				set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3294 				set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3295 				set_bit(R5_Wantcompute,
3296 					&sh->dev[sh->pd_idx].flags);
3297 				sh->ops.target = sh->pd_idx;
3298 				sh->ops.target2 = -1;
3299 				s->uptodate++;
3300 			}
3301 		}
3302 		break;
3303 	case check_state_compute_run:
3304 		break;
3305 	default:
3306 		printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3307 		       __func__, sh->check_state,
3308 		       (unsigned long long) sh->sector);
3309 		BUG();
3310 	}
3311 }
3312 
handle_parity_checks6(struct r5conf * conf,struct stripe_head * sh,struct stripe_head_state * s,int disks)3313 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
3314 				  struct stripe_head_state *s,
3315 				  int disks)
3316 {
3317 	int pd_idx = sh->pd_idx;
3318 	int qd_idx = sh->qd_idx;
3319 	struct r5dev *dev;
3320 
3321 	set_bit(STRIPE_HANDLE, &sh->state);
3322 
3323 	BUG_ON(s->failed > 2);
3324 
3325 	/* Want to check and possibly repair P and Q.
3326 	 * However there could be one 'failed' device, in which
3327 	 * case we can only check one of them, possibly using the
3328 	 * other to generate missing data
3329 	 */
3330 
3331 	switch (sh->check_state) {
3332 	case check_state_idle:
3333 		/* start a new check operation if there are < 2 failures */
3334 		if (s->failed == s->q_failed) {
3335 			/* The only possible failed device holds Q, so it
3336 			 * makes sense to check P (If anything else were failed,
3337 			 * we would have used P to recreate it).
3338 			 */
3339 			sh->check_state = check_state_run;
3340 		}
3341 		if (!s->q_failed && s->failed < 2) {
3342 			/* Q is not failed, and we didn't use it to generate
3343 			 * anything, so it makes sense to check it
3344 			 */
3345 			if (sh->check_state == check_state_run)
3346 				sh->check_state = check_state_run_pq;
3347 			else
3348 				sh->check_state = check_state_run_q;
3349 		}
3350 
3351 		/* discard potentially stale zero_sum_result */
3352 		sh->ops.zero_sum_result = 0;
3353 
3354 		if (sh->check_state == check_state_run) {
3355 			/* async_xor_zero_sum destroys the contents of P */
3356 			clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3357 			s->uptodate--;
3358 		}
3359 		if (sh->check_state >= check_state_run &&
3360 		    sh->check_state <= check_state_run_pq) {
3361 			/* async_syndrome_zero_sum preserves P and Q, so
3362 			 * no need to mark them !uptodate here
3363 			 */
3364 			set_bit(STRIPE_OP_CHECK, &s->ops_request);
3365 			break;
3366 		}
3367 
3368 		/* we have 2-disk failure */
3369 		BUG_ON(s->failed != 2);
3370 		/* fall through */
3371 	case check_state_compute_result:
3372 		sh->check_state = check_state_idle;
3373 
3374 		/* check that a write has not made the stripe insync */
3375 		if (test_bit(STRIPE_INSYNC, &sh->state))
3376 			break;
3377 
3378 		/* now write out any block on a failed drive,
3379 		 * or P or Q if they were recomputed
3380 		 */
3381 		BUG_ON(s->uptodate < disks - 1); /* We don't need Q to recover */
3382 		if (s->failed == 2) {
3383 			dev = &sh->dev[s->failed_num[1]];
3384 			s->locked++;
3385 			set_bit(R5_LOCKED, &dev->flags);
3386 			set_bit(R5_Wantwrite, &dev->flags);
3387 		}
3388 		if (s->failed >= 1) {
3389 			dev = &sh->dev[s->failed_num[0]];
3390 			s->locked++;
3391 			set_bit(R5_LOCKED, &dev->flags);
3392 			set_bit(R5_Wantwrite, &dev->flags);
3393 		}
3394 		if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3395 			dev = &sh->dev[pd_idx];
3396 			s->locked++;
3397 			set_bit(R5_LOCKED, &dev->flags);
3398 			set_bit(R5_Wantwrite, &dev->flags);
3399 		}
3400 		if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3401 			dev = &sh->dev[qd_idx];
3402 			s->locked++;
3403 			set_bit(R5_LOCKED, &dev->flags);
3404 			set_bit(R5_Wantwrite, &dev->flags);
3405 		}
3406 		clear_bit(STRIPE_DEGRADED, &sh->state);
3407 
3408 		set_bit(STRIPE_INSYNC, &sh->state);
3409 		break;
3410 	case check_state_run:
3411 	case check_state_run_q:
3412 	case check_state_run_pq:
3413 		break; /* we will be called again upon completion */
3414 	case check_state_check_result:
3415 		sh->check_state = check_state_idle;
3416 
3417 		/* handle a successful check operation, if parity is correct
3418 		 * we are done.  Otherwise update the mismatch count and repair
3419 		 * parity if !MD_RECOVERY_CHECK
3420 		 */
3421 		if (sh->ops.zero_sum_result == 0) {
3422 			/* both parities are correct */
3423 			if (!s->failed)
3424 				set_bit(STRIPE_INSYNC, &sh->state);
3425 			else {
3426 				/* in contrast to the raid5 case we can validate
3427 				 * parity, but still have a failure to write
3428 				 * back
3429 				 */
3430 				sh->check_state = check_state_compute_result;
3431 				/* Returning at this point means that we may go
3432 				 * off and bring p and/or q uptodate again so
3433 				 * we make sure to check zero_sum_result again
3434 				 * to verify if p or q need writeback
3435 				 */
3436 			}
3437 		} else {
3438 			atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3439 			if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3440 				/* don't try to repair!! */
3441 				set_bit(STRIPE_INSYNC, &sh->state);
3442 			else {
3443 				int *target = &sh->ops.target;
3444 
3445 				sh->ops.target = -1;
3446 				sh->ops.target2 = -1;
3447 				sh->check_state = check_state_compute_run;
3448 				set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3449 				set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3450 				if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3451 					set_bit(R5_Wantcompute,
3452 						&sh->dev[pd_idx].flags);
3453 					*target = pd_idx;
3454 					target = &sh->ops.target2;
3455 					s->uptodate++;
3456 				}
3457 				if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3458 					set_bit(R5_Wantcompute,
3459 						&sh->dev[qd_idx].flags);
3460 					*target = qd_idx;
3461 					s->uptodate++;
3462 				}
3463 			}
3464 		}
3465 		break;
3466 	case check_state_compute_run:
3467 		break;
3468 	default:
3469 		printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3470 		       __func__, sh->check_state,
3471 		       (unsigned long long) sh->sector);
3472 		BUG();
3473 	}
3474 }
3475 
handle_stripe_expansion(struct r5conf * conf,struct stripe_head * sh)3476 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
3477 {
3478 	int i;
3479 
3480 	/* We have read all the blocks in this stripe and now we need to
3481 	 * copy some of them into a target stripe for expand.
3482 	 */
3483 	struct dma_async_tx_descriptor *tx = NULL;
3484 	clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3485 	for (i = 0; i < sh->disks; i++)
3486 		if (i != sh->pd_idx && i != sh->qd_idx) {
3487 			int dd_idx, j;
3488 			struct stripe_head *sh2;
3489 			struct async_submit_ctl submit;
3490 
3491 			sector_t bn = compute_blocknr(sh, i, 1);
3492 			sector_t s = raid5_compute_sector(conf, bn, 0,
3493 							  &dd_idx, NULL);
3494 			sh2 = get_active_stripe(conf, s, 0, 1, 1);
3495 			if (sh2 == NULL)
3496 				/* so far only the early blocks of this stripe
3497 				 * have been requested.  When later blocks
3498 				 * get requested, we will try again
3499 				 */
3500 				continue;
3501 			if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
3502 			   test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
3503 				/* must have already done this block */
3504 				release_stripe(sh2);
3505 				continue;
3506 			}
3507 
3508 			/* place all the copies on one channel */
3509 			init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
3510 			tx = async_memcpy(sh2->dev[dd_idx].page,
3511 					  sh->dev[i].page, 0, 0, STRIPE_SIZE,
3512 					  &submit);
3513 
3514 			set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
3515 			set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
3516 			for (j = 0; j < conf->raid_disks; j++)
3517 				if (j != sh2->pd_idx &&
3518 				    j != sh2->qd_idx &&
3519 				    !test_bit(R5_Expanded, &sh2->dev[j].flags))
3520 					break;
3521 			if (j == conf->raid_disks) {
3522 				set_bit(STRIPE_EXPAND_READY, &sh2->state);
3523 				set_bit(STRIPE_HANDLE, &sh2->state);
3524 			}
3525 			release_stripe(sh2);
3526 
3527 		}
3528 	/* done submitting copies, wait for them to complete */
3529 	async_tx_quiesce(&tx);
3530 }
3531 
3532 /*
3533  * handle_stripe - do things to a stripe.
3534  *
3535  * We lock the stripe by setting STRIPE_ACTIVE and then examine the
3536  * state of various bits to see what needs to be done.
3537  * Possible results:
3538  *    return some read requests which now have data
3539  *    return some write requests which are safely on storage
3540  *    schedule a read on some buffers
3541  *    schedule a write of some buffers
3542  *    return confirmation of parity correctness
3543  *
3544  */
3545 
analyse_stripe(struct stripe_head * sh,struct stripe_head_state * s)3546 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
3547 {
3548 	struct r5conf *conf = sh->raid_conf;
3549 	int disks = sh->disks;
3550 	struct r5dev *dev;
3551 	int i;
3552 	int do_recovery = 0;
3553 
3554 	memset(s, 0, sizeof(*s));
3555 
3556 	s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3557 	s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
3558 	s->failed_num[0] = -1;
3559 	s->failed_num[1] = -1;
3560 
3561 	/* Now to look around and see what can be done */
3562 	rcu_read_lock();
3563 	for (i=disks; i--; ) {
3564 		struct md_rdev *rdev;
3565 		sector_t first_bad;
3566 		int bad_sectors;
3567 		int is_bad = 0;
3568 
3569 		dev = &sh->dev[i];
3570 
3571 		pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
3572 			 i, dev->flags,
3573 			 dev->toread, dev->towrite, dev->written);
3574 		/* maybe we can reply to a read
3575 		 *
3576 		 * new wantfill requests are only permitted while
3577 		 * ops_complete_biofill is guaranteed to be inactive
3578 		 */
3579 		if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
3580 		    !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
3581 			set_bit(R5_Wantfill, &dev->flags);
3582 
3583 		/* now count some things */
3584 		if (test_bit(R5_LOCKED, &dev->flags))
3585 			s->locked++;
3586 		if (test_bit(R5_UPTODATE, &dev->flags))
3587 			s->uptodate++;
3588 		if (test_bit(R5_Wantcompute, &dev->flags)) {
3589 			s->compute++;
3590 			BUG_ON(s->compute > 2);
3591 		}
3592 
3593 		if (test_bit(R5_Wantfill, &dev->flags))
3594 			s->to_fill++;
3595 		else if (dev->toread)
3596 			s->to_read++;
3597 		if (dev->towrite) {
3598 			s->to_write++;
3599 			if (!test_bit(R5_OVERWRITE, &dev->flags))
3600 				s->non_overwrite++;
3601 		}
3602 		if (dev->written)
3603 			s->written++;
3604 		/* Prefer to use the replacement for reads, but only
3605 		 * if it is recovered enough and has no bad blocks.
3606 		 */
3607 		rdev = rcu_dereference(conf->disks[i].replacement);
3608 		if (rdev && !test_bit(Faulty, &rdev->flags) &&
3609 		    rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
3610 		    !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
3611 				 &first_bad, &bad_sectors))
3612 			set_bit(R5_ReadRepl, &dev->flags);
3613 		else {
3614 			if (rdev)
3615 				set_bit(R5_NeedReplace, &dev->flags);
3616 			rdev = rcu_dereference(conf->disks[i].rdev);
3617 			clear_bit(R5_ReadRepl, &dev->flags);
3618 		}
3619 		if (rdev && test_bit(Faulty, &rdev->flags))
3620 			rdev = NULL;
3621 		if (rdev) {
3622 			is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
3623 					     &first_bad, &bad_sectors);
3624 			if (s->blocked_rdev == NULL
3625 			    && (test_bit(Blocked, &rdev->flags)
3626 				|| is_bad < 0)) {
3627 				if (is_bad < 0)
3628 					set_bit(BlockedBadBlocks,
3629 						&rdev->flags);
3630 				s->blocked_rdev = rdev;
3631 				atomic_inc(&rdev->nr_pending);
3632 			}
3633 		}
3634 		clear_bit(R5_Insync, &dev->flags);
3635 		if (!rdev)
3636 			/* Not in-sync */;
3637 		else if (is_bad) {
3638 			/* also not in-sync */
3639 			if (!test_bit(WriteErrorSeen, &rdev->flags) &&
3640 			    test_bit(R5_UPTODATE, &dev->flags)) {
3641 				/* treat as in-sync, but with a read error
3642 				 * which we can now try to correct
3643 				 */
3644 				set_bit(R5_Insync, &dev->flags);
3645 				set_bit(R5_ReadError, &dev->flags);
3646 			}
3647 		} else if (test_bit(In_sync, &rdev->flags))
3648 			set_bit(R5_Insync, &dev->flags);
3649 		else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
3650 			/* in sync if before recovery_offset */
3651 			set_bit(R5_Insync, &dev->flags);
3652 		else if (test_bit(R5_UPTODATE, &dev->flags) &&
3653 			 test_bit(R5_Expanded, &dev->flags))
3654 			/* If we've reshaped into here, we assume it is Insync.
3655 			 * We will shortly update recovery_offset to make
3656 			 * it official.
3657 			 */
3658 			set_bit(R5_Insync, &dev->flags);
3659 
3660 		if (test_bit(R5_WriteError, &dev->flags)) {
3661 			/* This flag does not apply to '.replacement'
3662 			 * only to .rdev, so make sure to check that*/
3663 			struct md_rdev *rdev2 = rcu_dereference(
3664 				conf->disks[i].rdev);
3665 			if (rdev2 == rdev)
3666 				clear_bit(R5_Insync, &dev->flags);
3667 			if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3668 				s->handle_bad_blocks = 1;
3669 				atomic_inc(&rdev2->nr_pending);
3670 			} else
3671 				clear_bit(R5_WriteError, &dev->flags);
3672 		}
3673 		if (test_bit(R5_MadeGood, &dev->flags)) {
3674 			/* This flag does not apply to '.replacement'
3675 			 * only to .rdev, so make sure to check that*/
3676 			struct md_rdev *rdev2 = rcu_dereference(
3677 				conf->disks[i].rdev);
3678 			if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3679 				s->handle_bad_blocks = 1;
3680 				atomic_inc(&rdev2->nr_pending);
3681 			} else
3682 				clear_bit(R5_MadeGood, &dev->flags);
3683 		}
3684 		if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
3685 			struct md_rdev *rdev2 = rcu_dereference(
3686 				conf->disks[i].replacement);
3687 			if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3688 				s->handle_bad_blocks = 1;
3689 				atomic_inc(&rdev2->nr_pending);
3690 			} else
3691 				clear_bit(R5_MadeGoodRepl, &dev->flags);
3692 		}
3693 		if (!test_bit(R5_Insync, &dev->flags)) {
3694 			/* The ReadError flag will just be confusing now */
3695 			clear_bit(R5_ReadError, &dev->flags);
3696 			clear_bit(R5_ReWrite, &dev->flags);
3697 		}
3698 		if (test_bit(R5_ReadError, &dev->flags))
3699 			clear_bit(R5_Insync, &dev->flags);
3700 		if (!test_bit(R5_Insync, &dev->flags)) {
3701 			if (s->failed < 2)
3702 				s->failed_num[s->failed] = i;
3703 			s->failed++;
3704 			if (rdev && !test_bit(Faulty, &rdev->flags))
3705 				do_recovery = 1;
3706 		}
3707 	}
3708 	if (test_bit(STRIPE_SYNCING, &sh->state)) {
3709 		/* If there is a failed device being replaced,
3710 		 *     we must be recovering.
3711 		 * else if we are after recovery_cp, we must be syncing
3712 		 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
3713 		 * else we can only be replacing
3714 		 * sync and recovery both need to read all devices, and so
3715 		 * use the same flag.
3716 		 */
3717 		if (do_recovery ||
3718 		    sh->sector >= conf->mddev->recovery_cp ||
3719 		    test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
3720 			s->syncing = 1;
3721 		else
3722 			s->replacing = 1;
3723 	}
3724 	rcu_read_unlock();
3725 }
3726 
handle_stripe(struct stripe_head * sh)3727 static void handle_stripe(struct stripe_head *sh)
3728 {
3729 	struct stripe_head_state s;
3730 	struct r5conf *conf = sh->raid_conf;
3731 	int i;
3732 	int prexor;
3733 	int disks = sh->disks;
3734 	struct r5dev *pdev, *qdev;
3735 
3736 	clear_bit(STRIPE_HANDLE, &sh->state);
3737 	if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
3738 		/* already being handled, ensure it gets handled
3739 		 * again when current action finishes */
3740 		set_bit(STRIPE_HANDLE, &sh->state);
3741 		return;
3742 	}
3743 
3744 	if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
3745 		spin_lock(&sh->stripe_lock);
3746 		/* Cannot process 'sync' concurrently with 'discard' */
3747 		if (!test_bit(STRIPE_DISCARD, &sh->state) &&
3748 		    test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
3749 			set_bit(STRIPE_SYNCING, &sh->state);
3750 			clear_bit(STRIPE_INSYNC, &sh->state);
3751 			clear_bit(STRIPE_REPLACED, &sh->state);
3752 		}
3753 		spin_unlock(&sh->stripe_lock);
3754 	}
3755 	clear_bit(STRIPE_DELAYED, &sh->state);
3756 
3757 	pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
3758 		"pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
3759 	       (unsigned long long)sh->sector, sh->state,
3760 	       atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
3761 	       sh->check_state, sh->reconstruct_state);
3762 
3763 	analyse_stripe(sh, &s);
3764 
3765 	if (s.handle_bad_blocks) {
3766 		set_bit(STRIPE_HANDLE, &sh->state);
3767 		goto finish;
3768 	}
3769 
3770 	if (unlikely(s.blocked_rdev)) {
3771 		if (s.syncing || s.expanding || s.expanded ||
3772 		    s.replacing || s.to_write || s.written) {
3773 			set_bit(STRIPE_HANDLE, &sh->state);
3774 			goto finish;
3775 		}
3776 		/* There is nothing for the blocked_rdev to block */
3777 		rdev_dec_pending(s.blocked_rdev, conf->mddev);
3778 		s.blocked_rdev = NULL;
3779 	}
3780 
3781 	if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
3782 		set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
3783 		set_bit(STRIPE_BIOFILL_RUN, &sh->state);
3784 	}
3785 
3786 	pr_debug("locked=%d uptodate=%d to_read=%d"
3787 	       " to_write=%d failed=%d failed_num=%d,%d\n",
3788 	       s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
3789 	       s.failed_num[0], s.failed_num[1]);
3790 	/* check if the array has lost more than max_degraded devices and,
3791 	 * if so, some requests might need to be failed.
3792 	 */
3793 	if (s.failed > conf->max_degraded) {
3794 		sh->check_state = 0;
3795 		sh->reconstruct_state = 0;
3796 		if (s.to_read+s.to_write+s.written)
3797 			handle_failed_stripe(conf, sh, &s, disks, &s.return_bi);
3798 		if (s.syncing + s.replacing)
3799 			handle_failed_sync(conf, sh, &s);
3800 	}
3801 
3802 	/* Now we check to see if any write operations have recently
3803 	 * completed
3804 	 */
3805 	prexor = 0;
3806 	if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
3807 		prexor = 1;
3808 	if (sh->reconstruct_state == reconstruct_state_drain_result ||
3809 	    sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
3810 		sh->reconstruct_state = reconstruct_state_idle;
3811 
3812 		/* All the 'written' buffers and the parity block are ready to
3813 		 * be written back to disk
3814 		 */
3815 		BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
3816 		       !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
3817 		BUG_ON(sh->qd_idx >= 0 &&
3818 		       !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
3819 		       !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
3820 		for (i = disks; i--; ) {
3821 			struct r5dev *dev = &sh->dev[i];
3822 			if (test_bit(R5_LOCKED, &dev->flags) &&
3823 				(i == sh->pd_idx || i == sh->qd_idx ||
3824 				 dev->written)) {
3825 				pr_debug("Writing block %d\n", i);
3826 				set_bit(R5_Wantwrite, &dev->flags);
3827 				if (prexor)
3828 					continue;
3829 				if (s.failed > 1)
3830 					continue;
3831 				if (!test_bit(R5_Insync, &dev->flags) ||
3832 				    ((i == sh->pd_idx || i == sh->qd_idx)  &&
3833 				     s.failed == 0))
3834 					set_bit(STRIPE_INSYNC, &sh->state);
3835 			}
3836 		}
3837 		if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3838 			s.dec_preread_active = 1;
3839 	}
3840 
3841 	/*
3842 	 * might be able to return some write requests if the parity blocks
3843 	 * are safe, or on a failed drive
3844 	 */
3845 	pdev = &sh->dev[sh->pd_idx];
3846 	s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
3847 		|| (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
3848 	qdev = &sh->dev[sh->qd_idx];
3849 	s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
3850 		|| (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
3851 		|| conf->level < 6;
3852 
3853 	if (s.written &&
3854 	    (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
3855 			     && !test_bit(R5_LOCKED, &pdev->flags)
3856 			     && (test_bit(R5_UPTODATE, &pdev->flags) ||
3857 				 test_bit(R5_Discard, &pdev->flags))))) &&
3858 	    (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
3859 			     && !test_bit(R5_LOCKED, &qdev->flags)
3860 			     && (test_bit(R5_UPTODATE, &qdev->flags) ||
3861 				 test_bit(R5_Discard, &qdev->flags))))))
3862 		handle_stripe_clean_event(conf, sh, disks, &s.return_bi);
3863 
3864 	/* Now we might consider reading some blocks, either to check/generate
3865 	 * parity, or to satisfy requests
3866 	 * or to load a block that is being partially written.
3867 	 */
3868 	if (s.to_read || s.non_overwrite
3869 	    || (conf->level == 6 && s.to_write && s.failed)
3870 	    || (s.syncing && (s.uptodate + s.compute < disks))
3871 	    || s.replacing
3872 	    || s.expanding)
3873 		handle_stripe_fill(sh, &s, disks);
3874 
3875 	/* Now to consider new write requests and what else, if anything
3876 	 * should be read.  We do not handle new writes when:
3877 	 * 1/ A 'write' operation (copy+xor) is already in flight.
3878 	 * 2/ A 'check' operation is in flight, as it may clobber the parity
3879 	 *    block.
3880 	 */
3881 	if (s.to_write && !sh->reconstruct_state && !sh->check_state)
3882 		handle_stripe_dirtying(conf, sh, &s, disks);
3883 
3884 	/* maybe we need to check and possibly fix the parity for this stripe
3885 	 * Any reads will already have been scheduled, so we just see if enough
3886 	 * data is available.  The parity check is held off while parity
3887 	 * dependent operations are in flight.
3888 	 */
3889 	if (sh->check_state ||
3890 	    (s.syncing && s.locked == 0 &&
3891 	     !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
3892 	     !test_bit(STRIPE_INSYNC, &sh->state))) {
3893 		if (conf->level == 6)
3894 			handle_parity_checks6(conf, sh, &s, disks);
3895 		else
3896 			handle_parity_checks5(conf, sh, &s, disks);
3897 	}
3898 
3899 	if ((s.replacing || s.syncing) && s.locked == 0
3900 	    && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
3901 	    && !test_bit(STRIPE_REPLACED, &sh->state)) {
3902 		/* Write out to replacement devices where possible */
3903 		for (i = 0; i < conf->raid_disks; i++)
3904 			if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
3905 				WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
3906 				set_bit(R5_WantReplace, &sh->dev[i].flags);
3907 				set_bit(R5_LOCKED, &sh->dev[i].flags);
3908 				s.locked++;
3909 			}
3910 		if (s.replacing)
3911 			set_bit(STRIPE_INSYNC, &sh->state);
3912 		set_bit(STRIPE_REPLACED, &sh->state);
3913 	}
3914 	if ((s.syncing || s.replacing) && s.locked == 0 &&
3915 	    !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
3916 	    test_bit(STRIPE_INSYNC, &sh->state)) {
3917 		md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3918 		clear_bit(STRIPE_SYNCING, &sh->state);
3919 		if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3920 			wake_up(&conf->wait_for_overlap);
3921 	}
3922 
3923 	/* If the failed drives are just a ReadError, then we might need
3924 	 * to progress the repair/check process
3925 	 */
3926 	if (s.failed <= conf->max_degraded && !conf->mddev->ro)
3927 		for (i = 0; i < s.failed; i++) {
3928 			struct r5dev *dev = &sh->dev[s.failed_num[i]];
3929 			if (test_bit(R5_ReadError, &dev->flags)
3930 			    && !test_bit(R5_LOCKED, &dev->flags)
3931 			    && test_bit(R5_UPTODATE, &dev->flags)
3932 				) {
3933 				if (!test_bit(R5_ReWrite, &dev->flags)) {
3934 					set_bit(R5_Wantwrite, &dev->flags);
3935 					set_bit(R5_ReWrite, &dev->flags);
3936 					set_bit(R5_LOCKED, &dev->flags);
3937 					s.locked++;
3938 				} else {
3939 					/* let's read it back */
3940 					set_bit(R5_Wantread, &dev->flags);
3941 					set_bit(R5_LOCKED, &dev->flags);
3942 					s.locked++;
3943 				}
3944 			}
3945 		}
3946 
3947 	/* Finish reconstruct operations initiated by the expansion process */
3948 	if (sh->reconstruct_state == reconstruct_state_result) {
3949 		struct stripe_head *sh_src
3950 			= get_active_stripe(conf, sh->sector, 1, 1, 1);
3951 		if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
3952 			/* sh cannot be written until sh_src has been read.
3953 			 * so arrange for sh to be delayed a little
3954 			 */
3955 			set_bit(STRIPE_DELAYED, &sh->state);
3956 			set_bit(STRIPE_HANDLE, &sh->state);
3957 			if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
3958 					      &sh_src->state))
3959 				atomic_inc(&conf->preread_active_stripes);
3960 			release_stripe(sh_src);
3961 			goto finish;
3962 		}
3963 		if (sh_src)
3964 			release_stripe(sh_src);
3965 
3966 		sh->reconstruct_state = reconstruct_state_idle;
3967 		clear_bit(STRIPE_EXPANDING, &sh->state);
3968 		for (i = conf->raid_disks; i--; ) {
3969 			set_bit(R5_Wantwrite, &sh->dev[i].flags);
3970 			set_bit(R5_LOCKED, &sh->dev[i].flags);
3971 			s.locked++;
3972 		}
3973 	}
3974 
3975 	if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
3976 	    !sh->reconstruct_state) {
3977 		/* Need to write out all blocks after computing parity */
3978 		sh->disks = conf->raid_disks;
3979 		stripe_set_idx(sh->sector, conf, 0, sh);
3980 		schedule_reconstruction(sh, &s, 1, 1);
3981 	} else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
3982 		clear_bit(STRIPE_EXPAND_READY, &sh->state);
3983 		atomic_dec(&conf->reshape_stripes);
3984 		wake_up(&conf->wait_for_overlap);
3985 		md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3986 	}
3987 
3988 	if (s.expanding && s.locked == 0 &&
3989 	    !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
3990 		handle_stripe_expansion(conf, sh);
3991 
3992 finish:
3993 	/* wait for this device to become unblocked */
3994 	if (unlikely(s.blocked_rdev)) {
3995 		if (conf->mddev->external)
3996 			md_wait_for_blocked_rdev(s.blocked_rdev,
3997 						 conf->mddev);
3998 		else
3999 			/* Internal metadata will immediately
4000 			 * be written by raid5d, so we don't
4001 			 * need to wait here.
4002 			 */
4003 			rdev_dec_pending(s.blocked_rdev,
4004 					 conf->mddev);
4005 	}
4006 
4007 	if (s.handle_bad_blocks)
4008 		for (i = disks; i--; ) {
4009 			struct md_rdev *rdev;
4010 			struct r5dev *dev = &sh->dev[i];
4011 			if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
4012 				/* We own a safe reference to the rdev */
4013 				rdev = conf->disks[i].rdev;
4014 				if (!rdev_set_badblocks(rdev, sh->sector,
4015 							STRIPE_SECTORS, 0))
4016 					md_error(conf->mddev, rdev);
4017 				rdev_dec_pending(rdev, conf->mddev);
4018 			}
4019 			if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
4020 				rdev = conf->disks[i].rdev;
4021 				rdev_clear_badblocks(rdev, sh->sector,
4022 						     STRIPE_SECTORS, 0);
4023 				rdev_dec_pending(rdev, conf->mddev);
4024 			}
4025 			if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
4026 				rdev = conf->disks[i].replacement;
4027 				if (!rdev)
4028 					/* rdev have been moved down */
4029 					rdev = conf->disks[i].rdev;
4030 				rdev_clear_badblocks(rdev, sh->sector,
4031 						     STRIPE_SECTORS, 0);
4032 				rdev_dec_pending(rdev, conf->mddev);
4033 			}
4034 		}
4035 
4036 	if (s.ops_request)
4037 		raid_run_ops(sh, s.ops_request);
4038 
4039 	ops_run_io(sh, &s);
4040 
4041 	if (s.dec_preread_active) {
4042 		/* We delay this until after ops_run_io so that if make_request
4043 		 * is waiting on a flush, it won't continue until the writes
4044 		 * have actually been submitted.
4045 		 */
4046 		atomic_dec(&conf->preread_active_stripes);
4047 		if (atomic_read(&conf->preread_active_stripes) <
4048 		    IO_THRESHOLD)
4049 			md_wakeup_thread(conf->mddev->thread);
4050 	}
4051 
4052 	return_io(s.return_bi);
4053 
4054 	clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4055 }
4056 
raid5_activate_delayed(struct r5conf * conf)4057 static void raid5_activate_delayed(struct r5conf *conf)
4058 {
4059 	if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
4060 		while (!list_empty(&conf->delayed_list)) {
4061 			struct list_head *l = conf->delayed_list.next;
4062 			struct stripe_head *sh;
4063 			sh = list_entry(l, struct stripe_head, lru);
4064 			list_del_init(l);
4065 			clear_bit(STRIPE_DELAYED, &sh->state);
4066 			if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4067 				atomic_inc(&conf->preread_active_stripes);
4068 			list_add_tail(&sh->lru, &conf->hold_list);
4069 			raid5_wakeup_stripe_thread(sh);
4070 		}
4071 	}
4072 }
4073 
activate_bit_delay(struct r5conf * conf,struct list_head * temp_inactive_list)4074 static void activate_bit_delay(struct r5conf *conf,
4075 	struct list_head *temp_inactive_list)
4076 {
4077 	/* device_lock is held */
4078 	struct list_head head;
4079 	list_add(&head, &conf->bitmap_list);
4080 	list_del_init(&conf->bitmap_list);
4081 	while (!list_empty(&head)) {
4082 		struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
4083 		int hash;
4084 		list_del_init(&sh->lru);
4085 		atomic_inc(&sh->count);
4086 		hash = sh->hash_lock_index;
4087 		__release_stripe(conf, sh, &temp_inactive_list[hash]);
4088 	}
4089 }
4090 
md_raid5_congested(struct mddev * mddev,int bits)4091 int md_raid5_congested(struct mddev *mddev, int bits)
4092 {
4093 	struct r5conf *conf = mddev->private;
4094 
4095 	/* No difference between reads and writes.  Just check
4096 	 * how busy the stripe_cache is
4097 	 */
4098 
4099 	if (conf->inactive_blocked)
4100 		return 1;
4101 	if (conf->quiesce)
4102 		return 1;
4103 	if (atomic_read(&conf->empty_inactive_list_nr))
4104 		return 1;
4105 
4106 	return 0;
4107 }
4108 EXPORT_SYMBOL_GPL(md_raid5_congested);
4109 
raid5_congested(void * data,int bits)4110 static int raid5_congested(void *data, int bits)
4111 {
4112 	struct mddev *mddev = data;
4113 
4114 	return mddev_congested(mddev, bits) ||
4115 		md_raid5_congested(mddev, bits);
4116 }
4117 
4118 /* We want read requests to align with chunks where possible,
4119  * but write requests don't need to.
4120  */
raid5_mergeable_bvec(struct request_queue * q,struct bvec_merge_data * bvm,struct bio_vec * biovec)4121 static int raid5_mergeable_bvec(struct request_queue *q,
4122 				struct bvec_merge_data *bvm,
4123 				struct bio_vec *biovec)
4124 {
4125 	struct mddev *mddev = q->queuedata;
4126 	sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
4127 	int max;
4128 	unsigned int chunk_sectors = mddev->chunk_sectors;
4129 	unsigned int bio_sectors = bvm->bi_size >> 9;
4130 
4131 	if ((bvm->bi_rw & 1) == WRITE)
4132 		return biovec->bv_len; /* always allow writes to be mergeable */
4133 
4134 	if (mddev->new_chunk_sectors < mddev->chunk_sectors)
4135 		chunk_sectors = mddev->new_chunk_sectors;
4136 	max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
4137 	if (max < 0) max = 0;
4138 	if (max <= biovec->bv_len && bio_sectors == 0)
4139 		return biovec->bv_len;
4140 	else
4141 		return max;
4142 }
4143 
in_chunk_boundary(struct mddev * mddev,struct bio * bio)4144 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
4145 {
4146 	sector_t sector = bio->bi_iter.bi_sector + get_start_sect(bio->bi_bdev);
4147 	unsigned int chunk_sectors = mddev->chunk_sectors;
4148 	unsigned int bio_sectors = bio_sectors(bio);
4149 
4150 	if (mddev->new_chunk_sectors < mddev->chunk_sectors)
4151 		chunk_sectors = mddev->new_chunk_sectors;
4152 	return  chunk_sectors >=
4153 		((sector & (chunk_sectors - 1)) + bio_sectors);
4154 }
4155 
4156 /*
4157  *  add bio to the retry LIFO  ( in O(1) ... we are in interrupt )
4158  *  later sampled by raid5d.
4159  */
add_bio_to_retry(struct bio * bi,struct r5conf * conf)4160 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
4161 {
4162 	unsigned long flags;
4163 
4164 	spin_lock_irqsave(&conf->device_lock, flags);
4165 
4166 	bi->bi_next = conf->retry_read_aligned_list;
4167 	conf->retry_read_aligned_list = bi;
4168 
4169 	spin_unlock_irqrestore(&conf->device_lock, flags);
4170 	md_wakeup_thread(conf->mddev->thread);
4171 }
4172 
remove_bio_from_retry(struct r5conf * conf)4173 static struct bio *remove_bio_from_retry(struct r5conf *conf)
4174 {
4175 	struct bio *bi;
4176 
4177 	bi = conf->retry_read_aligned;
4178 	if (bi) {
4179 		conf->retry_read_aligned = NULL;
4180 		return bi;
4181 	}
4182 	bi = conf->retry_read_aligned_list;
4183 	if(bi) {
4184 		conf->retry_read_aligned_list = bi->bi_next;
4185 		bi->bi_next = NULL;
4186 		/*
4187 		 * this sets the active strip count to 1 and the processed
4188 		 * strip count to zero (upper 8 bits)
4189 		 */
4190 		raid5_set_bi_stripes(bi, 1); /* biased count of active stripes */
4191 	}
4192 
4193 	return bi;
4194 }
4195 
4196 /*
4197  *  The "raid5_align_endio" should check if the read succeeded and if it
4198  *  did, call bio_endio on the original bio (having bio_put the new bio
4199  *  first).
4200  *  If the read failed..
4201  */
raid5_align_endio(struct bio * bi,int error)4202 static void raid5_align_endio(struct bio *bi, int error)
4203 {
4204 	struct bio* raid_bi  = bi->bi_private;
4205 	struct mddev *mddev;
4206 	struct r5conf *conf;
4207 	int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
4208 	struct md_rdev *rdev;
4209 
4210 	bio_put(bi);
4211 
4212 	rdev = (void*)raid_bi->bi_next;
4213 	raid_bi->bi_next = NULL;
4214 	mddev = rdev->mddev;
4215 	conf = mddev->private;
4216 
4217 	rdev_dec_pending(rdev, conf->mddev);
4218 
4219 	if (!error && uptodate) {
4220 		trace_block_bio_complete(bdev_get_queue(raid_bi->bi_bdev),
4221 					 raid_bi, 0);
4222 		bio_endio(raid_bi, 0);
4223 		if (atomic_dec_and_test(&conf->active_aligned_reads))
4224 			wake_up(&conf->wait_for_stripe);
4225 		return;
4226 	}
4227 
4228 	pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
4229 
4230 	add_bio_to_retry(raid_bi, conf);
4231 }
4232 
bio_fits_rdev(struct bio * bi)4233 static int bio_fits_rdev(struct bio *bi)
4234 {
4235 	struct request_queue *q = bdev_get_queue(bi->bi_bdev);
4236 
4237 	if (bio_sectors(bi) > queue_max_sectors(q))
4238 		return 0;
4239 	blk_recount_segments(q, bi);
4240 	if (bi->bi_phys_segments > queue_max_segments(q))
4241 		return 0;
4242 
4243 	if (q->merge_bvec_fn)
4244 		/* it's too hard to apply the merge_bvec_fn at this stage,
4245 		 * just just give up
4246 		 */
4247 		return 0;
4248 
4249 	return 1;
4250 }
4251 
chunk_aligned_read(struct mddev * mddev,struct bio * raid_bio)4252 static int chunk_aligned_read(struct mddev *mddev, struct bio * raid_bio)
4253 {
4254 	struct r5conf *conf = mddev->private;
4255 	int dd_idx;
4256 	struct bio* align_bi;
4257 	struct md_rdev *rdev;
4258 	sector_t end_sector;
4259 
4260 	if (!in_chunk_boundary(mddev, raid_bio)) {
4261 		pr_debug("chunk_aligned_read : non aligned\n");
4262 		return 0;
4263 	}
4264 	/*
4265 	 * use bio_clone_mddev to make a copy of the bio
4266 	 */
4267 	align_bi = bio_clone_mddev(raid_bio, GFP_NOIO, mddev);
4268 	if (!align_bi)
4269 		return 0;
4270 	/*
4271 	 *   set bi_end_io to a new function, and set bi_private to the
4272 	 *     original bio.
4273 	 */
4274 	align_bi->bi_end_io  = raid5_align_endio;
4275 	align_bi->bi_private = raid_bio;
4276 	/*
4277 	 *	compute position
4278 	 */
4279 	align_bi->bi_iter.bi_sector =
4280 		raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
4281 				     0, &dd_idx, NULL);
4282 
4283 	end_sector = bio_end_sector(align_bi);
4284 	rcu_read_lock();
4285 	rdev = rcu_dereference(conf->disks[dd_idx].replacement);
4286 	if (!rdev || test_bit(Faulty, &rdev->flags) ||
4287 	    rdev->recovery_offset < end_sector) {
4288 		rdev = rcu_dereference(conf->disks[dd_idx].rdev);
4289 		if (rdev &&
4290 		    (test_bit(Faulty, &rdev->flags) ||
4291 		    !(test_bit(In_sync, &rdev->flags) ||
4292 		      rdev->recovery_offset >= end_sector)))
4293 			rdev = NULL;
4294 	}
4295 	if (rdev) {
4296 		sector_t first_bad;
4297 		int bad_sectors;
4298 
4299 		atomic_inc(&rdev->nr_pending);
4300 		rcu_read_unlock();
4301 		raid_bio->bi_next = (void*)rdev;
4302 		align_bi->bi_bdev =  rdev->bdev;
4303 		__clear_bit(BIO_SEG_VALID, &align_bi->bi_flags);
4304 
4305 		if (!bio_fits_rdev(align_bi) ||
4306 		    is_badblock(rdev, align_bi->bi_iter.bi_sector,
4307 				bio_sectors(align_bi),
4308 				&first_bad, &bad_sectors)) {
4309 			/* too big in some way, or has a known bad block */
4310 			bio_put(align_bi);
4311 			rdev_dec_pending(rdev, mddev);
4312 			return 0;
4313 		}
4314 
4315 		/* No reshape active, so we can trust rdev->data_offset */
4316 		align_bi->bi_iter.bi_sector += rdev->data_offset;
4317 
4318 		spin_lock_irq(&conf->device_lock);
4319 		wait_event_lock_irq(conf->wait_for_stripe,
4320 				    conf->quiesce == 0,
4321 				    conf->device_lock);
4322 		atomic_inc(&conf->active_aligned_reads);
4323 		spin_unlock_irq(&conf->device_lock);
4324 
4325 		if (mddev->gendisk)
4326 			trace_block_bio_remap(bdev_get_queue(align_bi->bi_bdev),
4327 					      align_bi, disk_devt(mddev->gendisk),
4328 					      raid_bio->bi_iter.bi_sector);
4329 		generic_make_request(align_bi);
4330 		return 1;
4331 	} else {
4332 		rcu_read_unlock();
4333 		bio_put(align_bi);
4334 		return 0;
4335 	}
4336 }
4337 
4338 /* __get_priority_stripe - get the next stripe to process
4339  *
4340  * Full stripe writes are allowed to pass preread active stripes up until
4341  * the bypass_threshold is exceeded.  In general the bypass_count
4342  * increments when the handle_list is handled before the hold_list; however, it
4343  * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
4344  * stripe with in flight i/o.  The bypass_count will be reset when the
4345  * head of the hold_list has changed, i.e. the head was promoted to the
4346  * handle_list.
4347  */
__get_priority_stripe(struct r5conf * conf,int group)4348 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
4349 {
4350 	struct stripe_head *sh = NULL, *tmp;
4351 	struct list_head *handle_list = NULL;
4352 	struct r5worker_group *wg = NULL;
4353 
4354 	if (conf->worker_cnt_per_group == 0) {
4355 		handle_list = &conf->handle_list;
4356 	} else if (group != ANY_GROUP) {
4357 		handle_list = &conf->worker_groups[group].handle_list;
4358 		wg = &conf->worker_groups[group];
4359 	} else {
4360 		int i;
4361 		for (i = 0; i < conf->group_cnt; i++) {
4362 			handle_list = &conf->worker_groups[i].handle_list;
4363 			wg = &conf->worker_groups[i];
4364 			if (!list_empty(handle_list))
4365 				break;
4366 		}
4367 	}
4368 
4369 	pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
4370 		  __func__,
4371 		  list_empty(handle_list) ? "empty" : "busy",
4372 		  list_empty(&conf->hold_list) ? "empty" : "busy",
4373 		  atomic_read(&conf->pending_full_writes), conf->bypass_count);
4374 
4375 	if (!list_empty(handle_list)) {
4376 		sh = list_entry(handle_list->next, typeof(*sh), lru);
4377 
4378 		if (list_empty(&conf->hold_list))
4379 			conf->bypass_count = 0;
4380 		else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
4381 			if (conf->hold_list.next == conf->last_hold)
4382 				conf->bypass_count++;
4383 			else {
4384 				conf->last_hold = conf->hold_list.next;
4385 				conf->bypass_count -= conf->bypass_threshold;
4386 				if (conf->bypass_count < 0)
4387 					conf->bypass_count = 0;
4388 			}
4389 		}
4390 	} else if (!list_empty(&conf->hold_list) &&
4391 		   ((conf->bypass_threshold &&
4392 		     conf->bypass_count > conf->bypass_threshold) ||
4393 		    atomic_read(&conf->pending_full_writes) == 0)) {
4394 
4395 		list_for_each_entry(tmp, &conf->hold_list,  lru) {
4396 			if (conf->worker_cnt_per_group == 0 ||
4397 			    group == ANY_GROUP ||
4398 			    !cpu_online(tmp->cpu) ||
4399 			    cpu_to_group(tmp->cpu) == group) {
4400 				sh = tmp;
4401 				break;
4402 			}
4403 		}
4404 
4405 		if (sh) {
4406 			conf->bypass_count -= conf->bypass_threshold;
4407 			if (conf->bypass_count < 0)
4408 				conf->bypass_count = 0;
4409 		}
4410 		wg = NULL;
4411 	}
4412 
4413 	if (!sh)
4414 		return NULL;
4415 
4416 	if (wg) {
4417 		wg->stripes_cnt--;
4418 		sh->group = NULL;
4419 	}
4420 	list_del_init(&sh->lru);
4421 	BUG_ON(atomic_inc_return(&sh->count) != 1);
4422 	return sh;
4423 }
4424 
4425 struct raid5_plug_cb {
4426 	struct blk_plug_cb	cb;
4427 	struct list_head	list;
4428 	struct list_head	temp_inactive_list[NR_STRIPE_HASH_LOCKS];
4429 };
4430 
raid5_unplug(struct blk_plug_cb * blk_cb,bool from_schedule)4431 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
4432 {
4433 	struct raid5_plug_cb *cb = container_of(
4434 		blk_cb, struct raid5_plug_cb, cb);
4435 	struct stripe_head *sh;
4436 	struct mddev *mddev = cb->cb.data;
4437 	struct r5conf *conf = mddev->private;
4438 	int cnt = 0;
4439 	int hash;
4440 
4441 	if (cb->list.next && !list_empty(&cb->list)) {
4442 		spin_lock_irq(&conf->device_lock);
4443 		while (!list_empty(&cb->list)) {
4444 			sh = list_first_entry(&cb->list, struct stripe_head, lru);
4445 			list_del_init(&sh->lru);
4446 			/*
4447 			 * avoid race release_stripe_plug() sees
4448 			 * STRIPE_ON_UNPLUG_LIST clear but the stripe
4449 			 * is still in our list
4450 			 */
4451 			smp_mb__before_atomic();
4452 			clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
4453 			/*
4454 			 * STRIPE_ON_RELEASE_LIST could be set here. In that
4455 			 * case, the count is always > 1 here
4456 			 */
4457 			hash = sh->hash_lock_index;
4458 			__release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
4459 			cnt++;
4460 		}
4461 		spin_unlock_irq(&conf->device_lock);
4462 	}
4463 	release_inactive_stripe_list(conf, cb->temp_inactive_list,
4464 				     NR_STRIPE_HASH_LOCKS);
4465 	if (mddev->queue)
4466 		trace_block_unplug(mddev->queue, cnt, !from_schedule);
4467 	kfree(cb);
4468 }
4469 
release_stripe_plug(struct mddev * mddev,struct stripe_head * sh)4470 static void release_stripe_plug(struct mddev *mddev,
4471 				struct stripe_head *sh)
4472 {
4473 	struct blk_plug_cb *blk_cb = blk_check_plugged(
4474 		raid5_unplug, mddev,
4475 		sizeof(struct raid5_plug_cb));
4476 	struct raid5_plug_cb *cb;
4477 
4478 	if (!blk_cb) {
4479 		release_stripe(sh);
4480 		return;
4481 	}
4482 
4483 	cb = container_of(blk_cb, struct raid5_plug_cb, cb);
4484 
4485 	if (cb->list.next == NULL) {
4486 		int i;
4487 		INIT_LIST_HEAD(&cb->list);
4488 		for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
4489 			INIT_LIST_HEAD(cb->temp_inactive_list + i);
4490 	}
4491 
4492 	if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
4493 		list_add_tail(&sh->lru, &cb->list);
4494 	else
4495 		release_stripe(sh);
4496 }
4497 
make_discard_request(struct mddev * mddev,struct bio * bi)4498 static void make_discard_request(struct mddev *mddev, struct bio *bi)
4499 {
4500 	struct r5conf *conf = mddev->private;
4501 	sector_t logical_sector, last_sector;
4502 	struct stripe_head *sh;
4503 	int remaining;
4504 	int stripe_sectors;
4505 
4506 	if (mddev->reshape_position != MaxSector)
4507 		/* Skip discard while reshape is happening */
4508 		return;
4509 
4510 	logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4511 	last_sector = bi->bi_iter.bi_sector + (bi->bi_iter.bi_size>>9);
4512 
4513 	bi->bi_next = NULL;
4514 	bi->bi_phys_segments = 1; /* over-loaded to count active stripes */
4515 
4516 	stripe_sectors = conf->chunk_sectors *
4517 		(conf->raid_disks - conf->max_degraded);
4518 	logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
4519 					       stripe_sectors);
4520 	sector_div(last_sector, stripe_sectors);
4521 
4522 	logical_sector *= conf->chunk_sectors;
4523 	last_sector *= conf->chunk_sectors;
4524 
4525 	for (; logical_sector < last_sector;
4526 	     logical_sector += STRIPE_SECTORS) {
4527 		DEFINE_WAIT(w);
4528 		int d;
4529 	again:
4530 		sh = get_active_stripe(conf, logical_sector, 0, 0, 0);
4531 		prepare_to_wait(&conf->wait_for_overlap, &w,
4532 				TASK_UNINTERRUPTIBLE);
4533 		set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
4534 		if (test_bit(STRIPE_SYNCING, &sh->state)) {
4535 			release_stripe(sh);
4536 			schedule();
4537 			goto again;
4538 		}
4539 		clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
4540 		spin_lock_irq(&sh->stripe_lock);
4541 		for (d = 0; d < conf->raid_disks; d++) {
4542 			if (d == sh->pd_idx || d == sh->qd_idx)
4543 				continue;
4544 			if (sh->dev[d].towrite || sh->dev[d].toread) {
4545 				set_bit(R5_Overlap, &sh->dev[d].flags);
4546 				spin_unlock_irq(&sh->stripe_lock);
4547 				release_stripe(sh);
4548 				schedule();
4549 				goto again;
4550 			}
4551 		}
4552 		set_bit(STRIPE_DISCARD, &sh->state);
4553 		finish_wait(&conf->wait_for_overlap, &w);
4554 		for (d = 0; d < conf->raid_disks; d++) {
4555 			if (d == sh->pd_idx || d == sh->qd_idx)
4556 				continue;
4557 			sh->dev[d].towrite = bi;
4558 			set_bit(R5_OVERWRITE, &sh->dev[d].flags);
4559 			raid5_inc_bi_active_stripes(bi);
4560 		}
4561 		spin_unlock_irq(&sh->stripe_lock);
4562 		if (conf->mddev->bitmap) {
4563 			for (d = 0;
4564 			     d < conf->raid_disks - conf->max_degraded;
4565 			     d++)
4566 				bitmap_startwrite(mddev->bitmap,
4567 						  sh->sector,
4568 						  STRIPE_SECTORS,
4569 						  0);
4570 			sh->bm_seq = conf->seq_flush + 1;
4571 			set_bit(STRIPE_BIT_DELAY, &sh->state);
4572 		}
4573 
4574 		set_bit(STRIPE_HANDLE, &sh->state);
4575 		clear_bit(STRIPE_DELAYED, &sh->state);
4576 		if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4577 			atomic_inc(&conf->preread_active_stripes);
4578 		release_stripe_plug(mddev, sh);
4579 	}
4580 
4581 	remaining = raid5_dec_bi_active_stripes(bi);
4582 	if (remaining == 0) {
4583 		md_write_end(mddev);
4584 		bio_endio(bi, 0);
4585 	}
4586 }
4587 
make_request(struct mddev * mddev,struct bio * bi)4588 static void make_request(struct mddev *mddev, struct bio * bi)
4589 {
4590 	struct r5conf *conf = mddev->private;
4591 	int dd_idx;
4592 	sector_t new_sector;
4593 	sector_t logical_sector, last_sector;
4594 	struct stripe_head *sh;
4595 	const int rw = bio_data_dir(bi);
4596 	int remaining;
4597 	DEFINE_WAIT(w);
4598 	bool do_prepare;
4599 
4600 	if (unlikely(bi->bi_rw & REQ_FLUSH)) {
4601 		md_flush_request(mddev, bi);
4602 		return;
4603 	}
4604 
4605 	md_write_start(mddev, bi);
4606 
4607 	if (rw == READ &&
4608 	     mddev->reshape_position == MaxSector &&
4609 	     chunk_aligned_read(mddev,bi))
4610 		return;
4611 
4612 	if (unlikely(bi->bi_rw & REQ_DISCARD)) {
4613 		make_discard_request(mddev, bi);
4614 		return;
4615 	}
4616 
4617 	logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4618 	last_sector = bio_end_sector(bi);
4619 	bi->bi_next = NULL;
4620 	bi->bi_phys_segments = 1;	/* over-loaded to count active stripes */
4621 
4622 	prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
4623 	for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
4624 		int previous;
4625 		int seq;
4626 
4627 		do_prepare = false;
4628 	retry:
4629 		seq = read_seqcount_begin(&conf->gen_lock);
4630 		previous = 0;
4631 		if (do_prepare)
4632 			prepare_to_wait(&conf->wait_for_overlap, &w,
4633 				TASK_UNINTERRUPTIBLE);
4634 		if (unlikely(conf->reshape_progress != MaxSector)) {
4635 			/* spinlock is needed as reshape_progress may be
4636 			 * 64bit on a 32bit platform, and so it might be
4637 			 * possible to see a half-updated value
4638 			 * Of course reshape_progress could change after
4639 			 * the lock is dropped, so once we get a reference
4640 			 * to the stripe that we think it is, we will have
4641 			 * to check again.
4642 			 */
4643 			spin_lock_irq(&conf->device_lock);
4644 			if (mddev->reshape_backwards
4645 			    ? logical_sector < conf->reshape_progress
4646 			    : logical_sector >= conf->reshape_progress) {
4647 				previous = 1;
4648 			} else {
4649 				if (mddev->reshape_backwards
4650 				    ? logical_sector < conf->reshape_safe
4651 				    : logical_sector >= conf->reshape_safe) {
4652 					spin_unlock_irq(&conf->device_lock);
4653 					schedule();
4654 					do_prepare = true;
4655 					goto retry;
4656 				}
4657 			}
4658 			spin_unlock_irq(&conf->device_lock);
4659 		}
4660 
4661 		new_sector = raid5_compute_sector(conf, logical_sector,
4662 						  previous,
4663 						  &dd_idx, NULL);
4664 		pr_debug("raid456: make_request, sector %llu logical %llu\n",
4665 			(unsigned long long)new_sector,
4666 			(unsigned long long)logical_sector);
4667 
4668 		sh = get_active_stripe(conf, new_sector, previous,
4669 				       (bi->bi_rw&RWA_MASK), 0);
4670 		if (sh) {
4671 			if (unlikely(previous)) {
4672 				/* expansion might have moved on while waiting for a
4673 				 * stripe, so we must do the range check again.
4674 				 * Expansion could still move past after this
4675 				 * test, but as we are holding a reference to
4676 				 * 'sh', we know that if that happens,
4677 				 *  STRIPE_EXPANDING will get set and the expansion
4678 				 * won't proceed until we finish with the stripe.
4679 				 */
4680 				int must_retry = 0;
4681 				spin_lock_irq(&conf->device_lock);
4682 				if (mddev->reshape_backwards
4683 				    ? logical_sector >= conf->reshape_progress
4684 				    : logical_sector < conf->reshape_progress)
4685 					/* mismatch, need to try again */
4686 					must_retry = 1;
4687 				spin_unlock_irq(&conf->device_lock);
4688 				if (must_retry) {
4689 					release_stripe(sh);
4690 					schedule();
4691 					do_prepare = true;
4692 					goto retry;
4693 				}
4694 			}
4695 			if (read_seqcount_retry(&conf->gen_lock, seq)) {
4696 				/* Might have got the wrong stripe_head
4697 				 * by accident
4698 				 */
4699 				release_stripe(sh);
4700 				goto retry;
4701 			}
4702 
4703 			if (rw == WRITE &&
4704 			    logical_sector >= mddev->suspend_lo &&
4705 			    logical_sector < mddev->suspend_hi) {
4706 				release_stripe(sh);
4707 				/* As the suspend_* range is controlled by
4708 				 * userspace, we want an interruptible
4709 				 * wait.
4710 				 */
4711 				prepare_to_wait(&conf->wait_for_overlap,
4712 						&w, TASK_INTERRUPTIBLE);
4713 				if (logical_sector >= mddev->suspend_lo &&
4714 				    logical_sector < mddev->suspend_hi) {
4715 					sigset_t full, old;
4716 					sigfillset(&full);
4717 					sigprocmask(SIG_BLOCK, &full, &old);
4718 					schedule();
4719 					sigprocmask(SIG_SETMASK, &old, NULL);
4720 					do_prepare = true;
4721 				}
4722 				goto retry;
4723 			}
4724 
4725 			if (test_bit(STRIPE_EXPANDING, &sh->state) ||
4726 			    !add_stripe_bio(sh, bi, dd_idx, rw)) {
4727 				/* Stripe is busy expanding or
4728 				 * add failed due to overlap.  Flush everything
4729 				 * and wait a while
4730 				 */
4731 				md_wakeup_thread(mddev->thread);
4732 				release_stripe(sh);
4733 				schedule();
4734 				do_prepare = true;
4735 				goto retry;
4736 			}
4737 			set_bit(STRIPE_HANDLE, &sh->state);
4738 			clear_bit(STRIPE_DELAYED, &sh->state);
4739 			if ((bi->bi_rw & REQ_SYNC) &&
4740 			    !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4741 				atomic_inc(&conf->preread_active_stripes);
4742 			release_stripe_plug(mddev, sh);
4743 		} else {
4744 			/* cannot get stripe for read-ahead, just give-up */
4745 			clear_bit(BIO_UPTODATE, &bi->bi_flags);
4746 			break;
4747 		}
4748 	}
4749 	finish_wait(&conf->wait_for_overlap, &w);
4750 
4751 	remaining = raid5_dec_bi_active_stripes(bi);
4752 	if (remaining == 0) {
4753 
4754 		if ( rw == WRITE )
4755 			md_write_end(mddev);
4756 
4757 		trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
4758 					 bi, 0);
4759 		bio_endio(bi, 0);
4760 	}
4761 }
4762 
4763 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
4764 
reshape_request(struct mddev * mddev,sector_t sector_nr,int * skipped)4765 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
4766 {
4767 	/* reshaping is quite different to recovery/resync so it is
4768 	 * handled quite separately ... here.
4769 	 *
4770 	 * On each call to sync_request, we gather one chunk worth of
4771 	 * destination stripes and flag them as expanding.
4772 	 * Then we find all the source stripes and request reads.
4773 	 * As the reads complete, handle_stripe will copy the data
4774 	 * into the destination stripe and release that stripe.
4775 	 */
4776 	struct r5conf *conf = mddev->private;
4777 	struct stripe_head *sh;
4778 	sector_t first_sector, last_sector;
4779 	int raid_disks = conf->previous_raid_disks;
4780 	int data_disks = raid_disks - conf->max_degraded;
4781 	int new_data_disks = conf->raid_disks - conf->max_degraded;
4782 	int i;
4783 	int dd_idx;
4784 	sector_t writepos, readpos, safepos;
4785 	sector_t stripe_addr;
4786 	int reshape_sectors;
4787 	struct list_head stripes;
4788 
4789 	if (sector_nr == 0) {
4790 		/* If restarting in the middle, skip the initial sectors */
4791 		if (mddev->reshape_backwards &&
4792 		    conf->reshape_progress < raid5_size(mddev, 0, 0)) {
4793 			sector_nr = raid5_size(mddev, 0, 0)
4794 				- conf->reshape_progress;
4795 		} else if (!mddev->reshape_backwards &&
4796 			   conf->reshape_progress > 0)
4797 			sector_nr = conf->reshape_progress;
4798 		sector_div(sector_nr, new_data_disks);
4799 		if (sector_nr) {
4800 			mddev->curr_resync_completed = sector_nr;
4801 			sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4802 			*skipped = 1;
4803 			return sector_nr;
4804 		}
4805 	}
4806 
4807 	/* We need to process a full chunk at a time.
4808 	 * If old and new chunk sizes differ, we need to process the
4809 	 * largest of these
4810 	 */
4811 	if (mddev->new_chunk_sectors > mddev->chunk_sectors)
4812 		reshape_sectors = mddev->new_chunk_sectors;
4813 	else
4814 		reshape_sectors = mddev->chunk_sectors;
4815 
4816 	/* We update the metadata at least every 10 seconds, or when
4817 	 * the data about to be copied would over-write the source of
4818 	 * the data at the front of the range.  i.e. one new_stripe
4819 	 * along from reshape_progress new_maps to after where
4820 	 * reshape_safe old_maps to
4821 	 */
4822 	writepos = conf->reshape_progress;
4823 	sector_div(writepos, new_data_disks);
4824 	readpos = conf->reshape_progress;
4825 	sector_div(readpos, data_disks);
4826 	safepos = conf->reshape_safe;
4827 	sector_div(safepos, data_disks);
4828 	if (mddev->reshape_backwards) {
4829 		writepos -= min_t(sector_t, reshape_sectors, writepos);
4830 		readpos += reshape_sectors;
4831 		safepos += reshape_sectors;
4832 	} else {
4833 		writepos += reshape_sectors;
4834 		readpos -= min_t(sector_t, reshape_sectors, readpos);
4835 		safepos -= min_t(sector_t, reshape_sectors, safepos);
4836 	}
4837 
4838 	/* Having calculated the 'writepos' possibly use it
4839 	 * to set 'stripe_addr' which is where we will write to.
4840 	 */
4841 	if (mddev->reshape_backwards) {
4842 		BUG_ON(conf->reshape_progress == 0);
4843 		stripe_addr = writepos;
4844 		BUG_ON((mddev->dev_sectors &
4845 			~((sector_t)reshape_sectors - 1))
4846 		       - reshape_sectors - stripe_addr
4847 		       != sector_nr);
4848 	} else {
4849 		BUG_ON(writepos != sector_nr + reshape_sectors);
4850 		stripe_addr = sector_nr;
4851 	}
4852 
4853 	/* 'writepos' is the most advanced device address we might write.
4854 	 * 'readpos' is the least advanced device address we might read.
4855 	 * 'safepos' is the least address recorded in the metadata as having
4856 	 *     been reshaped.
4857 	 * If there is a min_offset_diff, these are adjusted either by
4858 	 * increasing the safepos/readpos if diff is negative, or
4859 	 * increasing writepos if diff is positive.
4860 	 * If 'readpos' is then behind 'writepos', there is no way that we can
4861 	 * ensure safety in the face of a crash - that must be done by userspace
4862 	 * making a backup of the data.  So in that case there is no particular
4863 	 * rush to update metadata.
4864 	 * Otherwise if 'safepos' is behind 'writepos', then we really need to
4865 	 * update the metadata to advance 'safepos' to match 'readpos' so that
4866 	 * we can be safe in the event of a crash.
4867 	 * So we insist on updating metadata if safepos is behind writepos and
4868 	 * readpos is beyond writepos.
4869 	 * In any case, update the metadata every 10 seconds.
4870 	 * Maybe that number should be configurable, but I'm not sure it is
4871 	 * worth it.... maybe it could be a multiple of safemode_delay???
4872 	 */
4873 	if (conf->min_offset_diff < 0) {
4874 		safepos += -conf->min_offset_diff;
4875 		readpos += -conf->min_offset_diff;
4876 	} else
4877 		writepos += conf->min_offset_diff;
4878 
4879 	if ((mddev->reshape_backwards
4880 	     ? (safepos > writepos && readpos < writepos)
4881 	     : (safepos < writepos && readpos > writepos)) ||
4882 	    time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
4883 		/* Cannot proceed until we've updated the superblock... */
4884 		wait_event(conf->wait_for_overlap,
4885 			   atomic_read(&conf->reshape_stripes)==0
4886 			   || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
4887 		if (atomic_read(&conf->reshape_stripes) != 0)
4888 			return 0;
4889 		mddev->reshape_position = conf->reshape_progress;
4890 		mddev->curr_resync_completed = sector_nr;
4891 		conf->reshape_checkpoint = jiffies;
4892 		set_bit(MD_CHANGE_DEVS, &mddev->flags);
4893 		md_wakeup_thread(mddev->thread);
4894 		wait_event(mddev->sb_wait, mddev->flags == 0 ||
4895 			   test_bit(MD_RECOVERY_INTR, &mddev->recovery));
4896 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
4897 			return 0;
4898 		spin_lock_irq(&conf->device_lock);
4899 		conf->reshape_safe = mddev->reshape_position;
4900 		spin_unlock_irq(&conf->device_lock);
4901 		wake_up(&conf->wait_for_overlap);
4902 		sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4903 	}
4904 
4905 	INIT_LIST_HEAD(&stripes);
4906 	for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
4907 		int j;
4908 		int skipped_disk = 0;
4909 		sh = get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
4910 		set_bit(STRIPE_EXPANDING, &sh->state);
4911 		atomic_inc(&conf->reshape_stripes);
4912 		/* If any of this stripe is beyond the end of the old
4913 		 * array, then we need to zero those blocks
4914 		 */
4915 		for (j=sh->disks; j--;) {
4916 			sector_t s;
4917 			if (j == sh->pd_idx)
4918 				continue;
4919 			if (conf->level == 6 &&
4920 			    j == sh->qd_idx)
4921 				continue;
4922 			s = compute_blocknr(sh, j, 0);
4923 			if (s < raid5_size(mddev, 0, 0)) {
4924 				skipped_disk = 1;
4925 				continue;
4926 			}
4927 			memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
4928 			set_bit(R5_Expanded, &sh->dev[j].flags);
4929 			set_bit(R5_UPTODATE, &sh->dev[j].flags);
4930 		}
4931 		if (!skipped_disk) {
4932 			set_bit(STRIPE_EXPAND_READY, &sh->state);
4933 			set_bit(STRIPE_HANDLE, &sh->state);
4934 		}
4935 		list_add(&sh->lru, &stripes);
4936 	}
4937 	spin_lock_irq(&conf->device_lock);
4938 	if (mddev->reshape_backwards)
4939 		conf->reshape_progress -= reshape_sectors * new_data_disks;
4940 	else
4941 		conf->reshape_progress += reshape_sectors * new_data_disks;
4942 	spin_unlock_irq(&conf->device_lock);
4943 	/* Ok, those stripe are ready. We can start scheduling
4944 	 * reads on the source stripes.
4945 	 * The source stripes are determined by mapping the first and last
4946 	 * block on the destination stripes.
4947 	 */
4948 	first_sector =
4949 		raid5_compute_sector(conf, stripe_addr*(new_data_disks),
4950 				     1, &dd_idx, NULL);
4951 	last_sector =
4952 		raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
4953 					    * new_data_disks - 1),
4954 				     1, &dd_idx, NULL);
4955 	if (last_sector >= mddev->dev_sectors)
4956 		last_sector = mddev->dev_sectors - 1;
4957 	while (first_sector <= last_sector) {
4958 		sh = get_active_stripe(conf, first_sector, 1, 0, 1);
4959 		set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4960 		set_bit(STRIPE_HANDLE, &sh->state);
4961 		release_stripe(sh);
4962 		first_sector += STRIPE_SECTORS;
4963 	}
4964 	/* Now that the sources are clearly marked, we can release
4965 	 * the destination stripes
4966 	 */
4967 	while (!list_empty(&stripes)) {
4968 		sh = list_entry(stripes.next, struct stripe_head, lru);
4969 		list_del_init(&sh->lru);
4970 		release_stripe(sh);
4971 	}
4972 	/* If this takes us to the resync_max point where we have to pause,
4973 	 * then we need to write out the superblock.
4974 	 */
4975 	sector_nr += reshape_sectors;
4976 	if ((sector_nr - mddev->curr_resync_completed) * 2
4977 	    >= mddev->resync_max - mddev->curr_resync_completed) {
4978 		/* Cannot proceed until we've updated the superblock... */
4979 		wait_event(conf->wait_for_overlap,
4980 			   atomic_read(&conf->reshape_stripes) == 0
4981 			   || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
4982 		if (atomic_read(&conf->reshape_stripes) != 0)
4983 			goto ret;
4984 		mddev->reshape_position = conf->reshape_progress;
4985 		mddev->curr_resync_completed = sector_nr;
4986 		conf->reshape_checkpoint = jiffies;
4987 		set_bit(MD_CHANGE_DEVS, &mddev->flags);
4988 		md_wakeup_thread(mddev->thread);
4989 		wait_event(mddev->sb_wait,
4990 			   !test_bit(MD_CHANGE_DEVS, &mddev->flags)
4991 			   || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
4992 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
4993 			goto ret;
4994 		spin_lock_irq(&conf->device_lock);
4995 		conf->reshape_safe = mddev->reshape_position;
4996 		spin_unlock_irq(&conf->device_lock);
4997 		wake_up(&conf->wait_for_overlap);
4998 		sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4999 	}
5000 ret:
5001 	return reshape_sectors;
5002 }
5003 
5004 /* FIXME go_faster isn't used */
sync_request(struct mddev * mddev,sector_t sector_nr,int * skipped,int go_faster)5005 static inline sector_t sync_request(struct mddev *mddev, sector_t sector_nr, int *skipped, int go_faster)
5006 {
5007 	struct r5conf *conf = mddev->private;
5008 	struct stripe_head *sh;
5009 	sector_t max_sector = mddev->dev_sectors;
5010 	sector_t sync_blocks;
5011 	int still_degraded = 0;
5012 	int i;
5013 
5014 	if (sector_nr >= max_sector) {
5015 		/* just being told to finish up .. nothing much to do */
5016 
5017 		if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
5018 			end_reshape(conf);
5019 			return 0;
5020 		}
5021 
5022 		if (mddev->curr_resync < max_sector) /* aborted */
5023 			bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
5024 					&sync_blocks, 1);
5025 		else /* completed sync */
5026 			conf->fullsync = 0;
5027 		bitmap_close_sync(mddev->bitmap);
5028 
5029 		return 0;
5030 	}
5031 
5032 	/* Allow raid5_quiesce to complete */
5033 	wait_event(conf->wait_for_overlap, conf->quiesce != 2);
5034 
5035 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
5036 		return reshape_request(mddev, sector_nr, skipped);
5037 
5038 	/* No need to check resync_max as we never do more than one
5039 	 * stripe, and as resync_max will always be on a chunk boundary,
5040 	 * if the check in md_do_sync didn't fire, there is no chance
5041 	 * of overstepping resync_max here
5042 	 */
5043 
5044 	/* if there is too many failed drives and we are trying
5045 	 * to resync, then assert that we are finished, because there is
5046 	 * nothing we can do.
5047 	 */
5048 	if (mddev->degraded >= conf->max_degraded &&
5049 	    test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
5050 		sector_t rv = mddev->dev_sectors - sector_nr;
5051 		*skipped = 1;
5052 		return rv;
5053 	}
5054 	if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
5055 	    !conf->fullsync &&
5056 	    !bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
5057 	    sync_blocks >= STRIPE_SECTORS) {
5058 		/* we can skip this block, and probably more */
5059 		sync_blocks /= STRIPE_SECTORS;
5060 		*skipped = 1;
5061 		return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
5062 	}
5063 
5064 	bitmap_cond_end_sync(mddev->bitmap, sector_nr);
5065 
5066 	sh = get_active_stripe(conf, sector_nr, 0, 1, 0);
5067 	if (sh == NULL) {
5068 		sh = get_active_stripe(conf, sector_nr, 0, 0, 0);
5069 		/* make sure we don't swamp the stripe cache if someone else
5070 		 * is trying to get access
5071 		 */
5072 		schedule_timeout_uninterruptible(1);
5073 	}
5074 	/* Need to check if array will still be degraded after recovery/resync
5075 	 * We don't need to check the 'failed' flag as when that gets set,
5076 	 * recovery aborts.
5077 	 */
5078 	for (i = 0; i < conf->raid_disks; i++)
5079 		if (conf->disks[i].rdev == NULL)
5080 			still_degraded = 1;
5081 
5082 	bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
5083 
5084 	set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
5085 	set_bit(STRIPE_HANDLE, &sh->state);
5086 
5087 	release_stripe(sh);
5088 
5089 	return STRIPE_SECTORS;
5090 }
5091 
retry_aligned_read(struct r5conf * conf,struct bio * raid_bio)5092 static int  retry_aligned_read(struct r5conf *conf, struct bio *raid_bio)
5093 {
5094 	/* We may not be able to submit a whole bio at once as there
5095 	 * may not be enough stripe_heads available.
5096 	 * We cannot pre-allocate enough stripe_heads as we may need
5097 	 * more than exist in the cache (if we allow ever large chunks).
5098 	 * So we do one stripe head at a time and record in
5099 	 * ->bi_hw_segments how many have been done.
5100 	 *
5101 	 * We *know* that this entire raid_bio is in one chunk, so
5102 	 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
5103 	 */
5104 	struct stripe_head *sh;
5105 	int dd_idx;
5106 	sector_t sector, logical_sector, last_sector;
5107 	int scnt = 0;
5108 	int remaining;
5109 	int handled = 0;
5110 
5111 	logical_sector = raid_bio->bi_iter.bi_sector &
5112 		~((sector_t)STRIPE_SECTORS-1);
5113 	sector = raid5_compute_sector(conf, logical_sector,
5114 				      0, &dd_idx, NULL);
5115 	last_sector = bio_end_sector(raid_bio);
5116 
5117 	for (; logical_sector < last_sector;
5118 	     logical_sector += STRIPE_SECTORS,
5119 		     sector += STRIPE_SECTORS,
5120 		     scnt++) {
5121 
5122 		if (scnt < raid5_bi_processed_stripes(raid_bio))
5123 			/* already done this stripe */
5124 			continue;
5125 
5126 		sh = get_active_stripe(conf, sector, 0, 1, 1);
5127 
5128 		if (!sh) {
5129 			/* failed to get a stripe - must wait */
5130 			raid5_set_bi_processed_stripes(raid_bio, scnt);
5131 			conf->retry_read_aligned = raid_bio;
5132 			return handled;
5133 		}
5134 
5135 		if (!add_stripe_bio(sh, raid_bio, dd_idx, 0)) {
5136 			release_stripe(sh);
5137 			raid5_set_bi_processed_stripes(raid_bio, scnt);
5138 			conf->retry_read_aligned = raid_bio;
5139 			return handled;
5140 		}
5141 
5142 		set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
5143 		handle_stripe(sh);
5144 		release_stripe(sh);
5145 		handled++;
5146 	}
5147 	remaining = raid5_dec_bi_active_stripes(raid_bio);
5148 	if (remaining == 0) {
5149 		trace_block_bio_complete(bdev_get_queue(raid_bio->bi_bdev),
5150 					 raid_bio, 0);
5151 		bio_endio(raid_bio, 0);
5152 	}
5153 	if (atomic_dec_and_test(&conf->active_aligned_reads))
5154 		wake_up(&conf->wait_for_stripe);
5155 	return handled;
5156 }
5157 
handle_active_stripes(struct r5conf * conf,int group,struct r5worker * worker,struct list_head * temp_inactive_list)5158 static int handle_active_stripes(struct r5conf *conf, int group,
5159 				 struct r5worker *worker,
5160 				 struct list_head *temp_inactive_list)
5161 {
5162 	struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
5163 	int i, batch_size = 0, hash;
5164 	bool release_inactive = false;
5165 
5166 	while (batch_size < MAX_STRIPE_BATCH &&
5167 			(sh = __get_priority_stripe(conf, group)) != NULL)
5168 		batch[batch_size++] = sh;
5169 
5170 	if (batch_size == 0) {
5171 		for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5172 			if (!list_empty(temp_inactive_list + i))
5173 				break;
5174 		if (i == NR_STRIPE_HASH_LOCKS)
5175 			return batch_size;
5176 		release_inactive = true;
5177 	}
5178 	spin_unlock_irq(&conf->device_lock);
5179 
5180 	release_inactive_stripe_list(conf, temp_inactive_list,
5181 				     NR_STRIPE_HASH_LOCKS);
5182 
5183 	if (release_inactive) {
5184 		spin_lock_irq(&conf->device_lock);
5185 		return 0;
5186 	}
5187 
5188 	for (i = 0; i < batch_size; i++)
5189 		handle_stripe(batch[i]);
5190 
5191 	cond_resched();
5192 
5193 	spin_lock_irq(&conf->device_lock);
5194 	for (i = 0; i < batch_size; i++) {
5195 		hash = batch[i]->hash_lock_index;
5196 		__release_stripe(conf, batch[i], &temp_inactive_list[hash]);
5197 	}
5198 	return batch_size;
5199 }
5200 
raid5_do_work(struct work_struct * work)5201 static void raid5_do_work(struct work_struct *work)
5202 {
5203 	struct r5worker *worker = container_of(work, struct r5worker, work);
5204 	struct r5worker_group *group = worker->group;
5205 	struct r5conf *conf = group->conf;
5206 	int group_id = group - conf->worker_groups;
5207 	int handled;
5208 	struct blk_plug plug;
5209 
5210 	pr_debug("+++ raid5worker active\n");
5211 
5212 	blk_start_plug(&plug);
5213 	handled = 0;
5214 	spin_lock_irq(&conf->device_lock);
5215 	while (1) {
5216 		int batch_size, released;
5217 
5218 		released = release_stripe_list(conf, worker->temp_inactive_list);
5219 
5220 		batch_size = handle_active_stripes(conf, group_id, worker,
5221 						   worker->temp_inactive_list);
5222 		worker->working = false;
5223 		if (!batch_size && !released)
5224 			break;
5225 		handled += batch_size;
5226 	}
5227 	pr_debug("%d stripes handled\n", handled);
5228 
5229 	spin_unlock_irq(&conf->device_lock);
5230 
5231 	async_tx_issue_pending_all();
5232 	blk_finish_plug(&plug);
5233 
5234 	pr_debug("--- raid5worker inactive\n");
5235 }
5236 
5237 /*
5238  * This is our raid5 kernel thread.
5239  *
5240  * We scan the hash table for stripes which can be handled now.
5241  * During the scan, completed stripes are saved for us by the interrupt
5242  * handler, so that they will not have to wait for our next wakeup.
5243  */
raid5d(struct md_thread * thread)5244 static void raid5d(struct md_thread *thread)
5245 {
5246 	struct mddev *mddev = thread->mddev;
5247 	struct r5conf *conf = mddev->private;
5248 	int handled;
5249 	struct blk_plug plug;
5250 
5251 	pr_debug("+++ raid5d active\n");
5252 
5253 	md_check_recovery(mddev);
5254 
5255 	blk_start_plug(&plug);
5256 	handled = 0;
5257 	spin_lock_irq(&conf->device_lock);
5258 	while (1) {
5259 		struct bio *bio;
5260 		int batch_size, released;
5261 
5262 		released = release_stripe_list(conf, conf->temp_inactive_list);
5263 
5264 		if (
5265 		    !list_empty(&conf->bitmap_list)) {
5266 			/* Now is a good time to flush some bitmap updates */
5267 			conf->seq_flush++;
5268 			spin_unlock_irq(&conf->device_lock);
5269 			bitmap_unplug(mddev->bitmap);
5270 			spin_lock_irq(&conf->device_lock);
5271 			conf->seq_write = conf->seq_flush;
5272 			activate_bit_delay(conf, conf->temp_inactive_list);
5273 		}
5274 		raid5_activate_delayed(conf);
5275 
5276 		while ((bio = remove_bio_from_retry(conf))) {
5277 			int ok;
5278 			spin_unlock_irq(&conf->device_lock);
5279 			ok = retry_aligned_read(conf, bio);
5280 			spin_lock_irq(&conf->device_lock);
5281 			if (!ok)
5282 				break;
5283 			handled++;
5284 		}
5285 
5286 		batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
5287 						   conf->temp_inactive_list);
5288 		if (!batch_size && !released)
5289 			break;
5290 		handled += batch_size;
5291 
5292 		if (mddev->flags & ~(1<<MD_CHANGE_PENDING)) {
5293 			spin_unlock_irq(&conf->device_lock);
5294 			md_check_recovery(mddev);
5295 			spin_lock_irq(&conf->device_lock);
5296 		}
5297 	}
5298 	pr_debug("%d stripes handled\n", handled);
5299 
5300 	spin_unlock_irq(&conf->device_lock);
5301 
5302 	async_tx_issue_pending_all();
5303 	blk_finish_plug(&plug);
5304 
5305 	pr_debug("--- raid5d inactive\n");
5306 }
5307 
5308 static ssize_t
raid5_show_stripe_cache_size(struct mddev * mddev,char * page)5309 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
5310 {
5311 	struct r5conf *conf = mddev->private;
5312 	if (conf)
5313 		return sprintf(page, "%d\n", conf->max_nr_stripes);
5314 	else
5315 		return 0;
5316 }
5317 
5318 int
raid5_set_cache_size(struct mddev * mddev,int size)5319 raid5_set_cache_size(struct mddev *mddev, int size)
5320 {
5321 	struct r5conf *conf = mddev->private;
5322 	int err;
5323 	int hash;
5324 
5325 	if (size <= 16 || size > 32768)
5326 		return -EINVAL;
5327 	hash = (conf->max_nr_stripes - 1) % NR_STRIPE_HASH_LOCKS;
5328 	while (size < conf->max_nr_stripes) {
5329 		if (drop_one_stripe(conf, hash))
5330 			conf->max_nr_stripes--;
5331 		else
5332 			break;
5333 		hash--;
5334 		if (hash < 0)
5335 			hash = NR_STRIPE_HASH_LOCKS - 1;
5336 	}
5337 	err = md_allow_write(mddev);
5338 	if (err)
5339 		return err;
5340 	hash = conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
5341 	while (size > conf->max_nr_stripes) {
5342 		if (grow_one_stripe(conf, hash))
5343 			conf->max_nr_stripes++;
5344 		else break;
5345 		hash = (hash + 1) % NR_STRIPE_HASH_LOCKS;
5346 	}
5347 	return 0;
5348 }
5349 EXPORT_SYMBOL(raid5_set_cache_size);
5350 
5351 static ssize_t
raid5_store_stripe_cache_size(struct mddev * mddev,const char * page,size_t len)5352 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
5353 {
5354 	struct r5conf *conf = mddev->private;
5355 	unsigned long new;
5356 	int err;
5357 
5358 	if (len >= PAGE_SIZE)
5359 		return -EINVAL;
5360 	if (!conf)
5361 		return -ENODEV;
5362 
5363 	if (kstrtoul(page, 10, &new))
5364 		return -EINVAL;
5365 	err = raid5_set_cache_size(mddev, new);
5366 	if (err)
5367 		return err;
5368 	return len;
5369 }
5370 
5371 static struct md_sysfs_entry
5372 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
5373 				raid5_show_stripe_cache_size,
5374 				raid5_store_stripe_cache_size);
5375 
5376 static ssize_t
raid5_show_preread_threshold(struct mddev * mddev,char * page)5377 raid5_show_preread_threshold(struct mddev *mddev, char *page)
5378 {
5379 	struct r5conf *conf = mddev->private;
5380 	if (conf)
5381 		return sprintf(page, "%d\n", conf->bypass_threshold);
5382 	else
5383 		return 0;
5384 }
5385 
5386 static ssize_t
raid5_store_preread_threshold(struct mddev * mddev,const char * page,size_t len)5387 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
5388 {
5389 	struct r5conf *conf = mddev->private;
5390 	unsigned long new;
5391 	if (len >= PAGE_SIZE)
5392 		return -EINVAL;
5393 	if (!conf)
5394 		return -ENODEV;
5395 
5396 	if (kstrtoul(page, 10, &new))
5397 		return -EINVAL;
5398 	if (new > conf->max_nr_stripes)
5399 		return -EINVAL;
5400 	conf->bypass_threshold = new;
5401 	return len;
5402 }
5403 
5404 static struct md_sysfs_entry
5405 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
5406 					S_IRUGO | S_IWUSR,
5407 					raid5_show_preread_threshold,
5408 					raid5_store_preread_threshold);
5409 
5410 static ssize_t
raid5_show_skip_copy(struct mddev * mddev,char * page)5411 raid5_show_skip_copy(struct mddev *mddev, char *page)
5412 {
5413 	struct r5conf *conf = mddev->private;
5414 	if (conf)
5415 		return sprintf(page, "%d\n", conf->skip_copy);
5416 	else
5417 		return 0;
5418 }
5419 
5420 static ssize_t
raid5_store_skip_copy(struct mddev * mddev,const char * page,size_t len)5421 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
5422 {
5423 	struct r5conf *conf = mddev->private;
5424 	unsigned long new;
5425 	if (len >= PAGE_SIZE)
5426 		return -EINVAL;
5427 	if (!conf)
5428 		return -ENODEV;
5429 
5430 	if (kstrtoul(page, 10, &new))
5431 		return -EINVAL;
5432 	new = !!new;
5433 	if (new == conf->skip_copy)
5434 		return len;
5435 
5436 	mddev_suspend(mddev);
5437 	conf->skip_copy = new;
5438 	if (new)
5439 		mddev->queue->backing_dev_info.capabilities |=
5440 						BDI_CAP_STABLE_WRITES;
5441 	else
5442 		mddev->queue->backing_dev_info.capabilities &=
5443 						~BDI_CAP_STABLE_WRITES;
5444 	mddev_resume(mddev);
5445 	return len;
5446 }
5447 
5448 static struct md_sysfs_entry
5449 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
5450 					raid5_show_skip_copy,
5451 					raid5_store_skip_copy);
5452 
5453 static ssize_t
stripe_cache_active_show(struct mddev * mddev,char * page)5454 stripe_cache_active_show(struct mddev *mddev, char *page)
5455 {
5456 	struct r5conf *conf = mddev->private;
5457 	if (conf)
5458 		return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
5459 	else
5460 		return 0;
5461 }
5462 
5463 static struct md_sysfs_entry
5464 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
5465 
5466 static ssize_t
raid5_show_group_thread_cnt(struct mddev * mddev,char * page)5467 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
5468 {
5469 	struct r5conf *conf = mddev->private;
5470 	if (conf)
5471 		return sprintf(page, "%d\n", conf->worker_cnt_per_group);
5472 	else
5473 		return 0;
5474 }
5475 
5476 static int alloc_thread_groups(struct r5conf *conf, int cnt,
5477 			       int *group_cnt,
5478 			       int *worker_cnt_per_group,
5479 			       struct r5worker_group **worker_groups);
5480 static ssize_t
raid5_store_group_thread_cnt(struct mddev * mddev,const char * page,size_t len)5481 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
5482 {
5483 	struct r5conf *conf = mddev->private;
5484 	unsigned long new;
5485 	int err;
5486 	struct r5worker_group *new_groups, *old_groups;
5487 	int group_cnt, worker_cnt_per_group;
5488 
5489 	if (len >= PAGE_SIZE)
5490 		return -EINVAL;
5491 	if (!conf)
5492 		return -ENODEV;
5493 
5494 	if (kstrtoul(page, 10, &new))
5495 		return -EINVAL;
5496 
5497 	if (new == conf->worker_cnt_per_group)
5498 		return len;
5499 
5500 	mddev_suspend(mddev);
5501 
5502 	old_groups = conf->worker_groups;
5503 	if (old_groups)
5504 		flush_workqueue(raid5_wq);
5505 
5506 	err = alloc_thread_groups(conf, new,
5507 				  &group_cnt, &worker_cnt_per_group,
5508 				  &new_groups);
5509 	if (!err) {
5510 		spin_lock_irq(&conf->device_lock);
5511 		conf->group_cnt = group_cnt;
5512 		conf->worker_cnt_per_group = worker_cnt_per_group;
5513 		conf->worker_groups = new_groups;
5514 		spin_unlock_irq(&conf->device_lock);
5515 
5516 		if (old_groups)
5517 			kfree(old_groups[0].workers);
5518 		kfree(old_groups);
5519 	}
5520 
5521 	mddev_resume(mddev);
5522 
5523 	if (err)
5524 		return err;
5525 	return len;
5526 }
5527 
5528 static struct md_sysfs_entry
5529 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
5530 				raid5_show_group_thread_cnt,
5531 				raid5_store_group_thread_cnt);
5532 
5533 static struct attribute *raid5_attrs[] =  {
5534 	&raid5_stripecache_size.attr,
5535 	&raid5_stripecache_active.attr,
5536 	&raid5_preread_bypass_threshold.attr,
5537 	&raid5_group_thread_cnt.attr,
5538 	&raid5_skip_copy.attr,
5539 	NULL,
5540 };
5541 static struct attribute_group raid5_attrs_group = {
5542 	.name = NULL,
5543 	.attrs = raid5_attrs,
5544 };
5545 
alloc_thread_groups(struct r5conf * conf,int cnt,int * group_cnt,int * worker_cnt_per_group,struct r5worker_group ** worker_groups)5546 static int alloc_thread_groups(struct r5conf *conf, int cnt,
5547 			       int *group_cnt,
5548 			       int *worker_cnt_per_group,
5549 			       struct r5worker_group **worker_groups)
5550 {
5551 	int i, j, k;
5552 	ssize_t size;
5553 	struct r5worker *workers;
5554 
5555 	*worker_cnt_per_group = cnt;
5556 	if (cnt == 0) {
5557 		*group_cnt = 0;
5558 		*worker_groups = NULL;
5559 		return 0;
5560 	}
5561 	*group_cnt = num_possible_nodes();
5562 	size = sizeof(struct r5worker) * cnt;
5563 	workers = kzalloc(size * *group_cnt, GFP_NOIO);
5564 	*worker_groups = kzalloc(sizeof(struct r5worker_group) *
5565 				*group_cnt, GFP_NOIO);
5566 	if (!*worker_groups || !workers) {
5567 		kfree(workers);
5568 		kfree(*worker_groups);
5569 		return -ENOMEM;
5570 	}
5571 
5572 	for (i = 0; i < *group_cnt; i++) {
5573 		struct r5worker_group *group;
5574 
5575 		group = &(*worker_groups)[i];
5576 		INIT_LIST_HEAD(&group->handle_list);
5577 		group->conf = conf;
5578 		group->workers = workers + i * cnt;
5579 
5580 		for (j = 0; j < cnt; j++) {
5581 			struct r5worker *worker = group->workers + j;
5582 			worker->group = group;
5583 			INIT_WORK(&worker->work, raid5_do_work);
5584 
5585 			for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
5586 				INIT_LIST_HEAD(worker->temp_inactive_list + k);
5587 		}
5588 	}
5589 
5590 	return 0;
5591 }
5592 
free_thread_groups(struct r5conf * conf)5593 static void free_thread_groups(struct r5conf *conf)
5594 {
5595 	if (conf->worker_groups)
5596 		kfree(conf->worker_groups[0].workers);
5597 	kfree(conf->worker_groups);
5598 	conf->worker_groups = NULL;
5599 }
5600 
5601 static sector_t
raid5_size(struct mddev * mddev,sector_t sectors,int raid_disks)5602 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
5603 {
5604 	struct r5conf *conf = mddev->private;
5605 
5606 	if (!sectors)
5607 		sectors = mddev->dev_sectors;
5608 	if (!raid_disks)
5609 		/* size is defined by the smallest of previous and new size */
5610 		raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
5611 
5612 	sectors &= ~((sector_t)mddev->chunk_sectors - 1);
5613 	sectors &= ~((sector_t)mddev->new_chunk_sectors - 1);
5614 	return sectors * (raid_disks - conf->max_degraded);
5615 }
5616 
free_scratch_buffer(struct r5conf * conf,struct raid5_percpu * percpu)5617 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
5618 {
5619 	safe_put_page(percpu->spare_page);
5620 	kfree(percpu->scribble);
5621 	percpu->spare_page = NULL;
5622 	percpu->scribble = NULL;
5623 }
5624 
alloc_scratch_buffer(struct r5conf * conf,struct raid5_percpu * percpu)5625 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
5626 {
5627 	if (conf->level == 6 && !percpu->spare_page)
5628 		percpu->spare_page = alloc_page(GFP_KERNEL);
5629 	if (!percpu->scribble)
5630 		percpu->scribble = kmalloc(conf->scribble_len, GFP_KERNEL);
5631 
5632 	if (!percpu->scribble || (conf->level == 6 && !percpu->spare_page)) {
5633 		free_scratch_buffer(conf, percpu);
5634 		return -ENOMEM;
5635 	}
5636 
5637 	return 0;
5638 }
5639 
raid5_free_percpu(struct r5conf * conf)5640 static void raid5_free_percpu(struct r5conf *conf)
5641 {
5642 	unsigned long cpu;
5643 
5644 	if (!conf->percpu)
5645 		return;
5646 
5647 #ifdef CONFIG_HOTPLUG_CPU
5648 	unregister_cpu_notifier(&conf->cpu_notify);
5649 #endif
5650 
5651 	get_online_cpus();
5652 	for_each_possible_cpu(cpu)
5653 		free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
5654 	put_online_cpus();
5655 
5656 	free_percpu(conf->percpu);
5657 }
5658 
free_conf(struct r5conf * conf)5659 static void free_conf(struct r5conf *conf)
5660 {
5661 	free_thread_groups(conf);
5662 	shrink_stripes(conf);
5663 	raid5_free_percpu(conf);
5664 	kfree(conf->disks);
5665 	kfree(conf->stripe_hashtbl);
5666 	kfree(conf);
5667 }
5668 
5669 #ifdef CONFIG_HOTPLUG_CPU
raid456_cpu_notify(struct notifier_block * nfb,unsigned long action,void * hcpu)5670 static int raid456_cpu_notify(struct notifier_block *nfb, unsigned long action,
5671 			      void *hcpu)
5672 {
5673 	struct r5conf *conf = container_of(nfb, struct r5conf, cpu_notify);
5674 	long cpu = (long)hcpu;
5675 	struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
5676 
5677 	switch (action) {
5678 	case CPU_UP_PREPARE:
5679 	case CPU_UP_PREPARE_FROZEN:
5680 		if (alloc_scratch_buffer(conf, percpu)) {
5681 			pr_err("%s: failed memory allocation for cpu%ld\n",
5682 			       __func__, cpu);
5683 			return notifier_from_errno(-ENOMEM);
5684 		}
5685 		break;
5686 	case CPU_DEAD:
5687 	case CPU_DEAD_FROZEN:
5688 		free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
5689 		break;
5690 	default:
5691 		break;
5692 	}
5693 	return NOTIFY_OK;
5694 }
5695 #endif
5696 
raid5_alloc_percpu(struct r5conf * conf)5697 static int raid5_alloc_percpu(struct r5conf *conf)
5698 {
5699 	unsigned long cpu;
5700 	int err = 0;
5701 
5702 	conf->percpu = alloc_percpu(struct raid5_percpu);
5703 	if (!conf->percpu)
5704 		return -ENOMEM;
5705 
5706 #ifdef CONFIG_HOTPLUG_CPU
5707 	conf->cpu_notify.notifier_call = raid456_cpu_notify;
5708 	conf->cpu_notify.priority = 0;
5709 	err = register_cpu_notifier(&conf->cpu_notify);
5710 	if (err)
5711 		return err;
5712 #endif
5713 
5714 	get_online_cpus();
5715 	for_each_present_cpu(cpu) {
5716 		err = alloc_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
5717 		if (err) {
5718 			pr_err("%s: failed memory allocation for cpu%ld\n",
5719 			       __func__, cpu);
5720 			break;
5721 		}
5722 	}
5723 	put_online_cpus();
5724 
5725 	return err;
5726 }
5727 
setup_conf(struct mddev * mddev)5728 static struct r5conf *setup_conf(struct mddev *mddev)
5729 {
5730 	struct r5conf *conf;
5731 	int raid_disk, memory, max_disks;
5732 	struct md_rdev *rdev;
5733 	struct disk_info *disk;
5734 	char pers_name[6];
5735 	int i;
5736 	int group_cnt, worker_cnt_per_group;
5737 	struct r5worker_group *new_group;
5738 
5739 	if (mddev->new_level != 5
5740 	    && mddev->new_level != 4
5741 	    && mddev->new_level != 6) {
5742 		printk(KERN_ERR "md/raid:%s: raid level not set to 4/5/6 (%d)\n",
5743 		       mdname(mddev), mddev->new_level);
5744 		return ERR_PTR(-EIO);
5745 	}
5746 	if ((mddev->new_level == 5
5747 	     && !algorithm_valid_raid5(mddev->new_layout)) ||
5748 	    (mddev->new_level == 6
5749 	     && !algorithm_valid_raid6(mddev->new_layout))) {
5750 		printk(KERN_ERR "md/raid:%s: layout %d not supported\n",
5751 		       mdname(mddev), mddev->new_layout);
5752 		return ERR_PTR(-EIO);
5753 	}
5754 	if (mddev->new_level == 6 && mddev->raid_disks < 4) {
5755 		printk(KERN_ERR "md/raid:%s: not enough configured devices (%d, minimum 4)\n",
5756 		       mdname(mddev), mddev->raid_disks);
5757 		return ERR_PTR(-EINVAL);
5758 	}
5759 
5760 	if (!mddev->new_chunk_sectors ||
5761 	    (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
5762 	    !is_power_of_2(mddev->new_chunk_sectors)) {
5763 		printk(KERN_ERR "md/raid:%s: invalid chunk size %d\n",
5764 		       mdname(mddev), mddev->new_chunk_sectors << 9);
5765 		return ERR_PTR(-EINVAL);
5766 	}
5767 
5768 	conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
5769 	if (conf == NULL)
5770 		goto abort;
5771 	/* Don't enable multi-threading by default*/
5772 	if (!alloc_thread_groups(conf, 0, &group_cnt, &worker_cnt_per_group,
5773 				 &new_group)) {
5774 		conf->group_cnt = group_cnt;
5775 		conf->worker_cnt_per_group = worker_cnt_per_group;
5776 		conf->worker_groups = new_group;
5777 	} else
5778 		goto abort;
5779 	spin_lock_init(&conf->device_lock);
5780 	seqcount_init(&conf->gen_lock);
5781 	init_waitqueue_head(&conf->wait_for_stripe);
5782 	init_waitqueue_head(&conf->wait_for_overlap);
5783 	INIT_LIST_HEAD(&conf->handle_list);
5784 	INIT_LIST_HEAD(&conf->hold_list);
5785 	INIT_LIST_HEAD(&conf->delayed_list);
5786 	INIT_LIST_HEAD(&conf->bitmap_list);
5787 	init_llist_head(&conf->released_stripes);
5788 	atomic_set(&conf->active_stripes, 0);
5789 	atomic_set(&conf->preread_active_stripes, 0);
5790 	atomic_set(&conf->active_aligned_reads, 0);
5791 	conf->bypass_threshold = BYPASS_THRESHOLD;
5792 	conf->recovery_disabled = mddev->recovery_disabled - 1;
5793 
5794 	conf->raid_disks = mddev->raid_disks;
5795 	if (mddev->reshape_position == MaxSector)
5796 		conf->previous_raid_disks = mddev->raid_disks;
5797 	else
5798 		conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
5799 	max_disks = max(conf->raid_disks, conf->previous_raid_disks);
5800 	conf->scribble_len = scribble_len(max_disks);
5801 
5802 	conf->disks = kzalloc(max_disks * sizeof(struct disk_info),
5803 			      GFP_KERNEL);
5804 	if (!conf->disks)
5805 		goto abort;
5806 
5807 	conf->mddev = mddev;
5808 
5809 	if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
5810 		goto abort;
5811 
5812 	/* We init hash_locks[0] separately to that it can be used
5813 	 * as the reference lock in the spin_lock_nest_lock() call
5814 	 * in lock_all_device_hash_locks_irq in order to convince
5815 	 * lockdep that we know what we are doing.
5816 	 */
5817 	spin_lock_init(conf->hash_locks);
5818 	for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
5819 		spin_lock_init(conf->hash_locks + i);
5820 
5821 	for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5822 		INIT_LIST_HEAD(conf->inactive_list + i);
5823 
5824 	for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5825 		INIT_LIST_HEAD(conf->temp_inactive_list + i);
5826 
5827 	conf->level = mddev->new_level;
5828 	if (raid5_alloc_percpu(conf) != 0)
5829 		goto abort;
5830 
5831 	pr_debug("raid456: run(%s) called.\n", mdname(mddev));
5832 
5833 	rdev_for_each(rdev, mddev) {
5834 		raid_disk = rdev->raid_disk;
5835 		if (raid_disk >= max_disks
5836 		    || raid_disk < 0)
5837 			continue;
5838 		disk = conf->disks + raid_disk;
5839 
5840 		if (test_bit(Replacement, &rdev->flags)) {
5841 			if (disk->replacement)
5842 				goto abort;
5843 			disk->replacement = rdev;
5844 		} else {
5845 			if (disk->rdev)
5846 				goto abort;
5847 			disk->rdev = rdev;
5848 		}
5849 
5850 		if (test_bit(In_sync, &rdev->flags)) {
5851 			char b[BDEVNAME_SIZE];
5852 			printk(KERN_INFO "md/raid:%s: device %s operational as raid"
5853 			       " disk %d\n",
5854 			       mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
5855 		} else if (rdev->saved_raid_disk != raid_disk)
5856 			/* Cannot rely on bitmap to complete recovery */
5857 			conf->fullsync = 1;
5858 	}
5859 
5860 	conf->chunk_sectors = mddev->new_chunk_sectors;
5861 	conf->level = mddev->new_level;
5862 	if (conf->level == 6)
5863 		conf->max_degraded = 2;
5864 	else
5865 		conf->max_degraded = 1;
5866 	conf->algorithm = mddev->new_layout;
5867 	conf->reshape_progress = mddev->reshape_position;
5868 	if (conf->reshape_progress != MaxSector) {
5869 		conf->prev_chunk_sectors = mddev->chunk_sectors;
5870 		conf->prev_algo = mddev->layout;
5871 	}
5872 
5873 	memory = conf->max_nr_stripes * (sizeof(struct stripe_head) +
5874 		 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
5875 	atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
5876 	if (grow_stripes(conf, NR_STRIPES)) {
5877 		printk(KERN_ERR
5878 		       "md/raid:%s: couldn't allocate %dkB for buffers\n",
5879 		       mdname(mddev), memory);
5880 		goto abort;
5881 	} else
5882 		printk(KERN_INFO "md/raid:%s: allocated %dkB\n",
5883 		       mdname(mddev), memory);
5884 
5885 	sprintf(pers_name, "raid%d", mddev->new_level);
5886 	conf->thread = md_register_thread(raid5d, mddev, pers_name);
5887 	if (!conf->thread) {
5888 		printk(KERN_ERR
5889 		       "md/raid:%s: couldn't allocate thread.\n",
5890 		       mdname(mddev));
5891 		goto abort;
5892 	}
5893 
5894 	return conf;
5895 
5896  abort:
5897 	if (conf) {
5898 		free_conf(conf);
5899 		return ERR_PTR(-EIO);
5900 	} else
5901 		return ERR_PTR(-ENOMEM);
5902 }
5903 
only_parity(int raid_disk,int algo,int raid_disks,int max_degraded)5904 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
5905 {
5906 	switch (algo) {
5907 	case ALGORITHM_PARITY_0:
5908 		if (raid_disk < max_degraded)
5909 			return 1;
5910 		break;
5911 	case ALGORITHM_PARITY_N:
5912 		if (raid_disk >= raid_disks - max_degraded)
5913 			return 1;
5914 		break;
5915 	case ALGORITHM_PARITY_0_6:
5916 		if (raid_disk == 0 ||
5917 		    raid_disk == raid_disks - 1)
5918 			return 1;
5919 		break;
5920 	case ALGORITHM_LEFT_ASYMMETRIC_6:
5921 	case ALGORITHM_RIGHT_ASYMMETRIC_6:
5922 	case ALGORITHM_LEFT_SYMMETRIC_6:
5923 	case ALGORITHM_RIGHT_SYMMETRIC_6:
5924 		if (raid_disk == raid_disks - 1)
5925 			return 1;
5926 	}
5927 	return 0;
5928 }
5929 
run(struct mddev * mddev)5930 static int run(struct mddev *mddev)
5931 {
5932 	struct r5conf *conf;
5933 	int working_disks = 0;
5934 	int dirty_parity_disks = 0;
5935 	struct md_rdev *rdev;
5936 	sector_t reshape_offset = 0;
5937 	int i;
5938 	long long min_offset_diff = 0;
5939 	int first = 1;
5940 
5941 	if (mddev->recovery_cp != MaxSector)
5942 		printk(KERN_NOTICE "md/raid:%s: not clean"
5943 		       " -- starting background reconstruction\n",
5944 		       mdname(mddev));
5945 
5946 	rdev_for_each(rdev, mddev) {
5947 		long long diff;
5948 		if (rdev->raid_disk < 0)
5949 			continue;
5950 		diff = (rdev->new_data_offset - rdev->data_offset);
5951 		if (first) {
5952 			min_offset_diff = diff;
5953 			first = 0;
5954 		} else if (mddev->reshape_backwards &&
5955 			 diff < min_offset_diff)
5956 			min_offset_diff = diff;
5957 		else if (!mddev->reshape_backwards &&
5958 			 diff > min_offset_diff)
5959 			min_offset_diff = diff;
5960 	}
5961 
5962 	if (mddev->reshape_position != MaxSector) {
5963 		/* Check that we can continue the reshape.
5964 		 * Difficulties arise if the stripe we would write to
5965 		 * next is at or after the stripe we would read from next.
5966 		 * For a reshape that changes the number of devices, this
5967 		 * is only possible for a very short time, and mdadm makes
5968 		 * sure that time appears to have past before assembling
5969 		 * the array.  So we fail if that time hasn't passed.
5970 		 * For a reshape that keeps the number of devices the same
5971 		 * mdadm must be monitoring the reshape can keeping the
5972 		 * critical areas read-only and backed up.  It will start
5973 		 * the array in read-only mode, so we check for that.
5974 		 */
5975 		sector_t here_new, here_old;
5976 		int old_disks;
5977 		int max_degraded = (mddev->level == 6 ? 2 : 1);
5978 
5979 		if (mddev->new_level != mddev->level) {
5980 			printk(KERN_ERR "md/raid:%s: unsupported reshape "
5981 			       "required - aborting.\n",
5982 			       mdname(mddev));
5983 			return -EINVAL;
5984 		}
5985 		old_disks = mddev->raid_disks - mddev->delta_disks;
5986 		/* reshape_position must be on a new-stripe boundary, and one
5987 		 * further up in new geometry must map after here in old
5988 		 * geometry.
5989 		 */
5990 		here_new = mddev->reshape_position;
5991 		if (sector_div(here_new, mddev->new_chunk_sectors *
5992 			       (mddev->raid_disks - max_degraded))) {
5993 			printk(KERN_ERR "md/raid:%s: reshape_position not "
5994 			       "on a stripe boundary\n", mdname(mddev));
5995 			return -EINVAL;
5996 		}
5997 		reshape_offset = here_new * mddev->new_chunk_sectors;
5998 		/* here_new is the stripe we will write to */
5999 		here_old = mddev->reshape_position;
6000 		sector_div(here_old, mddev->chunk_sectors *
6001 			   (old_disks-max_degraded));
6002 		/* here_old is the first stripe that we might need to read
6003 		 * from */
6004 		if (mddev->delta_disks == 0) {
6005 			if ((here_new * mddev->new_chunk_sectors !=
6006 			     here_old * mddev->chunk_sectors)) {
6007 				printk(KERN_ERR "md/raid:%s: reshape position is"
6008 				       " confused - aborting\n", mdname(mddev));
6009 				return -EINVAL;
6010 			}
6011 			/* We cannot be sure it is safe to start an in-place
6012 			 * reshape.  It is only safe if user-space is monitoring
6013 			 * and taking constant backups.
6014 			 * mdadm always starts a situation like this in
6015 			 * readonly mode so it can take control before
6016 			 * allowing any writes.  So just check for that.
6017 			 */
6018 			if (abs(min_offset_diff) >= mddev->chunk_sectors &&
6019 			    abs(min_offset_diff) >= mddev->new_chunk_sectors)
6020 				/* not really in-place - so OK */;
6021 			else if (mddev->ro == 0) {
6022 				printk(KERN_ERR "md/raid:%s: in-place reshape "
6023 				       "must be started in read-only mode "
6024 				       "- aborting\n",
6025 				       mdname(mddev));
6026 				return -EINVAL;
6027 			}
6028 		} else if (mddev->reshape_backwards
6029 		    ? (here_new * mddev->new_chunk_sectors + min_offset_diff <=
6030 		       here_old * mddev->chunk_sectors)
6031 		    : (here_new * mddev->new_chunk_sectors >=
6032 		       here_old * mddev->chunk_sectors + (-min_offset_diff))) {
6033 			/* Reading from the same stripe as writing to - bad */
6034 			printk(KERN_ERR "md/raid:%s: reshape_position too early for "
6035 			       "auto-recovery - aborting.\n",
6036 			       mdname(mddev));
6037 			return -EINVAL;
6038 		}
6039 		printk(KERN_INFO "md/raid:%s: reshape will continue\n",
6040 		       mdname(mddev));
6041 		/* OK, we should be able to continue; */
6042 	} else {
6043 		BUG_ON(mddev->level != mddev->new_level);
6044 		BUG_ON(mddev->layout != mddev->new_layout);
6045 		BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
6046 		BUG_ON(mddev->delta_disks != 0);
6047 	}
6048 
6049 	if (mddev->private == NULL)
6050 		conf = setup_conf(mddev);
6051 	else
6052 		conf = mddev->private;
6053 
6054 	if (IS_ERR(conf))
6055 		return PTR_ERR(conf);
6056 
6057 	conf->min_offset_diff = min_offset_diff;
6058 	mddev->thread = conf->thread;
6059 	conf->thread = NULL;
6060 	mddev->private = conf;
6061 
6062 	for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
6063 	     i++) {
6064 		rdev = conf->disks[i].rdev;
6065 		if (!rdev && conf->disks[i].replacement) {
6066 			/* The replacement is all we have yet */
6067 			rdev = conf->disks[i].replacement;
6068 			conf->disks[i].replacement = NULL;
6069 			clear_bit(Replacement, &rdev->flags);
6070 			conf->disks[i].rdev = rdev;
6071 		}
6072 		if (!rdev)
6073 			continue;
6074 		if (conf->disks[i].replacement &&
6075 		    conf->reshape_progress != MaxSector) {
6076 			/* replacements and reshape simply do not mix. */
6077 			printk(KERN_ERR "md: cannot handle concurrent "
6078 			       "replacement and reshape.\n");
6079 			goto abort;
6080 		}
6081 		if (test_bit(In_sync, &rdev->flags)) {
6082 			working_disks++;
6083 			continue;
6084 		}
6085 		/* This disc is not fully in-sync.  However if it
6086 		 * just stored parity (beyond the recovery_offset),
6087 		 * when we don't need to be concerned about the
6088 		 * array being dirty.
6089 		 * When reshape goes 'backwards', we never have
6090 		 * partially completed devices, so we only need
6091 		 * to worry about reshape going forwards.
6092 		 */
6093 		/* Hack because v0.91 doesn't store recovery_offset properly. */
6094 		if (mddev->major_version == 0 &&
6095 		    mddev->minor_version > 90)
6096 			rdev->recovery_offset = reshape_offset;
6097 
6098 		if (rdev->recovery_offset < reshape_offset) {
6099 			/* We need to check old and new layout */
6100 			if (!only_parity(rdev->raid_disk,
6101 					 conf->algorithm,
6102 					 conf->raid_disks,
6103 					 conf->max_degraded))
6104 				continue;
6105 		}
6106 		if (!only_parity(rdev->raid_disk,
6107 				 conf->prev_algo,
6108 				 conf->previous_raid_disks,
6109 				 conf->max_degraded))
6110 			continue;
6111 		dirty_parity_disks++;
6112 	}
6113 
6114 	/*
6115 	 * 0 for a fully functional array, 1 or 2 for a degraded array.
6116 	 */
6117 	mddev->degraded = calc_degraded(conf);
6118 
6119 	if (has_failed(conf)) {
6120 		printk(KERN_ERR "md/raid:%s: not enough operational devices"
6121 			" (%d/%d failed)\n",
6122 			mdname(mddev), mddev->degraded, conf->raid_disks);
6123 		goto abort;
6124 	}
6125 
6126 	/* device size must be a multiple of chunk size */
6127 	mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
6128 	mddev->resync_max_sectors = mddev->dev_sectors;
6129 
6130 	if (mddev->degraded > dirty_parity_disks &&
6131 	    mddev->recovery_cp != MaxSector) {
6132 		if (mddev->ok_start_degraded)
6133 			printk(KERN_WARNING
6134 			       "md/raid:%s: starting dirty degraded array"
6135 			       " - data corruption possible.\n",
6136 			       mdname(mddev));
6137 		else {
6138 			printk(KERN_ERR
6139 			       "md/raid:%s: cannot start dirty degraded array.\n",
6140 			       mdname(mddev));
6141 			goto abort;
6142 		}
6143 	}
6144 
6145 	if (mddev->degraded == 0)
6146 		printk(KERN_INFO "md/raid:%s: raid level %d active with %d out of %d"
6147 		       " devices, algorithm %d\n", mdname(mddev), conf->level,
6148 		       mddev->raid_disks-mddev->degraded, mddev->raid_disks,
6149 		       mddev->new_layout);
6150 	else
6151 		printk(KERN_ALERT "md/raid:%s: raid level %d active with %d"
6152 		       " out of %d devices, algorithm %d\n",
6153 		       mdname(mddev), conf->level,
6154 		       mddev->raid_disks - mddev->degraded,
6155 		       mddev->raid_disks, mddev->new_layout);
6156 
6157 	print_raid5_conf(conf);
6158 
6159 	if (conf->reshape_progress != MaxSector) {
6160 		conf->reshape_safe = conf->reshape_progress;
6161 		atomic_set(&conf->reshape_stripes, 0);
6162 		clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
6163 		clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
6164 		set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
6165 		set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
6166 		mddev->sync_thread = md_register_thread(md_do_sync, mddev,
6167 							"reshape");
6168 	}
6169 
6170 	/* Ok, everything is just fine now */
6171 	if (mddev->to_remove == &raid5_attrs_group)
6172 		mddev->to_remove = NULL;
6173 	else if (mddev->kobj.sd &&
6174 	    sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
6175 		printk(KERN_WARNING
6176 		       "raid5: failed to create sysfs attributes for %s\n",
6177 		       mdname(mddev));
6178 	md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
6179 
6180 	if (mddev->queue) {
6181 		int chunk_size;
6182 		bool discard_supported = true;
6183 		/* read-ahead size must cover two whole stripes, which
6184 		 * is 2 * (datadisks) * chunksize where 'n' is the
6185 		 * number of raid devices
6186 		 */
6187 		int data_disks = conf->previous_raid_disks - conf->max_degraded;
6188 		int stripe = data_disks *
6189 			((mddev->chunk_sectors << 9) / PAGE_SIZE);
6190 		if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
6191 			mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
6192 
6193 		blk_queue_merge_bvec(mddev->queue, raid5_mergeable_bvec);
6194 
6195 		mddev->queue->backing_dev_info.congested_data = mddev;
6196 		mddev->queue->backing_dev_info.congested_fn = raid5_congested;
6197 
6198 		chunk_size = mddev->chunk_sectors << 9;
6199 		blk_queue_io_min(mddev->queue, chunk_size);
6200 		blk_queue_io_opt(mddev->queue, chunk_size *
6201 				 (conf->raid_disks - conf->max_degraded));
6202 		mddev->queue->limits.raid_partial_stripes_expensive = 1;
6203 		/*
6204 		 * We can only discard a whole stripe. It doesn't make sense to
6205 		 * discard data disk but write parity disk
6206 		 */
6207 		stripe = stripe * PAGE_SIZE;
6208 		/* Round up to power of 2, as discard handling
6209 		 * currently assumes that */
6210 		while ((stripe-1) & stripe)
6211 			stripe = (stripe | (stripe-1)) + 1;
6212 		mddev->queue->limits.discard_alignment = stripe;
6213 		mddev->queue->limits.discard_granularity = stripe;
6214 
6215 		/*
6216 		 * We use 16-bit counter of active stripes in bi_phys_segments
6217 		 * (minus one for over-loaded initialization)
6218 		 */
6219 		blk_queue_max_hw_sectors(mddev->queue, 0xfffe * STRIPE_SECTORS);
6220 		blk_queue_max_discard_sectors(mddev->queue,
6221 					      0xfffe * STRIPE_SECTORS);
6222 
6223 		/*
6224 		 * unaligned part of discard request will be ignored, so can't
6225 		 * guarantee discard_zeroes_data
6226 		 */
6227 		mddev->queue->limits.discard_zeroes_data = 0;
6228 
6229 		blk_queue_max_write_same_sectors(mddev->queue, 0);
6230 
6231 		rdev_for_each(rdev, mddev) {
6232 			disk_stack_limits(mddev->gendisk, rdev->bdev,
6233 					  rdev->data_offset << 9);
6234 			disk_stack_limits(mddev->gendisk, rdev->bdev,
6235 					  rdev->new_data_offset << 9);
6236 			/*
6237 			 * discard_zeroes_data is required, otherwise data
6238 			 * could be lost. Consider a scenario: discard a stripe
6239 			 * (the stripe could be inconsistent if
6240 			 * discard_zeroes_data is 0); write one disk of the
6241 			 * stripe (the stripe could be inconsistent again
6242 			 * depending on which disks are used to calculate
6243 			 * parity); the disk is broken; The stripe data of this
6244 			 * disk is lost.
6245 			 */
6246 			if (!blk_queue_discard(bdev_get_queue(rdev->bdev)) ||
6247 			    !bdev_get_queue(rdev->bdev)->
6248 						limits.discard_zeroes_data)
6249 				discard_supported = false;
6250 			/* Unfortunately, discard_zeroes_data is not currently
6251 			 * a guarantee - just a hint.  So we only allow DISCARD
6252 			 * if the sysadmin has confirmed that only safe devices
6253 			 * are in use by setting a module parameter.
6254 			 */
6255 			if (!devices_handle_discard_safely) {
6256 				if (discard_supported) {
6257 					pr_info("md/raid456: discard support disabled due to uncertainty.\n");
6258 					pr_info("Set raid456.devices_handle_discard_safely=Y to override.\n");
6259 				}
6260 				discard_supported = false;
6261 			}
6262 		}
6263 
6264 		if (discard_supported &&
6265 		    mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
6266 		    mddev->queue->limits.discard_granularity >= stripe)
6267 			queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
6268 						mddev->queue);
6269 		else
6270 			queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
6271 						mddev->queue);
6272 	}
6273 
6274 	return 0;
6275 abort:
6276 	md_unregister_thread(&mddev->thread);
6277 	print_raid5_conf(conf);
6278 	free_conf(conf);
6279 	mddev->private = NULL;
6280 	printk(KERN_ALERT "md/raid:%s: failed to run raid set.\n", mdname(mddev));
6281 	return -EIO;
6282 }
6283 
stop(struct mddev * mddev)6284 static int stop(struct mddev *mddev)
6285 {
6286 	struct r5conf *conf = mddev->private;
6287 
6288 	md_unregister_thread(&mddev->thread);
6289 	if (mddev->queue)
6290 		mddev->queue->backing_dev_info.congested_fn = NULL;
6291 	free_conf(conf);
6292 	mddev->private = NULL;
6293 	mddev->to_remove = &raid5_attrs_group;
6294 	return 0;
6295 }
6296 
status(struct seq_file * seq,struct mddev * mddev)6297 static void status(struct seq_file *seq, struct mddev *mddev)
6298 {
6299 	struct r5conf *conf = mddev->private;
6300 	int i;
6301 
6302 	seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
6303 		mddev->chunk_sectors / 2, mddev->layout);
6304 	seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
6305 	for (i = 0; i < conf->raid_disks; i++)
6306 		seq_printf (seq, "%s",
6307 			       conf->disks[i].rdev &&
6308 			       test_bit(In_sync, &conf->disks[i].rdev->flags) ? "U" : "_");
6309 	seq_printf (seq, "]");
6310 }
6311 
print_raid5_conf(struct r5conf * conf)6312 static void print_raid5_conf (struct r5conf *conf)
6313 {
6314 	int i;
6315 	struct disk_info *tmp;
6316 
6317 	printk(KERN_DEBUG "RAID conf printout:\n");
6318 	if (!conf) {
6319 		printk("(conf==NULL)\n");
6320 		return;
6321 	}
6322 	printk(KERN_DEBUG " --- level:%d rd:%d wd:%d\n", conf->level,
6323 	       conf->raid_disks,
6324 	       conf->raid_disks - conf->mddev->degraded);
6325 
6326 	for (i = 0; i < conf->raid_disks; i++) {
6327 		char b[BDEVNAME_SIZE];
6328 		tmp = conf->disks + i;
6329 		if (tmp->rdev)
6330 			printk(KERN_DEBUG " disk %d, o:%d, dev:%s\n",
6331 			       i, !test_bit(Faulty, &tmp->rdev->flags),
6332 			       bdevname(tmp->rdev->bdev, b));
6333 	}
6334 }
6335 
raid5_spare_active(struct mddev * mddev)6336 static int raid5_spare_active(struct mddev *mddev)
6337 {
6338 	int i;
6339 	struct r5conf *conf = mddev->private;
6340 	struct disk_info *tmp;
6341 	int count = 0;
6342 	unsigned long flags;
6343 
6344 	for (i = 0; i < conf->raid_disks; i++) {
6345 		tmp = conf->disks + i;
6346 		if (tmp->replacement
6347 		    && tmp->replacement->recovery_offset == MaxSector
6348 		    && !test_bit(Faulty, &tmp->replacement->flags)
6349 		    && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
6350 			/* Replacement has just become active. */
6351 			if (!tmp->rdev
6352 			    || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
6353 				count++;
6354 			if (tmp->rdev) {
6355 				/* Replaced device not technically faulty,
6356 				 * but we need to be sure it gets removed
6357 				 * and never re-added.
6358 				 */
6359 				set_bit(Faulty, &tmp->rdev->flags);
6360 				sysfs_notify_dirent_safe(
6361 					tmp->rdev->sysfs_state);
6362 			}
6363 			sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
6364 		} else if (tmp->rdev
6365 		    && tmp->rdev->recovery_offset == MaxSector
6366 		    && !test_bit(Faulty, &tmp->rdev->flags)
6367 		    && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
6368 			count++;
6369 			sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
6370 		}
6371 	}
6372 	spin_lock_irqsave(&conf->device_lock, flags);
6373 	mddev->degraded = calc_degraded(conf);
6374 	spin_unlock_irqrestore(&conf->device_lock, flags);
6375 	print_raid5_conf(conf);
6376 	return count;
6377 }
6378 
raid5_remove_disk(struct mddev * mddev,struct md_rdev * rdev)6379 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
6380 {
6381 	struct r5conf *conf = mddev->private;
6382 	int err = 0;
6383 	int number = rdev->raid_disk;
6384 	struct md_rdev **rdevp;
6385 	struct disk_info *p = conf->disks + number;
6386 
6387 	print_raid5_conf(conf);
6388 	if (rdev == p->rdev)
6389 		rdevp = &p->rdev;
6390 	else if (rdev == p->replacement)
6391 		rdevp = &p->replacement;
6392 	else
6393 		return 0;
6394 
6395 	if (number >= conf->raid_disks &&
6396 	    conf->reshape_progress == MaxSector)
6397 		clear_bit(In_sync, &rdev->flags);
6398 
6399 	if (test_bit(In_sync, &rdev->flags) ||
6400 	    atomic_read(&rdev->nr_pending)) {
6401 		err = -EBUSY;
6402 		goto abort;
6403 	}
6404 	/* Only remove non-faulty devices if recovery
6405 	 * isn't possible.
6406 	 */
6407 	if (!test_bit(Faulty, &rdev->flags) &&
6408 	    mddev->recovery_disabled != conf->recovery_disabled &&
6409 	    !has_failed(conf) &&
6410 	    (!p->replacement || p->replacement == rdev) &&
6411 	    number < conf->raid_disks) {
6412 		err = -EBUSY;
6413 		goto abort;
6414 	}
6415 	*rdevp = NULL;
6416 	synchronize_rcu();
6417 	if (atomic_read(&rdev->nr_pending)) {
6418 		/* lost the race, try later */
6419 		err = -EBUSY;
6420 		*rdevp = rdev;
6421 	} else if (p->replacement) {
6422 		/* We must have just cleared 'rdev' */
6423 		p->rdev = p->replacement;
6424 		clear_bit(Replacement, &p->replacement->flags);
6425 		smp_mb(); /* Make sure other CPUs may see both as identical
6426 			   * but will never see neither - if they are careful
6427 			   */
6428 		p->replacement = NULL;
6429 		clear_bit(WantReplacement, &rdev->flags);
6430 	} else
6431 		/* We might have just removed the Replacement as faulty-
6432 		 * clear the bit just in case
6433 		 */
6434 		clear_bit(WantReplacement, &rdev->flags);
6435 abort:
6436 
6437 	print_raid5_conf(conf);
6438 	return err;
6439 }
6440 
raid5_add_disk(struct mddev * mddev,struct md_rdev * rdev)6441 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
6442 {
6443 	struct r5conf *conf = mddev->private;
6444 	int err = -EEXIST;
6445 	int disk;
6446 	struct disk_info *p;
6447 	int first = 0;
6448 	int last = conf->raid_disks - 1;
6449 
6450 	if (mddev->recovery_disabled == conf->recovery_disabled)
6451 		return -EBUSY;
6452 
6453 	if (rdev->saved_raid_disk < 0 && has_failed(conf))
6454 		/* no point adding a device */
6455 		return -EINVAL;
6456 
6457 	if (rdev->raid_disk >= 0)
6458 		first = last = rdev->raid_disk;
6459 
6460 	/*
6461 	 * find the disk ... but prefer rdev->saved_raid_disk
6462 	 * if possible.
6463 	 */
6464 	if (rdev->saved_raid_disk >= 0 &&
6465 	    rdev->saved_raid_disk >= first &&
6466 	    conf->disks[rdev->saved_raid_disk].rdev == NULL)
6467 		first = rdev->saved_raid_disk;
6468 
6469 	for (disk = first; disk <= last; disk++) {
6470 		p = conf->disks + disk;
6471 		if (p->rdev == NULL) {
6472 			clear_bit(In_sync, &rdev->flags);
6473 			rdev->raid_disk = disk;
6474 			err = 0;
6475 			if (rdev->saved_raid_disk != disk)
6476 				conf->fullsync = 1;
6477 			rcu_assign_pointer(p->rdev, rdev);
6478 			goto out;
6479 		}
6480 	}
6481 	for (disk = first; disk <= last; disk++) {
6482 		p = conf->disks + disk;
6483 		if (test_bit(WantReplacement, &p->rdev->flags) &&
6484 		    p->replacement == NULL) {
6485 			clear_bit(In_sync, &rdev->flags);
6486 			set_bit(Replacement, &rdev->flags);
6487 			rdev->raid_disk = disk;
6488 			err = 0;
6489 			conf->fullsync = 1;
6490 			rcu_assign_pointer(p->replacement, rdev);
6491 			break;
6492 		}
6493 	}
6494 out:
6495 	print_raid5_conf(conf);
6496 	return err;
6497 }
6498 
raid5_resize(struct mddev * mddev,sector_t sectors)6499 static int raid5_resize(struct mddev *mddev, sector_t sectors)
6500 {
6501 	/* no resync is happening, and there is enough space
6502 	 * on all devices, so we can resize.
6503 	 * We need to make sure resync covers any new space.
6504 	 * If the array is shrinking we should possibly wait until
6505 	 * any io in the removed space completes, but it hardly seems
6506 	 * worth it.
6507 	 */
6508 	sector_t newsize;
6509 	sectors &= ~((sector_t)mddev->chunk_sectors - 1);
6510 	newsize = raid5_size(mddev, sectors, mddev->raid_disks);
6511 	if (mddev->external_size &&
6512 	    mddev->array_sectors > newsize)
6513 		return -EINVAL;
6514 	if (mddev->bitmap) {
6515 		int ret = bitmap_resize(mddev->bitmap, sectors, 0, 0);
6516 		if (ret)
6517 			return ret;
6518 	}
6519 	md_set_array_sectors(mddev, newsize);
6520 	set_capacity(mddev->gendisk, mddev->array_sectors);
6521 	revalidate_disk(mddev->gendisk);
6522 	if (sectors > mddev->dev_sectors &&
6523 	    mddev->recovery_cp > mddev->dev_sectors) {
6524 		mddev->recovery_cp = mddev->dev_sectors;
6525 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6526 	}
6527 	mddev->dev_sectors = sectors;
6528 	mddev->resync_max_sectors = sectors;
6529 	return 0;
6530 }
6531 
check_stripe_cache(struct mddev * mddev)6532 static int check_stripe_cache(struct mddev *mddev)
6533 {
6534 	/* Can only proceed if there are plenty of stripe_heads.
6535 	 * We need a minimum of one full stripe,, and for sensible progress
6536 	 * it is best to have about 4 times that.
6537 	 * If we require 4 times, then the default 256 4K stripe_heads will
6538 	 * allow for chunk sizes up to 256K, which is probably OK.
6539 	 * If the chunk size is greater, user-space should request more
6540 	 * stripe_heads first.
6541 	 */
6542 	struct r5conf *conf = mddev->private;
6543 	if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
6544 	    > conf->max_nr_stripes ||
6545 	    ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
6546 	    > conf->max_nr_stripes) {
6547 		printk(KERN_WARNING "md/raid:%s: reshape: not enough stripes.  Needed %lu\n",
6548 		       mdname(mddev),
6549 		       ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
6550 			/ STRIPE_SIZE)*4);
6551 		return 0;
6552 	}
6553 	return 1;
6554 }
6555 
check_reshape(struct mddev * mddev)6556 static int check_reshape(struct mddev *mddev)
6557 {
6558 	struct r5conf *conf = mddev->private;
6559 
6560 	if (mddev->delta_disks == 0 &&
6561 	    mddev->new_layout == mddev->layout &&
6562 	    mddev->new_chunk_sectors == mddev->chunk_sectors)
6563 		return 0; /* nothing to do */
6564 	if (has_failed(conf))
6565 		return -EINVAL;
6566 	if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
6567 		/* We might be able to shrink, but the devices must
6568 		 * be made bigger first.
6569 		 * For raid6, 4 is the minimum size.
6570 		 * Otherwise 2 is the minimum
6571 		 */
6572 		int min = 2;
6573 		if (mddev->level == 6)
6574 			min = 4;
6575 		if (mddev->raid_disks + mddev->delta_disks < min)
6576 			return -EINVAL;
6577 	}
6578 
6579 	if (!check_stripe_cache(mddev))
6580 		return -ENOSPC;
6581 
6582 	return resize_stripes(conf, (conf->previous_raid_disks
6583 				     + mddev->delta_disks));
6584 }
6585 
raid5_start_reshape(struct mddev * mddev)6586 static int raid5_start_reshape(struct mddev *mddev)
6587 {
6588 	struct r5conf *conf = mddev->private;
6589 	struct md_rdev *rdev;
6590 	int spares = 0;
6591 	unsigned long flags;
6592 
6593 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
6594 		return -EBUSY;
6595 
6596 	if (!check_stripe_cache(mddev))
6597 		return -ENOSPC;
6598 
6599 	if (has_failed(conf))
6600 		return -EINVAL;
6601 
6602 	rdev_for_each(rdev, mddev) {
6603 		if (!test_bit(In_sync, &rdev->flags)
6604 		    && !test_bit(Faulty, &rdev->flags))
6605 			spares++;
6606 	}
6607 
6608 	if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
6609 		/* Not enough devices even to make a degraded array
6610 		 * of that size
6611 		 */
6612 		return -EINVAL;
6613 
6614 	/* Refuse to reduce size of the array.  Any reductions in
6615 	 * array size must be through explicit setting of array_size
6616 	 * attribute.
6617 	 */
6618 	if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
6619 	    < mddev->array_sectors) {
6620 		printk(KERN_ERR "md/raid:%s: array size must be reduced "
6621 		       "before number of disks\n", mdname(mddev));
6622 		return -EINVAL;
6623 	}
6624 
6625 	atomic_set(&conf->reshape_stripes, 0);
6626 	spin_lock_irq(&conf->device_lock);
6627 	write_seqcount_begin(&conf->gen_lock);
6628 	conf->previous_raid_disks = conf->raid_disks;
6629 	conf->raid_disks += mddev->delta_disks;
6630 	conf->prev_chunk_sectors = conf->chunk_sectors;
6631 	conf->chunk_sectors = mddev->new_chunk_sectors;
6632 	conf->prev_algo = conf->algorithm;
6633 	conf->algorithm = mddev->new_layout;
6634 	conf->generation++;
6635 	/* Code that selects data_offset needs to see the generation update
6636 	 * if reshape_progress has been set - so a memory barrier needed.
6637 	 */
6638 	smp_mb();
6639 	if (mddev->reshape_backwards)
6640 		conf->reshape_progress = raid5_size(mddev, 0, 0);
6641 	else
6642 		conf->reshape_progress = 0;
6643 	conf->reshape_safe = conf->reshape_progress;
6644 	write_seqcount_end(&conf->gen_lock);
6645 	spin_unlock_irq(&conf->device_lock);
6646 
6647 	/* Now make sure any requests that proceeded on the assumption
6648 	 * the reshape wasn't running - like Discard or Read - have
6649 	 * completed.
6650 	 */
6651 	mddev_suspend(mddev);
6652 	mddev_resume(mddev);
6653 
6654 	/* Add some new drives, as many as will fit.
6655 	 * We know there are enough to make the newly sized array work.
6656 	 * Don't add devices if we are reducing the number of
6657 	 * devices in the array.  This is because it is not possible
6658 	 * to correctly record the "partially reconstructed" state of
6659 	 * such devices during the reshape and confusion could result.
6660 	 */
6661 	if (mddev->delta_disks >= 0) {
6662 		rdev_for_each(rdev, mddev)
6663 			if (rdev->raid_disk < 0 &&
6664 			    !test_bit(Faulty, &rdev->flags)) {
6665 				if (raid5_add_disk(mddev, rdev) == 0) {
6666 					if (rdev->raid_disk
6667 					    >= conf->previous_raid_disks)
6668 						set_bit(In_sync, &rdev->flags);
6669 					else
6670 						rdev->recovery_offset = 0;
6671 
6672 					if (sysfs_link_rdev(mddev, rdev))
6673 						/* Failure here is OK */;
6674 				}
6675 			} else if (rdev->raid_disk >= conf->previous_raid_disks
6676 				   && !test_bit(Faulty, &rdev->flags)) {
6677 				/* This is a spare that was manually added */
6678 				set_bit(In_sync, &rdev->flags);
6679 			}
6680 
6681 		/* When a reshape changes the number of devices,
6682 		 * ->degraded is measured against the larger of the
6683 		 * pre and post number of devices.
6684 		 */
6685 		spin_lock_irqsave(&conf->device_lock, flags);
6686 		mddev->degraded = calc_degraded(conf);
6687 		spin_unlock_irqrestore(&conf->device_lock, flags);
6688 	}
6689 	mddev->raid_disks = conf->raid_disks;
6690 	mddev->reshape_position = conf->reshape_progress;
6691 	set_bit(MD_CHANGE_DEVS, &mddev->flags);
6692 
6693 	clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
6694 	clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
6695 	set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
6696 	set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
6697 	mddev->sync_thread = md_register_thread(md_do_sync, mddev,
6698 						"reshape");
6699 	if (!mddev->sync_thread) {
6700 		mddev->recovery = 0;
6701 		spin_lock_irq(&conf->device_lock);
6702 		write_seqcount_begin(&conf->gen_lock);
6703 		mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
6704 		mddev->new_chunk_sectors =
6705 			conf->chunk_sectors = conf->prev_chunk_sectors;
6706 		mddev->new_layout = conf->algorithm = conf->prev_algo;
6707 		rdev_for_each(rdev, mddev)
6708 			rdev->new_data_offset = rdev->data_offset;
6709 		smp_wmb();
6710 		conf->generation --;
6711 		conf->reshape_progress = MaxSector;
6712 		mddev->reshape_position = MaxSector;
6713 		write_seqcount_end(&conf->gen_lock);
6714 		spin_unlock_irq(&conf->device_lock);
6715 		return -EAGAIN;
6716 	}
6717 	conf->reshape_checkpoint = jiffies;
6718 	md_wakeup_thread(mddev->sync_thread);
6719 	md_new_event(mddev);
6720 	return 0;
6721 }
6722 
6723 /* This is called from the reshape thread and should make any
6724  * changes needed in 'conf'
6725  */
end_reshape(struct r5conf * conf)6726 static void end_reshape(struct r5conf *conf)
6727 {
6728 
6729 	if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
6730 
6731 		spin_lock_irq(&conf->device_lock);
6732 		conf->previous_raid_disks = conf->raid_disks;
6733 		md_finish_reshape(conf->mddev);
6734 		smp_wmb();
6735 		conf->reshape_progress = MaxSector;
6736 		spin_unlock_irq(&conf->device_lock);
6737 		wake_up(&conf->wait_for_overlap);
6738 
6739 		/* read-ahead size must cover two whole stripes, which is
6740 		 * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
6741 		 */
6742 		if (conf->mddev->queue) {
6743 			int data_disks = conf->raid_disks - conf->max_degraded;
6744 			int stripe = data_disks * ((conf->chunk_sectors << 9)
6745 						   / PAGE_SIZE);
6746 			if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
6747 				conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
6748 		}
6749 	}
6750 }
6751 
6752 /* This is called from the raid5d thread with mddev_lock held.
6753  * It makes config changes to the device.
6754  */
raid5_finish_reshape(struct mddev * mddev)6755 static void raid5_finish_reshape(struct mddev *mddev)
6756 {
6757 	struct r5conf *conf = mddev->private;
6758 
6759 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
6760 
6761 		if (mddev->delta_disks > 0) {
6762 			md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
6763 			set_capacity(mddev->gendisk, mddev->array_sectors);
6764 			revalidate_disk(mddev->gendisk);
6765 		} else {
6766 			int d;
6767 			spin_lock_irq(&conf->device_lock);
6768 			mddev->degraded = calc_degraded(conf);
6769 			spin_unlock_irq(&conf->device_lock);
6770 			for (d = conf->raid_disks ;
6771 			     d < conf->raid_disks - mddev->delta_disks;
6772 			     d++) {
6773 				struct md_rdev *rdev = conf->disks[d].rdev;
6774 				if (rdev)
6775 					clear_bit(In_sync, &rdev->flags);
6776 				rdev = conf->disks[d].replacement;
6777 				if (rdev)
6778 					clear_bit(In_sync, &rdev->flags);
6779 			}
6780 		}
6781 		mddev->layout = conf->algorithm;
6782 		mddev->chunk_sectors = conf->chunk_sectors;
6783 		mddev->reshape_position = MaxSector;
6784 		mddev->delta_disks = 0;
6785 		mddev->reshape_backwards = 0;
6786 	}
6787 }
6788 
raid5_quiesce(struct mddev * mddev,int state)6789 static void raid5_quiesce(struct mddev *mddev, int state)
6790 {
6791 	struct r5conf *conf = mddev->private;
6792 
6793 	switch(state) {
6794 	case 2: /* resume for a suspend */
6795 		wake_up(&conf->wait_for_overlap);
6796 		break;
6797 
6798 	case 1: /* stop all writes */
6799 		lock_all_device_hash_locks_irq(conf);
6800 		/* '2' tells resync/reshape to pause so that all
6801 		 * active stripes can drain
6802 		 */
6803 		conf->quiesce = 2;
6804 		wait_event_cmd(conf->wait_for_stripe,
6805 				    atomic_read(&conf->active_stripes) == 0 &&
6806 				    atomic_read(&conf->active_aligned_reads) == 0,
6807 				    unlock_all_device_hash_locks_irq(conf),
6808 				    lock_all_device_hash_locks_irq(conf));
6809 		conf->quiesce = 1;
6810 		unlock_all_device_hash_locks_irq(conf);
6811 		/* allow reshape to continue */
6812 		wake_up(&conf->wait_for_overlap);
6813 		break;
6814 
6815 	case 0: /* re-enable writes */
6816 		lock_all_device_hash_locks_irq(conf);
6817 		conf->quiesce = 0;
6818 		wake_up(&conf->wait_for_stripe);
6819 		wake_up(&conf->wait_for_overlap);
6820 		unlock_all_device_hash_locks_irq(conf);
6821 		break;
6822 	}
6823 }
6824 
raid45_takeover_raid0(struct mddev * mddev,int level)6825 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
6826 {
6827 	struct r0conf *raid0_conf = mddev->private;
6828 	sector_t sectors;
6829 
6830 	/* for raid0 takeover only one zone is supported */
6831 	if (raid0_conf->nr_strip_zones > 1) {
6832 		printk(KERN_ERR "md/raid:%s: cannot takeover raid0 with more than one zone.\n",
6833 		       mdname(mddev));
6834 		return ERR_PTR(-EINVAL);
6835 	}
6836 
6837 	sectors = raid0_conf->strip_zone[0].zone_end;
6838 	sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
6839 	mddev->dev_sectors = sectors;
6840 	mddev->new_level = level;
6841 	mddev->new_layout = ALGORITHM_PARITY_N;
6842 	mddev->new_chunk_sectors = mddev->chunk_sectors;
6843 	mddev->raid_disks += 1;
6844 	mddev->delta_disks = 1;
6845 	/* make sure it will be not marked as dirty */
6846 	mddev->recovery_cp = MaxSector;
6847 
6848 	return setup_conf(mddev);
6849 }
6850 
raid5_takeover_raid1(struct mddev * mddev)6851 static void *raid5_takeover_raid1(struct mddev *mddev)
6852 {
6853 	int chunksect;
6854 
6855 	if (mddev->raid_disks != 2 ||
6856 	    mddev->degraded > 1)
6857 		return ERR_PTR(-EINVAL);
6858 
6859 	/* Should check if there are write-behind devices? */
6860 
6861 	chunksect = 64*2; /* 64K by default */
6862 
6863 	/* The array must be an exact multiple of chunksize */
6864 	while (chunksect && (mddev->array_sectors & (chunksect-1)))
6865 		chunksect >>= 1;
6866 
6867 	if ((chunksect<<9) < STRIPE_SIZE)
6868 		/* array size does not allow a suitable chunk size */
6869 		return ERR_PTR(-EINVAL);
6870 
6871 	mddev->new_level = 5;
6872 	mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
6873 	mddev->new_chunk_sectors = chunksect;
6874 
6875 	return setup_conf(mddev);
6876 }
6877 
raid5_takeover_raid6(struct mddev * mddev)6878 static void *raid5_takeover_raid6(struct mddev *mddev)
6879 {
6880 	int new_layout;
6881 
6882 	switch (mddev->layout) {
6883 	case ALGORITHM_LEFT_ASYMMETRIC_6:
6884 		new_layout = ALGORITHM_LEFT_ASYMMETRIC;
6885 		break;
6886 	case ALGORITHM_RIGHT_ASYMMETRIC_6:
6887 		new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
6888 		break;
6889 	case ALGORITHM_LEFT_SYMMETRIC_6:
6890 		new_layout = ALGORITHM_LEFT_SYMMETRIC;
6891 		break;
6892 	case ALGORITHM_RIGHT_SYMMETRIC_6:
6893 		new_layout = ALGORITHM_RIGHT_SYMMETRIC;
6894 		break;
6895 	case ALGORITHM_PARITY_0_6:
6896 		new_layout = ALGORITHM_PARITY_0;
6897 		break;
6898 	case ALGORITHM_PARITY_N:
6899 		new_layout = ALGORITHM_PARITY_N;
6900 		break;
6901 	default:
6902 		return ERR_PTR(-EINVAL);
6903 	}
6904 	mddev->new_level = 5;
6905 	mddev->new_layout = new_layout;
6906 	mddev->delta_disks = -1;
6907 	mddev->raid_disks -= 1;
6908 	return setup_conf(mddev);
6909 }
6910 
raid5_check_reshape(struct mddev * mddev)6911 static int raid5_check_reshape(struct mddev *mddev)
6912 {
6913 	/* For a 2-drive array, the layout and chunk size can be changed
6914 	 * immediately as not restriping is needed.
6915 	 * For larger arrays we record the new value - after validation
6916 	 * to be used by a reshape pass.
6917 	 */
6918 	struct r5conf *conf = mddev->private;
6919 	int new_chunk = mddev->new_chunk_sectors;
6920 
6921 	if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
6922 		return -EINVAL;
6923 	if (new_chunk > 0) {
6924 		if (!is_power_of_2(new_chunk))
6925 			return -EINVAL;
6926 		if (new_chunk < (PAGE_SIZE>>9))
6927 			return -EINVAL;
6928 		if (mddev->array_sectors & (new_chunk-1))
6929 			/* not factor of array size */
6930 			return -EINVAL;
6931 	}
6932 
6933 	/* They look valid */
6934 
6935 	if (mddev->raid_disks == 2) {
6936 		/* can make the change immediately */
6937 		if (mddev->new_layout >= 0) {
6938 			conf->algorithm = mddev->new_layout;
6939 			mddev->layout = mddev->new_layout;
6940 		}
6941 		if (new_chunk > 0) {
6942 			conf->chunk_sectors = new_chunk ;
6943 			mddev->chunk_sectors = new_chunk;
6944 		}
6945 		set_bit(MD_CHANGE_DEVS, &mddev->flags);
6946 		md_wakeup_thread(mddev->thread);
6947 	}
6948 	return check_reshape(mddev);
6949 }
6950 
raid6_check_reshape(struct mddev * mddev)6951 static int raid6_check_reshape(struct mddev *mddev)
6952 {
6953 	int new_chunk = mddev->new_chunk_sectors;
6954 
6955 	if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
6956 		return -EINVAL;
6957 	if (new_chunk > 0) {
6958 		if (!is_power_of_2(new_chunk))
6959 			return -EINVAL;
6960 		if (new_chunk < (PAGE_SIZE >> 9))
6961 			return -EINVAL;
6962 		if (mddev->array_sectors & (new_chunk-1))
6963 			/* not factor of array size */
6964 			return -EINVAL;
6965 	}
6966 
6967 	/* They look valid */
6968 	return check_reshape(mddev);
6969 }
6970 
raid5_takeover(struct mddev * mddev)6971 static void *raid5_takeover(struct mddev *mddev)
6972 {
6973 	/* raid5 can take over:
6974 	 *  raid0 - if there is only one strip zone - make it a raid4 layout
6975 	 *  raid1 - if there are two drives.  We need to know the chunk size
6976 	 *  raid4 - trivial - just use a raid4 layout.
6977 	 *  raid6 - Providing it is a *_6 layout
6978 	 */
6979 	if (mddev->level == 0)
6980 		return raid45_takeover_raid0(mddev, 5);
6981 	if (mddev->level == 1)
6982 		return raid5_takeover_raid1(mddev);
6983 	if (mddev->level == 4) {
6984 		mddev->new_layout = ALGORITHM_PARITY_N;
6985 		mddev->new_level = 5;
6986 		return setup_conf(mddev);
6987 	}
6988 	if (mddev->level == 6)
6989 		return raid5_takeover_raid6(mddev);
6990 
6991 	return ERR_PTR(-EINVAL);
6992 }
6993 
raid4_takeover(struct mddev * mddev)6994 static void *raid4_takeover(struct mddev *mddev)
6995 {
6996 	/* raid4 can take over:
6997 	 *  raid0 - if there is only one strip zone
6998 	 *  raid5 - if layout is right
6999 	 */
7000 	if (mddev->level == 0)
7001 		return raid45_takeover_raid0(mddev, 4);
7002 	if (mddev->level == 5 &&
7003 	    mddev->layout == ALGORITHM_PARITY_N) {
7004 		mddev->new_layout = 0;
7005 		mddev->new_level = 4;
7006 		return setup_conf(mddev);
7007 	}
7008 	return ERR_PTR(-EINVAL);
7009 }
7010 
7011 static struct md_personality raid5_personality;
7012 
raid6_takeover(struct mddev * mddev)7013 static void *raid6_takeover(struct mddev *mddev)
7014 {
7015 	/* Currently can only take over a raid5.  We map the
7016 	 * personality to an equivalent raid6 personality
7017 	 * with the Q block at the end.
7018 	 */
7019 	int new_layout;
7020 
7021 	if (mddev->pers != &raid5_personality)
7022 		return ERR_PTR(-EINVAL);
7023 	if (mddev->degraded > 1)
7024 		return ERR_PTR(-EINVAL);
7025 	if (mddev->raid_disks > 253)
7026 		return ERR_PTR(-EINVAL);
7027 	if (mddev->raid_disks < 3)
7028 		return ERR_PTR(-EINVAL);
7029 
7030 	switch (mddev->layout) {
7031 	case ALGORITHM_LEFT_ASYMMETRIC:
7032 		new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
7033 		break;
7034 	case ALGORITHM_RIGHT_ASYMMETRIC:
7035 		new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
7036 		break;
7037 	case ALGORITHM_LEFT_SYMMETRIC:
7038 		new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
7039 		break;
7040 	case ALGORITHM_RIGHT_SYMMETRIC:
7041 		new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
7042 		break;
7043 	case ALGORITHM_PARITY_0:
7044 		new_layout = ALGORITHM_PARITY_0_6;
7045 		break;
7046 	case ALGORITHM_PARITY_N:
7047 		new_layout = ALGORITHM_PARITY_N;
7048 		break;
7049 	default:
7050 		return ERR_PTR(-EINVAL);
7051 	}
7052 	mddev->new_level = 6;
7053 	mddev->new_layout = new_layout;
7054 	mddev->delta_disks = 1;
7055 	mddev->raid_disks += 1;
7056 	return setup_conf(mddev);
7057 }
7058 
7059 static struct md_personality raid6_personality =
7060 {
7061 	.name		= "raid6",
7062 	.level		= 6,
7063 	.owner		= THIS_MODULE,
7064 	.make_request	= make_request,
7065 	.run		= run,
7066 	.stop		= stop,
7067 	.status		= status,
7068 	.error_handler	= error,
7069 	.hot_add_disk	= raid5_add_disk,
7070 	.hot_remove_disk= raid5_remove_disk,
7071 	.spare_active	= raid5_spare_active,
7072 	.sync_request	= sync_request,
7073 	.resize		= raid5_resize,
7074 	.size		= raid5_size,
7075 	.check_reshape	= raid6_check_reshape,
7076 	.start_reshape  = raid5_start_reshape,
7077 	.finish_reshape = raid5_finish_reshape,
7078 	.quiesce	= raid5_quiesce,
7079 	.takeover	= raid6_takeover,
7080 };
7081 static struct md_personality raid5_personality =
7082 {
7083 	.name		= "raid5",
7084 	.level		= 5,
7085 	.owner		= THIS_MODULE,
7086 	.make_request	= make_request,
7087 	.run		= run,
7088 	.stop		= stop,
7089 	.status		= status,
7090 	.error_handler	= error,
7091 	.hot_add_disk	= raid5_add_disk,
7092 	.hot_remove_disk= raid5_remove_disk,
7093 	.spare_active	= raid5_spare_active,
7094 	.sync_request	= sync_request,
7095 	.resize		= raid5_resize,
7096 	.size		= raid5_size,
7097 	.check_reshape	= raid5_check_reshape,
7098 	.start_reshape  = raid5_start_reshape,
7099 	.finish_reshape = raid5_finish_reshape,
7100 	.quiesce	= raid5_quiesce,
7101 	.takeover	= raid5_takeover,
7102 };
7103 
7104 static struct md_personality raid4_personality =
7105 {
7106 	.name		= "raid4",
7107 	.level		= 4,
7108 	.owner		= THIS_MODULE,
7109 	.make_request	= make_request,
7110 	.run		= run,
7111 	.stop		= stop,
7112 	.status		= status,
7113 	.error_handler	= error,
7114 	.hot_add_disk	= raid5_add_disk,
7115 	.hot_remove_disk= raid5_remove_disk,
7116 	.spare_active	= raid5_spare_active,
7117 	.sync_request	= sync_request,
7118 	.resize		= raid5_resize,
7119 	.size		= raid5_size,
7120 	.check_reshape	= raid5_check_reshape,
7121 	.start_reshape  = raid5_start_reshape,
7122 	.finish_reshape = raid5_finish_reshape,
7123 	.quiesce	= raid5_quiesce,
7124 	.takeover	= raid4_takeover,
7125 };
7126 
raid5_init(void)7127 static int __init raid5_init(void)
7128 {
7129 	raid5_wq = alloc_workqueue("raid5wq",
7130 		WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
7131 	if (!raid5_wq)
7132 		return -ENOMEM;
7133 	register_md_personality(&raid6_personality);
7134 	register_md_personality(&raid5_personality);
7135 	register_md_personality(&raid4_personality);
7136 	return 0;
7137 }
7138 
raid5_exit(void)7139 static void raid5_exit(void)
7140 {
7141 	unregister_md_personality(&raid6_personality);
7142 	unregister_md_personality(&raid5_personality);
7143 	unregister_md_personality(&raid4_personality);
7144 	destroy_workqueue(raid5_wq);
7145 }
7146 
7147 module_init(raid5_init);
7148 module_exit(raid5_exit);
7149 MODULE_LICENSE("GPL");
7150 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
7151 MODULE_ALIAS("md-personality-4"); /* RAID5 */
7152 MODULE_ALIAS("md-raid5");
7153 MODULE_ALIAS("md-raid4");
7154 MODULE_ALIAS("md-level-5");
7155 MODULE_ALIAS("md-level-4");
7156 MODULE_ALIAS("md-personality-8"); /* RAID6 */
7157 MODULE_ALIAS("md-raid6");
7158 MODULE_ALIAS("md-level-6");
7159 
7160 /* This used to be two separate modules, they were: */
7161 MODULE_ALIAS("raid5");
7162 MODULE_ALIAS("raid6");
7163