• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * raid10.c : Multiple Devices driver for Linux
3  *
4  * Copyright (C) 2000-2004 Neil Brown
5  *
6  * RAID-10 support for md.
7  *
8  * Base on code in raid1.c.  See raid1.c for further copyright information.
9  *
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 #include <linux/slab.h>
22 #include <linux/delay.h>
23 #include <linux/blkdev.h>
24 #include <linux/module.h>
25 #include <linux/seq_file.h>
26 #include <linux/ratelimit.h>
27 #include <linux/kthread.h>
28 #include "md.h"
29 #include "raid10.h"
30 #include "raid0.h"
31 #include "bitmap.h"
32 
33 /*
34  * RAID10 provides a combination of RAID0 and RAID1 functionality.
35  * The layout of data is defined by
36  *    chunk_size
37  *    raid_disks
38  *    near_copies (stored in low byte of layout)
39  *    far_copies (stored in second byte of layout)
40  *    far_offset (stored in bit 16 of layout )
41  *    use_far_sets (stored in bit 17 of layout )
42  *    use_far_sets_bugfixed (stored in bit 18 of layout )
43  *
44  * The data to be stored is divided into chunks using chunksize.  Each device
45  * is divided into far_copies sections.   In each section, chunks are laid out
46  * in a style similar to raid0, but near_copies copies of each chunk is stored
47  * (each on a different drive).  The starting device for each section is offset
48  * near_copies from the starting device of the previous section.  Thus there
49  * are (near_copies * far_copies) of each chunk, and each is on a different
50  * drive.  near_copies and far_copies must be at least one, and their product
51  * is at most raid_disks.
52  *
53  * If far_offset is true, then the far_copies are handled a bit differently.
54  * The copies are still in different stripes, but instead of being very far
55  * apart on disk, there are adjacent stripes.
56  *
57  * The far and offset algorithms are handled slightly differently if
58  * 'use_far_sets' is true.  In this case, the array's devices are grouped into
59  * sets that are (near_copies * far_copies) in size.  The far copied stripes
60  * are still shifted by 'near_copies' devices, but this shifting stays confined
61  * to the set rather than the entire array.  This is done to improve the number
62  * of device combinations that can fail without causing the array to fail.
63  * Example 'far' algorithm w/o 'use_far_sets' (each letter represents a chunk
64  * on a device):
65  *    A B C D    A B C D E
66  *      ...         ...
67  *    D A B C    E A B C D
68  * Example 'far' algorithm w/ 'use_far_sets' enabled (sets illustrated w/ []'s):
69  *    [A B] [C D]    [A B] [C D E]
70  *    |...| |...|    |...| | ... |
71  *    [B A] [D C]    [B A] [E C D]
72  */
73 
74 /*
75  * Number of guaranteed r10bios in case of extreme VM load:
76  */
77 #define	NR_RAID10_BIOS 256
78 
79 /* when we get a read error on a read-only array, we redirect to another
80  * device without failing the first device, or trying to over-write to
81  * correct the read error.  To keep track of bad blocks on a per-bio
82  * level, we store IO_BLOCKED in the appropriate 'bios' pointer
83  */
84 #define IO_BLOCKED ((struct bio *)1)
85 /* When we successfully write to a known bad-block, we need to remove the
86  * bad-block marking which must be done from process context.  So we record
87  * the success by setting devs[n].bio to IO_MADE_GOOD
88  */
89 #define IO_MADE_GOOD ((struct bio *)2)
90 
91 #define BIO_SPECIAL(bio) ((unsigned long)bio <= 2)
92 
93 /* When there are this many requests queued to be written by
94  * the raid10 thread, we become 'congested' to provide back-pressure
95  * for writeback.
96  */
97 static int max_queued_requests = 1024;
98 
99 static void allow_barrier(struct r10conf *conf);
100 static void lower_barrier(struct r10conf *conf);
101 static int _enough(struct r10conf *conf, int previous, int ignore);
102 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr,
103 				int *skipped);
104 static void reshape_request_write(struct mddev *mddev, struct r10bio *r10_bio);
105 static void end_reshape_write(struct bio *bio);
106 static void end_reshape(struct r10conf *conf);
107 
r10bio_pool_alloc(gfp_t gfp_flags,void * data)108 static void * r10bio_pool_alloc(gfp_t gfp_flags, void *data)
109 {
110 	struct r10conf *conf = data;
111 	int size = offsetof(struct r10bio, devs[conf->copies]);
112 
113 	/* allocate a r10bio with room for raid_disks entries in the
114 	 * bios array */
115 	return kzalloc(size, gfp_flags);
116 }
117 
r10bio_pool_free(void * r10_bio,void * data)118 static void r10bio_pool_free(void *r10_bio, void *data)
119 {
120 	kfree(r10_bio);
121 }
122 
123 /* Maximum size of each resync request */
124 #define RESYNC_BLOCK_SIZE (64*1024)
125 #define RESYNC_PAGES ((RESYNC_BLOCK_SIZE + PAGE_SIZE-1) / PAGE_SIZE)
126 /* amount of memory to reserve for resync requests */
127 #define RESYNC_WINDOW (1024*1024)
128 /* maximum number of concurrent requests, memory permitting */
129 #define RESYNC_DEPTH (32*1024*1024/RESYNC_BLOCK_SIZE)
130 
131 /*
132  * When performing a resync, we need to read and compare, so
133  * we need as many pages are there are copies.
134  * When performing a recovery, we need 2 bios, one for read,
135  * one for write (we recover only one drive per r10buf)
136  *
137  */
r10buf_pool_alloc(gfp_t gfp_flags,void * data)138 static void * r10buf_pool_alloc(gfp_t gfp_flags, void *data)
139 {
140 	struct r10conf *conf = data;
141 	struct page *page;
142 	struct r10bio *r10_bio;
143 	struct bio *bio;
144 	int i, j;
145 	int nalloc;
146 
147 	r10_bio = r10bio_pool_alloc(gfp_flags, conf);
148 	if (!r10_bio)
149 		return NULL;
150 
151 	if (test_bit(MD_RECOVERY_SYNC, &conf->mddev->recovery) ||
152 	    test_bit(MD_RECOVERY_RESHAPE, &conf->mddev->recovery))
153 		nalloc = conf->copies; /* resync */
154 	else
155 		nalloc = 2; /* recovery */
156 
157 	/*
158 	 * Allocate bios.
159 	 */
160 	for (j = nalloc ; j-- ; ) {
161 		bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
162 		if (!bio)
163 			goto out_free_bio;
164 		r10_bio->devs[j].bio = bio;
165 		if (!conf->have_replacement)
166 			continue;
167 		bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
168 		if (!bio)
169 			goto out_free_bio;
170 		r10_bio->devs[j].repl_bio = bio;
171 	}
172 	/*
173 	 * Allocate RESYNC_PAGES data pages and attach them
174 	 * where needed.
175 	 */
176 	for (j = 0 ; j < nalloc; j++) {
177 		struct bio *rbio = r10_bio->devs[j].repl_bio;
178 		bio = r10_bio->devs[j].bio;
179 		for (i = 0; i < RESYNC_PAGES; i++) {
180 			if (j > 0 && !test_bit(MD_RECOVERY_SYNC,
181 					       &conf->mddev->recovery)) {
182 				/* we can share bv_page's during recovery
183 				 * and reshape */
184 				struct bio *rbio = r10_bio->devs[0].bio;
185 				page = rbio->bi_io_vec[i].bv_page;
186 				get_page(page);
187 			} else
188 				page = alloc_page(gfp_flags);
189 			if (unlikely(!page))
190 				goto out_free_pages;
191 
192 			bio->bi_io_vec[i].bv_page = page;
193 			if (rbio)
194 				rbio->bi_io_vec[i].bv_page = page;
195 		}
196 	}
197 
198 	return r10_bio;
199 
200 out_free_pages:
201 	for ( ; i > 0 ; i--)
202 		safe_put_page(bio->bi_io_vec[i-1].bv_page);
203 	while (j--)
204 		for (i = 0; i < RESYNC_PAGES ; i++)
205 			safe_put_page(r10_bio->devs[j].bio->bi_io_vec[i].bv_page);
206 	j = 0;
207 out_free_bio:
208 	for ( ; j < nalloc; j++) {
209 		if (r10_bio->devs[j].bio)
210 			bio_put(r10_bio->devs[j].bio);
211 		if (r10_bio->devs[j].repl_bio)
212 			bio_put(r10_bio->devs[j].repl_bio);
213 	}
214 	r10bio_pool_free(r10_bio, conf);
215 	return NULL;
216 }
217 
r10buf_pool_free(void * __r10_bio,void * data)218 static void r10buf_pool_free(void *__r10_bio, void *data)
219 {
220 	int i;
221 	struct r10conf *conf = data;
222 	struct r10bio *r10bio = __r10_bio;
223 	int j;
224 
225 	for (j=0; j < conf->copies; j++) {
226 		struct bio *bio = r10bio->devs[j].bio;
227 		if (bio) {
228 			for (i = 0; i < RESYNC_PAGES; i++) {
229 				safe_put_page(bio->bi_io_vec[i].bv_page);
230 				bio->bi_io_vec[i].bv_page = NULL;
231 			}
232 			bio_put(bio);
233 		}
234 		bio = r10bio->devs[j].repl_bio;
235 		if (bio)
236 			bio_put(bio);
237 	}
238 	r10bio_pool_free(r10bio, conf);
239 }
240 
put_all_bios(struct r10conf * conf,struct r10bio * r10_bio)241 static void put_all_bios(struct r10conf *conf, struct r10bio *r10_bio)
242 {
243 	int i;
244 
245 	for (i = 0; i < conf->copies; i++) {
246 		struct bio **bio = & r10_bio->devs[i].bio;
247 		if (!BIO_SPECIAL(*bio))
248 			bio_put(*bio);
249 		*bio = NULL;
250 		bio = &r10_bio->devs[i].repl_bio;
251 		if (r10_bio->read_slot < 0 && !BIO_SPECIAL(*bio))
252 			bio_put(*bio);
253 		*bio = NULL;
254 	}
255 }
256 
free_r10bio(struct r10bio * r10_bio)257 static void free_r10bio(struct r10bio *r10_bio)
258 {
259 	struct r10conf *conf = r10_bio->mddev->private;
260 
261 	put_all_bios(conf, r10_bio);
262 	mempool_free(r10_bio, conf->r10bio_pool);
263 }
264 
put_buf(struct r10bio * r10_bio)265 static void put_buf(struct r10bio *r10_bio)
266 {
267 	struct r10conf *conf = r10_bio->mddev->private;
268 
269 	mempool_free(r10_bio, conf->r10buf_pool);
270 
271 	lower_barrier(conf);
272 }
273 
reschedule_retry(struct r10bio * r10_bio)274 static void reschedule_retry(struct r10bio *r10_bio)
275 {
276 	unsigned long flags;
277 	struct mddev *mddev = r10_bio->mddev;
278 	struct r10conf *conf = mddev->private;
279 
280 	spin_lock_irqsave(&conf->device_lock, flags);
281 	list_add(&r10_bio->retry_list, &conf->retry_list);
282 	conf->nr_queued ++;
283 	spin_unlock_irqrestore(&conf->device_lock, flags);
284 
285 	/* wake up frozen array... */
286 	wake_up(&conf->wait_barrier);
287 
288 	md_wakeup_thread(mddev->thread);
289 }
290 
291 /*
292  * raid_end_bio_io() is called when we have finished servicing a mirrored
293  * operation and are ready to return a success/failure code to the buffer
294  * cache layer.
295  */
raid_end_bio_io(struct r10bio * r10_bio)296 static void raid_end_bio_io(struct r10bio *r10_bio)
297 {
298 	struct bio *bio = r10_bio->master_bio;
299 	int done;
300 	struct r10conf *conf = r10_bio->mddev->private;
301 
302 	if (bio->bi_phys_segments) {
303 		unsigned long flags;
304 		spin_lock_irqsave(&conf->device_lock, flags);
305 		bio->bi_phys_segments--;
306 		done = (bio->bi_phys_segments == 0);
307 		spin_unlock_irqrestore(&conf->device_lock, flags);
308 	} else
309 		done = 1;
310 	if (!test_bit(R10BIO_Uptodate, &r10_bio->state))
311 		bio->bi_error = -EIO;
312 	if (done) {
313 		bio_endio(bio);
314 		/*
315 		 * Wake up any possible resync thread that waits for the device
316 		 * to go idle.
317 		 */
318 		allow_barrier(conf);
319 	}
320 	free_r10bio(r10_bio);
321 }
322 
323 /*
324  * Update disk head position estimator based on IRQ completion info.
325  */
update_head_pos(int slot,struct r10bio * r10_bio)326 static inline void update_head_pos(int slot, struct r10bio *r10_bio)
327 {
328 	struct r10conf *conf = r10_bio->mddev->private;
329 
330 	conf->mirrors[r10_bio->devs[slot].devnum].head_position =
331 		r10_bio->devs[slot].addr + (r10_bio->sectors);
332 }
333 
334 /*
335  * Find the disk number which triggered given bio
336  */
find_bio_disk(struct r10conf * conf,struct r10bio * r10_bio,struct bio * bio,int * slotp,int * replp)337 static int find_bio_disk(struct r10conf *conf, struct r10bio *r10_bio,
338 			 struct bio *bio, int *slotp, int *replp)
339 {
340 	int slot;
341 	int repl = 0;
342 
343 	for (slot = 0; slot < conf->copies; slot++) {
344 		if (r10_bio->devs[slot].bio == bio)
345 			break;
346 		if (r10_bio->devs[slot].repl_bio == bio) {
347 			repl = 1;
348 			break;
349 		}
350 	}
351 
352 	BUG_ON(slot == conf->copies);
353 	update_head_pos(slot, r10_bio);
354 
355 	if (slotp)
356 		*slotp = slot;
357 	if (replp)
358 		*replp = repl;
359 	return r10_bio->devs[slot].devnum;
360 }
361 
raid10_end_read_request(struct bio * bio)362 static void raid10_end_read_request(struct bio *bio)
363 {
364 	int uptodate = !bio->bi_error;
365 	struct r10bio *r10_bio = bio->bi_private;
366 	int slot, dev;
367 	struct md_rdev *rdev;
368 	struct r10conf *conf = r10_bio->mddev->private;
369 
370 	slot = r10_bio->read_slot;
371 	dev = r10_bio->devs[slot].devnum;
372 	rdev = r10_bio->devs[slot].rdev;
373 	/*
374 	 * this branch is our 'one mirror IO has finished' event handler:
375 	 */
376 	update_head_pos(slot, r10_bio);
377 
378 	if (uptodate) {
379 		/*
380 		 * Set R10BIO_Uptodate in our master bio, so that
381 		 * we will return a good error code to the higher
382 		 * levels even if IO on some other mirrored buffer fails.
383 		 *
384 		 * The 'master' represents the composite IO operation to
385 		 * user-side. So if something waits for IO, then it will
386 		 * wait for the 'master' bio.
387 		 */
388 		set_bit(R10BIO_Uptodate, &r10_bio->state);
389 	} else {
390 		/* If all other devices that store this block have
391 		 * failed, we want to return the error upwards rather
392 		 * than fail the last device.  Here we redefine
393 		 * "uptodate" to mean "Don't want to retry"
394 		 */
395 		if (!_enough(conf, test_bit(R10BIO_Previous, &r10_bio->state),
396 			     rdev->raid_disk))
397 			uptodate = 1;
398 	}
399 	if (uptodate) {
400 		raid_end_bio_io(r10_bio);
401 		rdev_dec_pending(rdev, conf->mddev);
402 	} else {
403 		/*
404 		 * oops, read error - keep the refcount on the rdev
405 		 */
406 		char b[BDEVNAME_SIZE];
407 		printk_ratelimited(KERN_ERR
408 				   "md/raid10:%s: %s: rescheduling sector %llu\n",
409 				   mdname(conf->mddev),
410 				   bdevname(rdev->bdev, b),
411 				   (unsigned long long)r10_bio->sector);
412 		set_bit(R10BIO_ReadError, &r10_bio->state);
413 		reschedule_retry(r10_bio);
414 	}
415 }
416 
close_write(struct r10bio * r10_bio)417 static void close_write(struct r10bio *r10_bio)
418 {
419 	/* clear the bitmap if all writes complete successfully */
420 	bitmap_endwrite(r10_bio->mddev->bitmap, r10_bio->sector,
421 			r10_bio->sectors,
422 			!test_bit(R10BIO_Degraded, &r10_bio->state),
423 			0);
424 	md_write_end(r10_bio->mddev);
425 }
426 
one_write_done(struct r10bio * r10_bio)427 static void one_write_done(struct r10bio *r10_bio)
428 {
429 	if (atomic_dec_and_test(&r10_bio->remaining)) {
430 		if (test_bit(R10BIO_WriteError, &r10_bio->state))
431 			reschedule_retry(r10_bio);
432 		else {
433 			close_write(r10_bio);
434 			if (test_bit(R10BIO_MadeGood, &r10_bio->state))
435 				reschedule_retry(r10_bio);
436 			else
437 				raid_end_bio_io(r10_bio);
438 		}
439 	}
440 }
441 
raid10_end_write_request(struct bio * bio)442 static void raid10_end_write_request(struct bio *bio)
443 {
444 	struct r10bio *r10_bio = bio->bi_private;
445 	int dev;
446 	int dec_rdev = 1;
447 	struct r10conf *conf = r10_bio->mddev->private;
448 	int slot, repl;
449 	struct md_rdev *rdev = NULL;
450 
451 	dev = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
452 
453 	if (repl)
454 		rdev = conf->mirrors[dev].replacement;
455 	if (!rdev) {
456 		smp_rmb();
457 		repl = 0;
458 		rdev = conf->mirrors[dev].rdev;
459 	}
460 	/*
461 	 * this branch is our 'one mirror IO has finished' event handler:
462 	 */
463 	if (bio->bi_error) {
464 		if (repl)
465 			/* Never record new bad blocks to replacement,
466 			 * just fail it.
467 			 */
468 			md_error(rdev->mddev, rdev);
469 		else {
470 			set_bit(WriteErrorSeen,	&rdev->flags);
471 			if (!test_and_set_bit(WantReplacement, &rdev->flags))
472 				set_bit(MD_RECOVERY_NEEDED,
473 					&rdev->mddev->recovery);
474 			set_bit(R10BIO_WriteError, &r10_bio->state);
475 			dec_rdev = 0;
476 		}
477 	} else {
478 		/*
479 		 * Set R10BIO_Uptodate in our master bio, so that
480 		 * we will return a good error code for to the higher
481 		 * levels even if IO on some other mirrored buffer fails.
482 		 *
483 		 * The 'master' represents the composite IO operation to
484 		 * user-side. So if something waits for IO, then it will
485 		 * wait for the 'master' bio.
486 		 */
487 		sector_t first_bad;
488 		int bad_sectors;
489 
490 		/*
491 		 * Do not set R10BIO_Uptodate if the current device is
492 		 * rebuilding or Faulty. This is because we cannot use
493 		 * such device for properly reading the data back (we could
494 		 * potentially use it, if the current write would have felt
495 		 * before rdev->recovery_offset, but for simplicity we don't
496 		 * check this here.
497 		 */
498 		if (test_bit(In_sync, &rdev->flags) &&
499 		    !test_bit(Faulty, &rdev->flags))
500 			set_bit(R10BIO_Uptodate, &r10_bio->state);
501 
502 		/* Maybe we can clear some bad blocks. */
503 		if (is_badblock(rdev,
504 				r10_bio->devs[slot].addr,
505 				r10_bio->sectors,
506 				&first_bad, &bad_sectors)) {
507 			bio_put(bio);
508 			if (repl)
509 				r10_bio->devs[slot].repl_bio = IO_MADE_GOOD;
510 			else
511 				r10_bio->devs[slot].bio = IO_MADE_GOOD;
512 			dec_rdev = 0;
513 			set_bit(R10BIO_MadeGood, &r10_bio->state);
514 		}
515 	}
516 
517 	/*
518 	 *
519 	 * Let's see if all mirrored write operations have finished
520 	 * already.
521 	 */
522 	one_write_done(r10_bio);
523 	if (dec_rdev)
524 		rdev_dec_pending(rdev, conf->mddev);
525 }
526 
527 /*
528  * RAID10 layout manager
529  * As well as the chunksize and raid_disks count, there are two
530  * parameters: near_copies and far_copies.
531  * near_copies * far_copies must be <= raid_disks.
532  * Normally one of these will be 1.
533  * If both are 1, we get raid0.
534  * If near_copies == raid_disks, we get raid1.
535  *
536  * Chunks are laid out in raid0 style with near_copies copies of the
537  * first chunk, followed by near_copies copies of the next chunk and
538  * so on.
539  * If far_copies > 1, then after 1/far_copies of the array has been assigned
540  * as described above, we start again with a device offset of near_copies.
541  * So we effectively have another copy of the whole array further down all
542  * the drives, but with blocks on different drives.
543  * With this layout, and block is never stored twice on the one device.
544  *
545  * raid10_find_phys finds the sector offset of a given virtual sector
546  * on each device that it is on.
547  *
548  * raid10_find_virt does the reverse mapping, from a device and a
549  * sector offset to a virtual address
550  */
551 
__raid10_find_phys(struct geom * geo,struct r10bio * r10bio)552 static void __raid10_find_phys(struct geom *geo, struct r10bio *r10bio)
553 {
554 	int n,f;
555 	sector_t sector;
556 	sector_t chunk;
557 	sector_t stripe;
558 	int dev;
559 	int slot = 0;
560 	int last_far_set_start, last_far_set_size;
561 
562 	last_far_set_start = (geo->raid_disks / geo->far_set_size) - 1;
563 	last_far_set_start *= geo->far_set_size;
564 
565 	last_far_set_size = geo->far_set_size;
566 	last_far_set_size += (geo->raid_disks % geo->far_set_size);
567 
568 	/* now calculate first sector/dev */
569 	chunk = r10bio->sector >> geo->chunk_shift;
570 	sector = r10bio->sector & geo->chunk_mask;
571 
572 	chunk *= geo->near_copies;
573 	stripe = chunk;
574 	dev = sector_div(stripe, geo->raid_disks);
575 	if (geo->far_offset)
576 		stripe *= geo->far_copies;
577 
578 	sector += stripe << geo->chunk_shift;
579 
580 	/* and calculate all the others */
581 	for (n = 0; n < geo->near_copies; n++) {
582 		int d = dev;
583 		int set;
584 		sector_t s = sector;
585 		r10bio->devs[slot].devnum = d;
586 		r10bio->devs[slot].addr = s;
587 		slot++;
588 
589 		for (f = 1; f < geo->far_copies; f++) {
590 			set = d / geo->far_set_size;
591 			d += geo->near_copies;
592 
593 			if ((geo->raid_disks % geo->far_set_size) &&
594 			    (d > last_far_set_start)) {
595 				d -= last_far_set_start;
596 				d %= last_far_set_size;
597 				d += last_far_set_start;
598 			} else {
599 				d %= geo->far_set_size;
600 				d += geo->far_set_size * set;
601 			}
602 			s += geo->stride;
603 			r10bio->devs[slot].devnum = d;
604 			r10bio->devs[slot].addr = s;
605 			slot++;
606 		}
607 		dev++;
608 		if (dev >= geo->raid_disks) {
609 			dev = 0;
610 			sector += (geo->chunk_mask + 1);
611 		}
612 	}
613 }
614 
raid10_find_phys(struct r10conf * conf,struct r10bio * r10bio)615 static void raid10_find_phys(struct r10conf *conf, struct r10bio *r10bio)
616 {
617 	struct geom *geo = &conf->geo;
618 
619 	if (conf->reshape_progress != MaxSector &&
620 	    ((r10bio->sector >= conf->reshape_progress) !=
621 	     conf->mddev->reshape_backwards)) {
622 		set_bit(R10BIO_Previous, &r10bio->state);
623 		geo = &conf->prev;
624 	} else
625 		clear_bit(R10BIO_Previous, &r10bio->state);
626 
627 	__raid10_find_phys(geo, r10bio);
628 }
629 
raid10_find_virt(struct r10conf * conf,sector_t sector,int dev)630 static sector_t raid10_find_virt(struct r10conf *conf, sector_t sector, int dev)
631 {
632 	sector_t offset, chunk, vchunk;
633 	/* Never use conf->prev as this is only called during resync
634 	 * or recovery, so reshape isn't happening
635 	 */
636 	struct geom *geo = &conf->geo;
637 	int far_set_start = (dev / geo->far_set_size) * geo->far_set_size;
638 	int far_set_size = geo->far_set_size;
639 	int last_far_set_start;
640 
641 	if (geo->raid_disks % geo->far_set_size) {
642 		last_far_set_start = (geo->raid_disks / geo->far_set_size) - 1;
643 		last_far_set_start *= geo->far_set_size;
644 
645 		if (dev >= last_far_set_start) {
646 			far_set_size = geo->far_set_size;
647 			far_set_size += (geo->raid_disks % geo->far_set_size);
648 			far_set_start = last_far_set_start;
649 		}
650 	}
651 
652 	offset = sector & geo->chunk_mask;
653 	if (geo->far_offset) {
654 		int fc;
655 		chunk = sector >> geo->chunk_shift;
656 		fc = sector_div(chunk, geo->far_copies);
657 		dev -= fc * geo->near_copies;
658 		if (dev < far_set_start)
659 			dev += far_set_size;
660 	} else {
661 		while (sector >= geo->stride) {
662 			sector -= geo->stride;
663 			if (dev < (geo->near_copies + far_set_start))
664 				dev += far_set_size - geo->near_copies;
665 			else
666 				dev -= geo->near_copies;
667 		}
668 		chunk = sector >> geo->chunk_shift;
669 	}
670 	vchunk = chunk * geo->raid_disks + dev;
671 	sector_div(vchunk, geo->near_copies);
672 	return (vchunk << geo->chunk_shift) + offset;
673 }
674 
675 /*
676  * This routine returns the disk from which the requested read should
677  * be done. There is a per-array 'next expected sequential IO' sector
678  * number - if this matches on the next IO then we use the last disk.
679  * There is also a per-disk 'last know head position' sector that is
680  * maintained from IRQ contexts, both the normal and the resync IO
681  * completion handlers update this position correctly. If there is no
682  * perfect sequential match then we pick the disk whose head is closest.
683  *
684  * If there are 2 mirrors in the same 2 devices, performance degrades
685  * because position is mirror, not device based.
686  *
687  * The rdev for the device selected will have nr_pending incremented.
688  */
689 
690 /*
691  * FIXME: possibly should rethink readbalancing and do it differently
692  * depending on near_copies / far_copies geometry.
693  */
read_balance(struct r10conf * conf,struct r10bio * r10_bio,int * max_sectors)694 static struct md_rdev *read_balance(struct r10conf *conf,
695 				    struct r10bio *r10_bio,
696 				    int *max_sectors)
697 {
698 	const sector_t this_sector = r10_bio->sector;
699 	int disk, slot;
700 	int sectors = r10_bio->sectors;
701 	int best_good_sectors;
702 	sector_t new_distance, best_dist;
703 	struct md_rdev *best_rdev, *rdev = NULL;
704 	int do_balance;
705 	int best_slot;
706 	struct geom *geo = &conf->geo;
707 
708 	raid10_find_phys(conf, r10_bio);
709 	rcu_read_lock();
710 retry:
711 	sectors = r10_bio->sectors;
712 	best_slot = -1;
713 	best_rdev = NULL;
714 	best_dist = MaxSector;
715 	best_good_sectors = 0;
716 	do_balance = 1;
717 	/*
718 	 * Check if we can balance. We can balance on the whole
719 	 * device if no resync is going on (recovery is ok), or below
720 	 * the resync window. We take the first readable disk when
721 	 * above the resync window.
722 	 */
723 	if (conf->mddev->recovery_cp < MaxSector
724 	    && (this_sector + sectors >= conf->next_resync))
725 		do_balance = 0;
726 
727 	for (slot = 0; slot < conf->copies ; slot++) {
728 		sector_t first_bad;
729 		int bad_sectors;
730 		sector_t dev_sector;
731 
732 		if (r10_bio->devs[slot].bio == IO_BLOCKED)
733 			continue;
734 		disk = r10_bio->devs[slot].devnum;
735 		rdev = rcu_dereference(conf->mirrors[disk].replacement);
736 		if (rdev == NULL || test_bit(Faulty, &rdev->flags) ||
737 		    r10_bio->devs[slot].addr + sectors > rdev->recovery_offset)
738 			rdev = rcu_dereference(conf->mirrors[disk].rdev);
739 		if (rdev == NULL ||
740 		    test_bit(Faulty, &rdev->flags))
741 			continue;
742 		if (!test_bit(In_sync, &rdev->flags) &&
743 		    r10_bio->devs[slot].addr + sectors > rdev->recovery_offset)
744 			continue;
745 
746 		dev_sector = r10_bio->devs[slot].addr;
747 		if (is_badblock(rdev, dev_sector, sectors,
748 				&first_bad, &bad_sectors)) {
749 			if (best_dist < MaxSector)
750 				/* Already have a better slot */
751 				continue;
752 			if (first_bad <= dev_sector) {
753 				/* Cannot read here.  If this is the
754 				 * 'primary' device, then we must not read
755 				 * beyond 'bad_sectors' from another device.
756 				 */
757 				bad_sectors -= (dev_sector - first_bad);
758 				if (!do_balance && sectors > bad_sectors)
759 					sectors = bad_sectors;
760 				if (best_good_sectors > sectors)
761 					best_good_sectors = sectors;
762 			} else {
763 				sector_t good_sectors =
764 					first_bad - dev_sector;
765 				if (good_sectors > best_good_sectors) {
766 					best_good_sectors = good_sectors;
767 					best_slot = slot;
768 					best_rdev = rdev;
769 				}
770 				if (!do_balance)
771 					/* Must read from here */
772 					break;
773 			}
774 			continue;
775 		} else
776 			best_good_sectors = sectors;
777 
778 		if (!do_balance)
779 			break;
780 
781 		/* This optimisation is debatable, and completely destroys
782 		 * sequential read speed for 'far copies' arrays.  So only
783 		 * keep it for 'near' arrays, and review those later.
784 		 */
785 		if (geo->near_copies > 1 && !atomic_read(&rdev->nr_pending))
786 			break;
787 
788 		/* for far > 1 always use the lowest address */
789 		if (geo->far_copies > 1)
790 			new_distance = r10_bio->devs[slot].addr;
791 		else
792 			new_distance = abs(r10_bio->devs[slot].addr -
793 					   conf->mirrors[disk].head_position);
794 		if (new_distance < best_dist) {
795 			best_dist = new_distance;
796 			best_slot = slot;
797 			best_rdev = rdev;
798 		}
799 	}
800 	if (slot >= conf->copies) {
801 		slot = best_slot;
802 		rdev = best_rdev;
803 	}
804 
805 	if (slot >= 0) {
806 		atomic_inc(&rdev->nr_pending);
807 		if (test_bit(Faulty, &rdev->flags)) {
808 			/* Cannot risk returning a device that failed
809 			 * before we inc'ed nr_pending
810 			 */
811 			rdev_dec_pending(rdev, conf->mddev);
812 			goto retry;
813 		}
814 		r10_bio->read_slot = slot;
815 	} else
816 		rdev = NULL;
817 	rcu_read_unlock();
818 	*max_sectors = best_good_sectors;
819 
820 	return rdev;
821 }
822 
raid10_congested(struct mddev * mddev,int bits)823 static int raid10_congested(struct mddev *mddev, int bits)
824 {
825 	struct r10conf *conf = mddev->private;
826 	int i, ret = 0;
827 
828 	if ((bits & (1 << WB_async_congested)) &&
829 	    conf->pending_count >= max_queued_requests)
830 		return 1;
831 
832 	rcu_read_lock();
833 	for (i = 0;
834 	     (i < conf->geo.raid_disks || i < conf->prev.raid_disks)
835 		     && ret == 0;
836 	     i++) {
837 		struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
838 		if (rdev && !test_bit(Faulty, &rdev->flags)) {
839 			struct request_queue *q = bdev_get_queue(rdev->bdev);
840 
841 			ret |= bdi_congested(&q->backing_dev_info, bits);
842 		}
843 	}
844 	rcu_read_unlock();
845 	return ret;
846 }
847 
flush_pending_writes(struct r10conf * conf)848 static void flush_pending_writes(struct r10conf *conf)
849 {
850 	/* Any writes that have been queued but are awaiting
851 	 * bitmap updates get flushed here.
852 	 */
853 	spin_lock_irq(&conf->device_lock);
854 
855 	if (conf->pending_bio_list.head) {
856 		struct bio *bio;
857 		bio = bio_list_get(&conf->pending_bio_list);
858 		conf->pending_count = 0;
859 		spin_unlock_irq(&conf->device_lock);
860 		/* flush any pending bitmap writes to disk
861 		 * before proceeding w/ I/O */
862 		bitmap_unplug(conf->mddev->bitmap);
863 		wake_up(&conf->wait_barrier);
864 
865 		while (bio) { /* submit pending writes */
866 			struct bio *next = bio->bi_next;
867 			bio->bi_next = NULL;
868 			if (unlikely((bio->bi_rw & REQ_DISCARD) &&
869 			    !blk_queue_discard(bdev_get_queue(bio->bi_bdev))))
870 				/* Just ignore it */
871 				bio_endio(bio);
872 			else
873 				generic_make_request(bio);
874 			bio = next;
875 		}
876 	} else
877 		spin_unlock_irq(&conf->device_lock);
878 }
879 
880 /* Barriers....
881  * Sometimes we need to suspend IO while we do something else,
882  * either some resync/recovery, or reconfigure the array.
883  * To do this we raise a 'barrier'.
884  * The 'barrier' is a counter that can be raised multiple times
885  * to count how many activities are happening which preclude
886  * normal IO.
887  * We can only raise the barrier if there is no pending IO.
888  * i.e. if nr_pending == 0.
889  * We choose only to raise the barrier if no-one is waiting for the
890  * barrier to go down.  This means that as soon as an IO request
891  * is ready, no other operations which require a barrier will start
892  * until the IO request has had a chance.
893  *
894  * So: regular IO calls 'wait_barrier'.  When that returns there
895  *    is no backgroup IO happening,  It must arrange to call
896  *    allow_barrier when it has finished its IO.
897  * backgroup IO calls must call raise_barrier.  Once that returns
898  *    there is no normal IO happeing.  It must arrange to call
899  *    lower_barrier when the particular background IO completes.
900  */
901 
raise_barrier(struct r10conf * conf,int force)902 static void raise_barrier(struct r10conf *conf, int force)
903 {
904 	BUG_ON(force && !conf->barrier);
905 	spin_lock_irq(&conf->resync_lock);
906 
907 	/* Wait until no block IO is waiting (unless 'force') */
908 	wait_event_lock_irq(conf->wait_barrier, force || !conf->nr_waiting,
909 			    conf->resync_lock);
910 
911 	/* block any new IO from starting */
912 	conf->barrier++;
913 
914 	/* Now wait for all pending IO to complete */
915 	wait_event_lock_irq(conf->wait_barrier,
916 			    !conf->nr_pending && conf->barrier < RESYNC_DEPTH,
917 			    conf->resync_lock);
918 
919 	spin_unlock_irq(&conf->resync_lock);
920 }
921 
lower_barrier(struct r10conf * conf)922 static void lower_barrier(struct r10conf *conf)
923 {
924 	unsigned long flags;
925 	spin_lock_irqsave(&conf->resync_lock, flags);
926 	conf->barrier--;
927 	spin_unlock_irqrestore(&conf->resync_lock, flags);
928 	wake_up(&conf->wait_barrier);
929 }
930 
wait_barrier(struct r10conf * conf)931 static void wait_barrier(struct r10conf *conf)
932 {
933 	spin_lock_irq(&conf->resync_lock);
934 	if (conf->barrier) {
935 		conf->nr_waiting++;
936 		/* Wait for the barrier to drop.
937 		 * However if there are already pending
938 		 * requests (preventing the barrier from
939 		 * rising completely), and the
940 		 * pre-process bio queue isn't empty,
941 		 * then don't wait, as we need to empty
942 		 * that queue to get the nr_pending
943 		 * count down.
944 		 */
945 		wait_event_lock_irq(conf->wait_barrier,
946 				    !conf->barrier ||
947 				    (conf->nr_pending &&
948 				     current->bio_list &&
949 				     (!bio_list_empty(&current->bio_list[0]) ||
950 				      !bio_list_empty(&current->bio_list[1]))),
951 				    conf->resync_lock);
952 		conf->nr_waiting--;
953 	}
954 	conf->nr_pending++;
955 	spin_unlock_irq(&conf->resync_lock);
956 }
957 
allow_barrier(struct r10conf * conf)958 static void allow_barrier(struct r10conf *conf)
959 {
960 	unsigned long flags;
961 	spin_lock_irqsave(&conf->resync_lock, flags);
962 	conf->nr_pending--;
963 	spin_unlock_irqrestore(&conf->resync_lock, flags);
964 	wake_up(&conf->wait_barrier);
965 }
966 
freeze_array(struct r10conf * conf,int extra)967 static void freeze_array(struct r10conf *conf, int extra)
968 {
969 	/* stop syncio and normal IO and wait for everything to
970 	 * go quiet.
971 	 * We increment barrier and nr_waiting, and then
972 	 * wait until nr_pending match nr_queued+extra
973 	 * This is called in the context of one normal IO request
974 	 * that has failed. Thus any sync request that might be pending
975 	 * will be blocked by nr_pending, and we need to wait for
976 	 * pending IO requests to complete or be queued for re-try.
977 	 * Thus the number queued (nr_queued) plus this request (extra)
978 	 * must match the number of pending IOs (nr_pending) before
979 	 * we continue.
980 	 */
981 	spin_lock_irq(&conf->resync_lock);
982 	conf->barrier++;
983 	conf->nr_waiting++;
984 	wait_event_lock_irq_cmd(conf->wait_barrier,
985 				conf->nr_pending == conf->nr_queued+extra,
986 				conf->resync_lock,
987 				flush_pending_writes(conf));
988 
989 	spin_unlock_irq(&conf->resync_lock);
990 }
991 
unfreeze_array(struct r10conf * conf)992 static void unfreeze_array(struct r10conf *conf)
993 {
994 	/* reverse the effect of the freeze */
995 	spin_lock_irq(&conf->resync_lock);
996 	conf->barrier--;
997 	conf->nr_waiting--;
998 	wake_up(&conf->wait_barrier);
999 	spin_unlock_irq(&conf->resync_lock);
1000 }
1001 
choose_data_offset(struct r10bio * r10_bio,struct md_rdev * rdev)1002 static sector_t choose_data_offset(struct r10bio *r10_bio,
1003 				   struct md_rdev *rdev)
1004 {
1005 	if (!test_bit(MD_RECOVERY_RESHAPE, &rdev->mddev->recovery) ||
1006 	    test_bit(R10BIO_Previous, &r10_bio->state))
1007 		return rdev->data_offset;
1008 	else
1009 		return rdev->new_data_offset;
1010 }
1011 
1012 struct raid10_plug_cb {
1013 	struct blk_plug_cb	cb;
1014 	struct bio_list		pending;
1015 	int			pending_cnt;
1016 };
1017 
raid10_unplug(struct blk_plug_cb * cb,bool from_schedule)1018 static void raid10_unplug(struct blk_plug_cb *cb, bool from_schedule)
1019 {
1020 	struct raid10_plug_cb *plug = container_of(cb, struct raid10_plug_cb,
1021 						   cb);
1022 	struct mddev *mddev = plug->cb.data;
1023 	struct r10conf *conf = mddev->private;
1024 	struct bio *bio;
1025 
1026 	if (from_schedule || current->bio_list) {
1027 		spin_lock_irq(&conf->device_lock);
1028 		bio_list_merge(&conf->pending_bio_list, &plug->pending);
1029 		conf->pending_count += plug->pending_cnt;
1030 		spin_unlock_irq(&conf->device_lock);
1031 		wake_up(&conf->wait_barrier);
1032 		md_wakeup_thread(mddev->thread);
1033 		kfree(plug);
1034 		return;
1035 	}
1036 
1037 	/* we aren't scheduling, so we can do the write-out directly. */
1038 	bio = bio_list_get(&plug->pending);
1039 	bitmap_unplug(mddev->bitmap);
1040 	wake_up(&conf->wait_barrier);
1041 
1042 	while (bio) { /* submit pending writes */
1043 		struct bio *next = bio->bi_next;
1044 		bio->bi_next = NULL;
1045 		if (unlikely((bio->bi_rw & REQ_DISCARD) &&
1046 		    !blk_queue_discard(bdev_get_queue(bio->bi_bdev))))
1047 			/* Just ignore it */
1048 			bio_endio(bio);
1049 		else
1050 			generic_make_request(bio);
1051 		bio = next;
1052 	}
1053 	kfree(plug);
1054 }
1055 
__make_request(struct mddev * mddev,struct bio * bio)1056 static void __make_request(struct mddev *mddev, struct bio *bio)
1057 {
1058 	struct r10conf *conf = mddev->private;
1059 	struct r10bio *r10_bio;
1060 	struct bio *read_bio;
1061 	int i;
1062 	const int rw = bio_data_dir(bio);
1063 	const unsigned long do_sync = (bio->bi_rw & REQ_SYNC);
1064 	const unsigned long do_fua = (bio->bi_rw & REQ_FUA);
1065 	const unsigned long do_discard = (bio->bi_rw
1066 					  & (REQ_DISCARD | REQ_SECURE));
1067 	const unsigned long do_same = (bio->bi_rw & REQ_WRITE_SAME);
1068 	unsigned long flags;
1069 	struct md_rdev *blocked_rdev;
1070 	struct blk_plug_cb *cb;
1071 	struct raid10_plug_cb *plug = NULL;
1072 	int sectors_handled;
1073 	int max_sectors;
1074 	int sectors;
1075 
1076 	md_write_start(mddev, bio);
1077 
1078 	/*
1079 	 * Register the new request and wait if the reconstruction
1080 	 * thread has put up a bar for new requests.
1081 	 * Continue immediately if no resync is active currently.
1082 	 */
1083 	wait_barrier(conf);
1084 
1085 	sectors = bio_sectors(bio);
1086 	while (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
1087 	    bio->bi_iter.bi_sector < conf->reshape_progress &&
1088 	    bio->bi_iter.bi_sector + sectors > conf->reshape_progress) {
1089 		/* IO spans the reshape position.  Need to wait for
1090 		 * reshape to pass
1091 		 */
1092 		allow_barrier(conf);
1093 		wait_event(conf->wait_barrier,
1094 			   conf->reshape_progress <= bio->bi_iter.bi_sector ||
1095 			   conf->reshape_progress >= bio->bi_iter.bi_sector +
1096 			   sectors);
1097 		wait_barrier(conf);
1098 	}
1099 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
1100 	    bio_data_dir(bio) == WRITE &&
1101 	    (mddev->reshape_backwards
1102 	     ? (bio->bi_iter.bi_sector < conf->reshape_safe &&
1103 		bio->bi_iter.bi_sector + sectors > conf->reshape_progress)
1104 	     : (bio->bi_iter.bi_sector + sectors > conf->reshape_safe &&
1105 		bio->bi_iter.bi_sector < conf->reshape_progress))) {
1106 		/* Need to update reshape_position in metadata */
1107 		mddev->reshape_position = conf->reshape_progress;
1108 		set_bit(MD_CHANGE_DEVS, &mddev->flags);
1109 		set_bit(MD_CHANGE_PENDING, &mddev->flags);
1110 		md_wakeup_thread(mddev->thread);
1111 		wait_event(mddev->sb_wait,
1112 			   !test_bit(MD_CHANGE_PENDING, &mddev->flags));
1113 
1114 		conf->reshape_safe = mddev->reshape_position;
1115 	}
1116 
1117 	r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1118 
1119 	r10_bio->master_bio = bio;
1120 	r10_bio->sectors = sectors;
1121 
1122 	r10_bio->mddev = mddev;
1123 	r10_bio->sector = bio->bi_iter.bi_sector;
1124 	r10_bio->state = 0;
1125 
1126 	/* We might need to issue multiple reads to different
1127 	 * devices if there are bad blocks around, so we keep
1128 	 * track of the number of reads in bio->bi_phys_segments.
1129 	 * If this is 0, there is only one r10_bio and no locking
1130 	 * will be needed when the request completes.  If it is
1131 	 * non-zero, then it is the number of not-completed requests.
1132 	 */
1133 	bio->bi_phys_segments = 0;
1134 	bio_clear_flag(bio, BIO_SEG_VALID);
1135 
1136 	if (rw == READ) {
1137 		/*
1138 		 * read balancing logic:
1139 		 */
1140 		struct md_rdev *rdev;
1141 		int slot;
1142 
1143 read_again:
1144 		rdev = read_balance(conf, r10_bio, &max_sectors);
1145 		if (!rdev) {
1146 			raid_end_bio_io(r10_bio);
1147 			return;
1148 		}
1149 		slot = r10_bio->read_slot;
1150 
1151 		read_bio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1152 		bio_trim(read_bio, r10_bio->sector - bio->bi_iter.bi_sector,
1153 			 max_sectors);
1154 
1155 		r10_bio->devs[slot].bio = read_bio;
1156 		r10_bio->devs[slot].rdev = rdev;
1157 
1158 		read_bio->bi_iter.bi_sector = r10_bio->devs[slot].addr +
1159 			choose_data_offset(r10_bio, rdev);
1160 		read_bio->bi_bdev = rdev->bdev;
1161 		read_bio->bi_end_io = raid10_end_read_request;
1162 		read_bio->bi_rw = READ | do_sync;
1163 		read_bio->bi_private = r10_bio;
1164 
1165 		if (max_sectors < r10_bio->sectors) {
1166 			/* Could not read all from this device, so we will
1167 			 * need another r10_bio.
1168 			 */
1169 			sectors_handled = (r10_bio->sector + max_sectors
1170 					   - bio->bi_iter.bi_sector);
1171 			r10_bio->sectors = max_sectors;
1172 			spin_lock_irq(&conf->device_lock);
1173 			if (bio->bi_phys_segments == 0)
1174 				bio->bi_phys_segments = 2;
1175 			else
1176 				bio->bi_phys_segments++;
1177 			spin_unlock_irq(&conf->device_lock);
1178 			/* Cannot call generic_make_request directly
1179 			 * as that will be queued in __generic_make_request
1180 			 * and subsequent mempool_alloc might block
1181 			 * waiting for it.  so hand bio over to raid10d.
1182 			 */
1183 			reschedule_retry(r10_bio);
1184 
1185 			r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1186 
1187 			r10_bio->master_bio = bio;
1188 			r10_bio->sectors = bio_sectors(bio) - sectors_handled;
1189 			r10_bio->state = 0;
1190 			r10_bio->mddev = mddev;
1191 			r10_bio->sector = bio->bi_iter.bi_sector +
1192 				sectors_handled;
1193 			goto read_again;
1194 		} else
1195 			generic_make_request(read_bio);
1196 		return;
1197 	}
1198 
1199 	/*
1200 	 * WRITE:
1201 	 */
1202 	if (conf->pending_count >= max_queued_requests) {
1203 		md_wakeup_thread(mddev->thread);
1204 		wait_event(conf->wait_barrier,
1205 			   conf->pending_count < max_queued_requests);
1206 	}
1207 	/* first select target devices under rcu_lock and
1208 	 * inc refcount on their rdev.  Record them by setting
1209 	 * bios[x] to bio
1210 	 * If there are known/acknowledged bad blocks on any device
1211 	 * on which we have seen a write error, we want to avoid
1212 	 * writing to those blocks.  This potentially requires several
1213 	 * writes to write around the bad blocks.  Each set of writes
1214 	 * gets its own r10_bio with a set of bios attached.  The number
1215 	 * of r10_bios is recored in bio->bi_phys_segments just as with
1216 	 * the read case.
1217 	 */
1218 
1219 	r10_bio->read_slot = -1; /* make sure repl_bio gets freed */
1220 	raid10_find_phys(conf, r10_bio);
1221 retry_write:
1222 	blocked_rdev = NULL;
1223 	rcu_read_lock();
1224 	max_sectors = r10_bio->sectors;
1225 
1226 	for (i = 0;  i < conf->copies; i++) {
1227 		int d = r10_bio->devs[i].devnum;
1228 		struct md_rdev *rdev = rcu_dereference(conf->mirrors[d].rdev);
1229 		struct md_rdev *rrdev = rcu_dereference(
1230 			conf->mirrors[d].replacement);
1231 		if (rdev == rrdev)
1232 			rrdev = NULL;
1233 		if (rdev && unlikely(test_bit(Blocked, &rdev->flags))) {
1234 			atomic_inc(&rdev->nr_pending);
1235 			blocked_rdev = rdev;
1236 			break;
1237 		}
1238 		if (rrdev && unlikely(test_bit(Blocked, &rrdev->flags))) {
1239 			atomic_inc(&rrdev->nr_pending);
1240 			blocked_rdev = rrdev;
1241 			break;
1242 		}
1243 		if (rdev && (test_bit(Faulty, &rdev->flags)))
1244 			rdev = NULL;
1245 		if (rrdev && (test_bit(Faulty, &rrdev->flags)))
1246 			rrdev = NULL;
1247 
1248 		r10_bio->devs[i].bio = NULL;
1249 		r10_bio->devs[i].repl_bio = NULL;
1250 
1251 		if (!rdev && !rrdev) {
1252 			set_bit(R10BIO_Degraded, &r10_bio->state);
1253 			continue;
1254 		}
1255 		if (rdev && test_bit(WriteErrorSeen, &rdev->flags)) {
1256 			sector_t first_bad;
1257 			sector_t dev_sector = r10_bio->devs[i].addr;
1258 			int bad_sectors;
1259 			int is_bad;
1260 
1261 			is_bad = is_badblock(rdev, dev_sector,
1262 					     max_sectors,
1263 					     &first_bad, &bad_sectors);
1264 			if (is_bad < 0) {
1265 				/* Mustn't write here until the bad block
1266 				 * is acknowledged
1267 				 */
1268 				atomic_inc(&rdev->nr_pending);
1269 				set_bit(BlockedBadBlocks, &rdev->flags);
1270 				blocked_rdev = rdev;
1271 				break;
1272 			}
1273 			if (is_bad && first_bad <= dev_sector) {
1274 				/* Cannot write here at all */
1275 				bad_sectors -= (dev_sector - first_bad);
1276 				if (bad_sectors < max_sectors)
1277 					/* Mustn't write more than bad_sectors
1278 					 * to other devices yet
1279 					 */
1280 					max_sectors = bad_sectors;
1281 				/* We don't set R10BIO_Degraded as that
1282 				 * only applies if the disk is missing,
1283 				 * so it might be re-added, and we want to
1284 				 * know to recover this chunk.
1285 				 * In this case the device is here, and the
1286 				 * fact that this chunk is not in-sync is
1287 				 * recorded in the bad block log.
1288 				 */
1289 				continue;
1290 			}
1291 			if (is_bad) {
1292 				int good_sectors = first_bad - dev_sector;
1293 				if (good_sectors < max_sectors)
1294 					max_sectors = good_sectors;
1295 			}
1296 		}
1297 		if (rdev) {
1298 			r10_bio->devs[i].bio = bio;
1299 			atomic_inc(&rdev->nr_pending);
1300 		}
1301 		if (rrdev) {
1302 			r10_bio->devs[i].repl_bio = bio;
1303 			atomic_inc(&rrdev->nr_pending);
1304 		}
1305 	}
1306 	rcu_read_unlock();
1307 
1308 	if (unlikely(blocked_rdev)) {
1309 		/* Have to wait for this device to get unblocked, then retry */
1310 		int j;
1311 		int d;
1312 
1313 		for (j = 0; j < i; j++) {
1314 			if (r10_bio->devs[j].bio) {
1315 				d = r10_bio->devs[j].devnum;
1316 				rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1317 			}
1318 			if (r10_bio->devs[j].repl_bio) {
1319 				struct md_rdev *rdev;
1320 				d = r10_bio->devs[j].devnum;
1321 				rdev = conf->mirrors[d].replacement;
1322 				if (!rdev) {
1323 					/* Race with remove_disk */
1324 					smp_mb();
1325 					rdev = conf->mirrors[d].rdev;
1326 				}
1327 				rdev_dec_pending(rdev, mddev);
1328 			}
1329 		}
1330 		allow_barrier(conf);
1331 		md_wait_for_blocked_rdev(blocked_rdev, mddev);
1332 		wait_barrier(conf);
1333 		goto retry_write;
1334 	}
1335 
1336 	if (max_sectors < r10_bio->sectors) {
1337 		/* We are splitting this into multiple parts, so
1338 		 * we need to prepare for allocating another r10_bio.
1339 		 */
1340 		r10_bio->sectors = max_sectors;
1341 		spin_lock_irq(&conf->device_lock);
1342 		if (bio->bi_phys_segments == 0)
1343 			bio->bi_phys_segments = 2;
1344 		else
1345 			bio->bi_phys_segments++;
1346 		spin_unlock_irq(&conf->device_lock);
1347 	}
1348 	sectors_handled = r10_bio->sector + max_sectors -
1349 		bio->bi_iter.bi_sector;
1350 
1351 	atomic_set(&r10_bio->remaining, 1);
1352 	bitmap_startwrite(mddev->bitmap, r10_bio->sector, r10_bio->sectors, 0);
1353 
1354 	for (i = 0; i < conf->copies; i++) {
1355 		struct bio *mbio;
1356 		int d = r10_bio->devs[i].devnum;
1357 		if (r10_bio->devs[i].bio) {
1358 			struct md_rdev *rdev = conf->mirrors[d].rdev;
1359 			mbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1360 			bio_trim(mbio, r10_bio->sector - bio->bi_iter.bi_sector,
1361 				 max_sectors);
1362 			r10_bio->devs[i].bio = mbio;
1363 
1364 			mbio->bi_iter.bi_sector	= (r10_bio->devs[i].addr+
1365 					   choose_data_offset(r10_bio,
1366 							      rdev));
1367 			mbio->bi_bdev = rdev->bdev;
1368 			mbio->bi_end_io	= raid10_end_write_request;
1369 			mbio->bi_rw =
1370 				WRITE | do_sync | do_fua | do_discard | do_same;
1371 			mbio->bi_private = r10_bio;
1372 
1373 			atomic_inc(&r10_bio->remaining);
1374 
1375 			cb = blk_check_plugged(raid10_unplug, mddev,
1376 					       sizeof(*plug));
1377 			if (cb)
1378 				plug = container_of(cb, struct raid10_plug_cb,
1379 						    cb);
1380 			else
1381 				plug = NULL;
1382 			spin_lock_irqsave(&conf->device_lock, flags);
1383 			if (plug) {
1384 				bio_list_add(&plug->pending, mbio);
1385 				plug->pending_cnt++;
1386 			} else {
1387 				bio_list_add(&conf->pending_bio_list, mbio);
1388 				conf->pending_count++;
1389 			}
1390 			spin_unlock_irqrestore(&conf->device_lock, flags);
1391 			if (!plug)
1392 				md_wakeup_thread(mddev->thread);
1393 		}
1394 
1395 		if (r10_bio->devs[i].repl_bio) {
1396 			struct md_rdev *rdev = conf->mirrors[d].replacement;
1397 			if (rdev == NULL) {
1398 				/* Replacement just got moved to main 'rdev' */
1399 				smp_mb();
1400 				rdev = conf->mirrors[d].rdev;
1401 			}
1402 			mbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1403 			bio_trim(mbio, r10_bio->sector - bio->bi_iter.bi_sector,
1404 				 max_sectors);
1405 			r10_bio->devs[i].repl_bio = mbio;
1406 
1407 			mbio->bi_iter.bi_sector	= (r10_bio->devs[i].addr +
1408 					   choose_data_offset(
1409 						   r10_bio, rdev));
1410 			mbio->bi_bdev = rdev->bdev;
1411 			mbio->bi_end_io	= raid10_end_write_request;
1412 			mbio->bi_rw =
1413 				WRITE | do_sync | do_fua | do_discard | do_same;
1414 			mbio->bi_private = r10_bio;
1415 
1416 			atomic_inc(&r10_bio->remaining);
1417 
1418 			cb = blk_check_plugged(raid10_unplug, mddev,
1419 					       sizeof(*plug));
1420 			if (cb)
1421 				plug = container_of(cb, struct raid10_plug_cb,
1422 						    cb);
1423 			else
1424 				plug = NULL;
1425 			spin_lock_irqsave(&conf->device_lock, flags);
1426 			if (plug) {
1427 				bio_list_add(&plug->pending, mbio);
1428 				plug->pending_cnt++;
1429 			} else {
1430 				bio_list_add(&conf->pending_bio_list, mbio);
1431 				conf->pending_count++;
1432 			}
1433 			spin_unlock_irqrestore(&conf->device_lock, flags);
1434 			if (!plug)
1435 				md_wakeup_thread(mddev->thread);
1436 		}
1437 	}
1438 
1439 	/* Don't remove the bias on 'remaining' (one_write_done) until
1440 	 * after checking if we need to go around again.
1441 	 */
1442 
1443 	if (sectors_handled < bio_sectors(bio)) {
1444 		one_write_done(r10_bio);
1445 		/* We need another r10_bio.  It has already been counted
1446 		 * in bio->bi_phys_segments.
1447 		 */
1448 		r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1449 
1450 		r10_bio->master_bio = bio;
1451 		r10_bio->sectors = bio_sectors(bio) - sectors_handled;
1452 
1453 		r10_bio->mddev = mddev;
1454 		r10_bio->sector = bio->bi_iter.bi_sector + sectors_handled;
1455 		r10_bio->state = 0;
1456 		goto retry_write;
1457 	}
1458 	one_write_done(r10_bio);
1459 }
1460 
make_request(struct mddev * mddev,struct bio * bio)1461 static void make_request(struct mddev *mddev, struct bio *bio)
1462 {
1463 	struct r10conf *conf = mddev->private;
1464 	sector_t chunk_mask = (conf->geo.chunk_mask & conf->prev.chunk_mask);
1465 	int chunk_sects = chunk_mask + 1;
1466 
1467 	struct bio *split;
1468 
1469 	if (unlikely(bio->bi_rw & REQ_FLUSH)) {
1470 		md_flush_request(mddev, bio);
1471 		return;
1472 	}
1473 
1474 	do {
1475 
1476 		/*
1477 		 * If this request crosses a chunk boundary, we need to split
1478 		 * it.
1479 		 */
1480 		if (unlikely((bio->bi_iter.bi_sector & chunk_mask) +
1481 			     bio_sectors(bio) > chunk_sects
1482 			     && (conf->geo.near_copies < conf->geo.raid_disks
1483 				 || conf->prev.near_copies <
1484 				 conf->prev.raid_disks))) {
1485 			split = bio_split(bio, chunk_sects -
1486 					  (bio->bi_iter.bi_sector &
1487 					   (chunk_sects - 1)),
1488 					  GFP_NOIO, fs_bio_set);
1489 			bio_chain(split, bio);
1490 		} else {
1491 			split = bio;
1492 		}
1493 
1494 		/*
1495 		 * If a bio is splitted, the first part of bio will pass
1496 		 * barrier but the bio is queued in current->bio_list (see
1497 		 * generic_make_request). If there is a raise_barrier() called
1498 		 * here, the second part of bio can't pass barrier. But since
1499 		 * the first part bio isn't dispatched to underlaying disks
1500 		 * yet, the barrier is never released, hence raise_barrier will
1501 		 * alays wait. We have a deadlock.
1502 		 * Note, this only happens in read path. For write path, the
1503 		 * first part of bio is dispatched in a schedule() call
1504 		 * (because of blk plug) or offloaded to raid10d.
1505 		 * Quitting from the function immediately can change the bio
1506 		 * order queued in bio_list and avoid the deadlock.
1507 		 */
1508 		__make_request(mddev, split);
1509 		if (split != bio && bio_data_dir(bio) == READ) {
1510 			generic_make_request(bio);
1511 			break;
1512 		}
1513 	} while (split != bio);
1514 
1515 	/* In case raid10d snuck in to freeze_array */
1516 	wake_up(&conf->wait_barrier);
1517 }
1518 
status(struct seq_file * seq,struct mddev * mddev)1519 static void status(struct seq_file *seq, struct mddev *mddev)
1520 {
1521 	struct r10conf *conf = mddev->private;
1522 	int i;
1523 
1524 	if (conf->geo.near_copies < conf->geo.raid_disks)
1525 		seq_printf(seq, " %dK chunks", mddev->chunk_sectors / 2);
1526 	if (conf->geo.near_copies > 1)
1527 		seq_printf(seq, " %d near-copies", conf->geo.near_copies);
1528 	if (conf->geo.far_copies > 1) {
1529 		if (conf->geo.far_offset)
1530 			seq_printf(seq, " %d offset-copies", conf->geo.far_copies);
1531 		else
1532 			seq_printf(seq, " %d far-copies", conf->geo.far_copies);
1533 		if (conf->geo.far_set_size != conf->geo.raid_disks)
1534 			seq_printf(seq, " %d devices per set", conf->geo.far_set_size);
1535 	}
1536 	seq_printf(seq, " [%d/%d] [", conf->geo.raid_disks,
1537 					conf->geo.raid_disks - mddev->degraded);
1538 	for (i = 0; i < conf->geo.raid_disks; i++)
1539 		seq_printf(seq, "%s",
1540 			      conf->mirrors[i].rdev &&
1541 			      test_bit(In_sync, &conf->mirrors[i].rdev->flags) ? "U" : "_");
1542 	seq_printf(seq, "]");
1543 }
1544 
1545 /* check if there are enough drives for
1546  * every block to appear on atleast one.
1547  * Don't consider the device numbered 'ignore'
1548  * as we might be about to remove it.
1549  */
_enough(struct r10conf * conf,int previous,int ignore)1550 static int _enough(struct r10conf *conf, int previous, int ignore)
1551 {
1552 	int first = 0;
1553 	int has_enough = 0;
1554 	int disks, ncopies;
1555 	if (previous) {
1556 		disks = conf->prev.raid_disks;
1557 		ncopies = conf->prev.near_copies;
1558 	} else {
1559 		disks = conf->geo.raid_disks;
1560 		ncopies = conf->geo.near_copies;
1561 	}
1562 
1563 	rcu_read_lock();
1564 	do {
1565 		int n = conf->copies;
1566 		int cnt = 0;
1567 		int this = first;
1568 		while (n--) {
1569 			struct md_rdev *rdev;
1570 			if (this != ignore &&
1571 			    (rdev = rcu_dereference(conf->mirrors[this].rdev)) &&
1572 			    test_bit(In_sync, &rdev->flags))
1573 				cnt++;
1574 			this = (this+1) % disks;
1575 		}
1576 		if (cnt == 0)
1577 			goto out;
1578 		first = (first + ncopies) % disks;
1579 	} while (first != 0);
1580 	has_enough = 1;
1581 out:
1582 	rcu_read_unlock();
1583 	return has_enough;
1584 }
1585 
enough(struct r10conf * conf,int ignore)1586 static int enough(struct r10conf *conf, int ignore)
1587 {
1588 	/* when calling 'enough', both 'prev' and 'geo' must
1589 	 * be stable.
1590 	 * This is ensured if ->reconfig_mutex or ->device_lock
1591 	 * is held.
1592 	 */
1593 	return _enough(conf, 0, ignore) &&
1594 		_enough(conf, 1, ignore);
1595 }
1596 
error(struct mddev * mddev,struct md_rdev * rdev)1597 static void error(struct mddev *mddev, struct md_rdev *rdev)
1598 {
1599 	char b[BDEVNAME_SIZE];
1600 	struct r10conf *conf = mddev->private;
1601 	unsigned long flags;
1602 
1603 	/*
1604 	 * If it is not operational, then we have already marked it as dead
1605 	 * else if it is the last working disks, ignore the error, let the
1606 	 * next level up know.
1607 	 * else mark the drive as failed
1608 	 */
1609 	spin_lock_irqsave(&conf->device_lock, flags);
1610 	if (test_bit(In_sync, &rdev->flags)
1611 	    && !enough(conf, rdev->raid_disk)) {
1612 		/*
1613 		 * Don't fail the drive, just return an IO error.
1614 		 */
1615 		spin_unlock_irqrestore(&conf->device_lock, flags);
1616 		return;
1617 	}
1618 	if (test_and_clear_bit(In_sync, &rdev->flags))
1619 		mddev->degraded++;
1620 	/*
1621 	 * If recovery is running, make sure it aborts.
1622 	 */
1623 	set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1624 	set_bit(Blocked, &rdev->flags);
1625 	set_bit(Faulty, &rdev->flags);
1626 	set_bit(MD_CHANGE_DEVS, &mddev->flags);
1627 	set_bit(MD_CHANGE_PENDING, &mddev->flags);
1628 	spin_unlock_irqrestore(&conf->device_lock, flags);
1629 	printk(KERN_ALERT
1630 	       "md/raid10:%s: Disk failure on %s, disabling device.\n"
1631 	       "md/raid10:%s: Operation continuing on %d devices.\n",
1632 	       mdname(mddev), bdevname(rdev->bdev, b),
1633 	       mdname(mddev), conf->geo.raid_disks - mddev->degraded);
1634 }
1635 
print_conf(struct r10conf * conf)1636 static void print_conf(struct r10conf *conf)
1637 {
1638 	int i;
1639 	struct raid10_info *tmp;
1640 
1641 	printk(KERN_DEBUG "RAID10 conf printout:\n");
1642 	if (!conf) {
1643 		printk(KERN_DEBUG "(!conf)\n");
1644 		return;
1645 	}
1646 	printk(KERN_DEBUG " --- wd:%d rd:%d\n", conf->geo.raid_disks - conf->mddev->degraded,
1647 		conf->geo.raid_disks);
1648 
1649 	for (i = 0; i < conf->geo.raid_disks; i++) {
1650 		char b[BDEVNAME_SIZE];
1651 		tmp = conf->mirrors + i;
1652 		if (tmp->rdev)
1653 			printk(KERN_DEBUG " disk %d, wo:%d, o:%d, dev:%s\n",
1654 				i, !test_bit(In_sync, &tmp->rdev->flags),
1655 			        !test_bit(Faulty, &tmp->rdev->flags),
1656 				bdevname(tmp->rdev->bdev,b));
1657 	}
1658 }
1659 
close_sync(struct r10conf * conf)1660 static void close_sync(struct r10conf *conf)
1661 {
1662 	wait_barrier(conf);
1663 	allow_barrier(conf);
1664 
1665 	mempool_destroy(conf->r10buf_pool);
1666 	conf->r10buf_pool = NULL;
1667 }
1668 
raid10_spare_active(struct mddev * mddev)1669 static int raid10_spare_active(struct mddev *mddev)
1670 {
1671 	int i;
1672 	struct r10conf *conf = mddev->private;
1673 	struct raid10_info *tmp;
1674 	int count = 0;
1675 	unsigned long flags;
1676 
1677 	/*
1678 	 * Find all non-in_sync disks within the RAID10 configuration
1679 	 * and mark them in_sync
1680 	 */
1681 	for (i = 0; i < conf->geo.raid_disks; i++) {
1682 		tmp = conf->mirrors + i;
1683 		if (tmp->replacement
1684 		    && tmp->replacement->recovery_offset == MaxSector
1685 		    && !test_bit(Faulty, &tmp->replacement->flags)
1686 		    && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
1687 			/* Replacement has just become active */
1688 			if (!tmp->rdev
1689 			    || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
1690 				count++;
1691 			if (tmp->rdev) {
1692 				/* Replaced device not technically faulty,
1693 				 * but we need to be sure it gets removed
1694 				 * and never re-added.
1695 				 */
1696 				set_bit(Faulty, &tmp->rdev->flags);
1697 				sysfs_notify_dirent_safe(
1698 					tmp->rdev->sysfs_state);
1699 			}
1700 			sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
1701 		} else if (tmp->rdev
1702 			   && tmp->rdev->recovery_offset == MaxSector
1703 			   && !test_bit(Faulty, &tmp->rdev->flags)
1704 			   && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
1705 			count++;
1706 			sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
1707 		}
1708 	}
1709 	spin_lock_irqsave(&conf->device_lock, flags);
1710 	mddev->degraded -= count;
1711 	spin_unlock_irqrestore(&conf->device_lock, flags);
1712 
1713 	print_conf(conf);
1714 	return count;
1715 }
1716 
raid10_add_disk(struct mddev * mddev,struct md_rdev * rdev)1717 static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
1718 {
1719 	struct r10conf *conf = mddev->private;
1720 	int err = -EEXIST;
1721 	int mirror;
1722 	int first = 0;
1723 	int last = conf->geo.raid_disks - 1;
1724 
1725 	if (mddev->recovery_cp < MaxSector)
1726 		/* only hot-add to in-sync arrays, as recovery is
1727 		 * very different from resync
1728 		 */
1729 		return -EBUSY;
1730 	if (rdev->saved_raid_disk < 0 && !_enough(conf, 1, -1))
1731 		return -EINVAL;
1732 
1733 	if (md_integrity_add_rdev(rdev, mddev))
1734 		return -ENXIO;
1735 
1736 	if (rdev->raid_disk >= 0)
1737 		first = last = rdev->raid_disk;
1738 
1739 	if (rdev->saved_raid_disk >= first &&
1740 	    rdev->saved_raid_disk < conf->geo.raid_disks &&
1741 	    conf->mirrors[rdev->saved_raid_disk].rdev == NULL)
1742 		mirror = rdev->saved_raid_disk;
1743 	else
1744 		mirror = first;
1745 	for ( ; mirror <= last ; mirror++) {
1746 		struct raid10_info *p = &conf->mirrors[mirror];
1747 		if (p->recovery_disabled == mddev->recovery_disabled)
1748 			continue;
1749 		if (p->rdev) {
1750 			if (!test_bit(WantReplacement, &p->rdev->flags) ||
1751 			    p->replacement != NULL)
1752 				continue;
1753 			clear_bit(In_sync, &rdev->flags);
1754 			set_bit(Replacement, &rdev->flags);
1755 			rdev->raid_disk = mirror;
1756 			err = 0;
1757 			if (mddev->gendisk)
1758 				disk_stack_limits(mddev->gendisk, rdev->bdev,
1759 						  rdev->data_offset << 9);
1760 			conf->fullsync = 1;
1761 			rcu_assign_pointer(p->replacement, rdev);
1762 			break;
1763 		}
1764 
1765 		if (mddev->gendisk)
1766 			disk_stack_limits(mddev->gendisk, rdev->bdev,
1767 					  rdev->data_offset << 9);
1768 
1769 		p->head_position = 0;
1770 		p->recovery_disabled = mddev->recovery_disabled - 1;
1771 		rdev->raid_disk = mirror;
1772 		err = 0;
1773 		if (rdev->saved_raid_disk != mirror)
1774 			conf->fullsync = 1;
1775 		rcu_assign_pointer(p->rdev, rdev);
1776 		break;
1777 	}
1778 	if (mddev->queue && blk_queue_discard(bdev_get_queue(rdev->bdev)))
1779 		queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, mddev->queue);
1780 
1781 	print_conf(conf);
1782 	return err;
1783 }
1784 
raid10_remove_disk(struct mddev * mddev,struct md_rdev * rdev)1785 static int raid10_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
1786 {
1787 	struct r10conf *conf = mddev->private;
1788 	int err = 0;
1789 	int number = rdev->raid_disk;
1790 	struct md_rdev **rdevp;
1791 	struct raid10_info *p = conf->mirrors + number;
1792 
1793 	print_conf(conf);
1794 	if (rdev == p->rdev)
1795 		rdevp = &p->rdev;
1796 	else if (rdev == p->replacement)
1797 		rdevp = &p->replacement;
1798 	else
1799 		return 0;
1800 
1801 	if (test_bit(In_sync, &rdev->flags) ||
1802 	    atomic_read(&rdev->nr_pending)) {
1803 		err = -EBUSY;
1804 		goto abort;
1805 	}
1806 	/* Only remove faulty devices if recovery
1807 	 * is not possible.
1808 	 */
1809 	if (!test_bit(Faulty, &rdev->flags) &&
1810 	    mddev->recovery_disabled != p->recovery_disabled &&
1811 	    (!p->replacement || p->replacement == rdev) &&
1812 	    number < conf->geo.raid_disks &&
1813 	    enough(conf, -1)) {
1814 		err = -EBUSY;
1815 		goto abort;
1816 	}
1817 	*rdevp = NULL;
1818 	synchronize_rcu();
1819 	if (atomic_read(&rdev->nr_pending)) {
1820 		/* lost the race, try later */
1821 		err = -EBUSY;
1822 		*rdevp = rdev;
1823 		goto abort;
1824 	} else if (p->replacement) {
1825 		/* We must have just cleared 'rdev' */
1826 		p->rdev = p->replacement;
1827 		clear_bit(Replacement, &p->replacement->flags);
1828 		smp_mb(); /* Make sure other CPUs may see both as identical
1829 			   * but will never see neither -- if they are careful.
1830 			   */
1831 		p->replacement = NULL;
1832 		clear_bit(WantReplacement, &rdev->flags);
1833 	} else
1834 		/* We might have just remove the Replacement as faulty
1835 		 * Clear the flag just in case
1836 		 */
1837 		clear_bit(WantReplacement, &rdev->flags);
1838 
1839 	err = md_integrity_register(mddev);
1840 
1841 abort:
1842 
1843 	print_conf(conf);
1844 	return err;
1845 }
1846 
end_sync_read(struct bio * bio)1847 static void end_sync_read(struct bio *bio)
1848 {
1849 	struct r10bio *r10_bio = bio->bi_private;
1850 	struct r10conf *conf = r10_bio->mddev->private;
1851 	int d;
1852 
1853 	if (bio == r10_bio->master_bio) {
1854 		/* this is a reshape read */
1855 		d = r10_bio->read_slot; /* really the read dev */
1856 	} else
1857 		d = find_bio_disk(conf, r10_bio, bio, NULL, NULL);
1858 
1859 	if (!bio->bi_error)
1860 		set_bit(R10BIO_Uptodate, &r10_bio->state);
1861 	else
1862 		/* The write handler will notice the lack of
1863 		 * R10BIO_Uptodate and record any errors etc
1864 		 */
1865 		atomic_add(r10_bio->sectors,
1866 			   &conf->mirrors[d].rdev->corrected_errors);
1867 
1868 	/* for reconstruct, we always reschedule after a read.
1869 	 * for resync, only after all reads
1870 	 */
1871 	rdev_dec_pending(conf->mirrors[d].rdev, conf->mddev);
1872 	if (test_bit(R10BIO_IsRecover, &r10_bio->state) ||
1873 	    atomic_dec_and_test(&r10_bio->remaining)) {
1874 		/* we have read all the blocks,
1875 		 * do the comparison in process context in raid10d
1876 		 */
1877 		reschedule_retry(r10_bio);
1878 	}
1879 }
1880 
end_sync_request(struct r10bio * r10_bio)1881 static void end_sync_request(struct r10bio *r10_bio)
1882 {
1883 	struct mddev *mddev = r10_bio->mddev;
1884 
1885 	while (atomic_dec_and_test(&r10_bio->remaining)) {
1886 		if (r10_bio->master_bio == NULL) {
1887 			/* the primary of several recovery bios */
1888 			sector_t s = r10_bio->sectors;
1889 			if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
1890 			    test_bit(R10BIO_WriteError, &r10_bio->state))
1891 				reschedule_retry(r10_bio);
1892 			else
1893 				put_buf(r10_bio);
1894 			md_done_sync(mddev, s, 1);
1895 			break;
1896 		} else {
1897 			struct r10bio *r10_bio2 = (struct r10bio *)r10_bio->master_bio;
1898 			if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
1899 			    test_bit(R10BIO_WriteError, &r10_bio->state))
1900 				reschedule_retry(r10_bio);
1901 			else
1902 				put_buf(r10_bio);
1903 			r10_bio = r10_bio2;
1904 		}
1905 	}
1906 }
1907 
end_sync_write(struct bio * bio)1908 static void end_sync_write(struct bio *bio)
1909 {
1910 	struct r10bio *r10_bio = bio->bi_private;
1911 	struct mddev *mddev = r10_bio->mddev;
1912 	struct r10conf *conf = mddev->private;
1913 	int d;
1914 	sector_t first_bad;
1915 	int bad_sectors;
1916 	int slot;
1917 	int repl;
1918 	struct md_rdev *rdev = NULL;
1919 
1920 	d = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
1921 	if (repl)
1922 		rdev = conf->mirrors[d].replacement;
1923 	else
1924 		rdev = conf->mirrors[d].rdev;
1925 
1926 	if (bio->bi_error) {
1927 		if (repl)
1928 			md_error(mddev, rdev);
1929 		else {
1930 			set_bit(WriteErrorSeen, &rdev->flags);
1931 			if (!test_and_set_bit(WantReplacement, &rdev->flags))
1932 				set_bit(MD_RECOVERY_NEEDED,
1933 					&rdev->mddev->recovery);
1934 			set_bit(R10BIO_WriteError, &r10_bio->state);
1935 		}
1936 	} else if (is_badblock(rdev,
1937 			     r10_bio->devs[slot].addr,
1938 			     r10_bio->sectors,
1939 			     &first_bad, &bad_sectors))
1940 		set_bit(R10BIO_MadeGood, &r10_bio->state);
1941 
1942 	rdev_dec_pending(rdev, mddev);
1943 
1944 	end_sync_request(r10_bio);
1945 }
1946 
1947 /*
1948  * Note: sync and recover and handled very differently for raid10
1949  * This code is for resync.
1950  * For resync, we read through virtual addresses and read all blocks.
1951  * If there is any error, we schedule a write.  The lowest numbered
1952  * drive is authoritative.
1953  * However requests come for physical address, so we need to map.
1954  * For every physical address there are raid_disks/copies virtual addresses,
1955  * which is always are least one, but is not necessarly an integer.
1956  * This means that a physical address can span multiple chunks, so we may
1957  * have to submit multiple io requests for a single sync request.
1958  */
1959 /*
1960  * We check if all blocks are in-sync and only write to blocks that
1961  * aren't in sync
1962  */
sync_request_write(struct mddev * mddev,struct r10bio * r10_bio)1963 static void sync_request_write(struct mddev *mddev, struct r10bio *r10_bio)
1964 {
1965 	struct r10conf *conf = mddev->private;
1966 	int i, first;
1967 	struct bio *tbio, *fbio;
1968 	int vcnt;
1969 
1970 	atomic_set(&r10_bio->remaining, 1);
1971 
1972 	/* find the first device with a block */
1973 	for (i=0; i<conf->copies; i++)
1974 		if (!r10_bio->devs[i].bio->bi_error)
1975 			break;
1976 
1977 	if (i == conf->copies)
1978 		goto done;
1979 
1980 	first = i;
1981 	fbio = r10_bio->devs[i].bio;
1982 	fbio->bi_iter.bi_size = r10_bio->sectors << 9;
1983 	fbio->bi_iter.bi_idx = 0;
1984 
1985 	vcnt = (r10_bio->sectors + (PAGE_SIZE >> 9) - 1) >> (PAGE_SHIFT - 9);
1986 	/* now find blocks with errors */
1987 	for (i=0 ; i < conf->copies ; i++) {
1988 		int  j, d;
1989 
1990 		tbio = r10_bio->devs[i].bio;
1991 
1992 		if (tbio->bi_end_io != end_sync_read)
1993 			continue;
1994 		if (i == first)
1995 			continue;
1996 		if (!r10_bio->devs[i].bio->bi_error) {
1997 			/* We know that the bi_io_vec layout is the same for
1998 			 * both 'first' and 'i', so we just compare them.
1999 			 * All vec entries are PAGE_SIZE;
2000 			 */
2001 			int sectors = r10_bio->sectors;
2002 			for (j = 0; j < vcnt; j++) {
2003 				int len = PAGE_SIZE;
2004 				if (sectors < (len / 512))
2005 					len = sectors * 512;
2006 				if (memcmp(page_address(fbio->bi_io_vec[j].bv_page),
2007 					   page_address(tbio->bi_io_vec[j].bv_page),
2008 					   len))
2009 					break;
2010 				sectors -= len/512;
2011 			}
2012 			if (j == vcnt)
2013 				continue;
2014 			atomic64_add(r10_bio->sectors, &mddev->resync_mismatches);
2015 			if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
2016 				/* Don't fix anything. */
2017 				continue;
2018 		}
2019 		/* Ok, we need to write this bio, either to correct an
2020 		 * inconsistency or to correct an unreadable block.
2021 		 * First we need to fixup bv_offset, bv_len and
2022 		 * bi_vecs, as the read request might have corrupted these
2023 		 */
2024 		bio_reset(tbio);
2025 
2026 		tbio->bi_vcnt = vcnt;
2027 		tbio->bi_iter.bi_size = fbio->bi_iter.bi_size;
2028 		tbio->bi_rw = WRITE;
2029 		tbio->bi_private = r10_bio;
2030 		tbio->bi_iter.bi_sector = r10_bio->devs[i].addr;
2031 		tbio->bi_end_io = end_sync_write;
2032 
2033 		bio_copy_data(tbio, fbio);
2034 
2035 		d = r10_bio->devs[i].devnum;
2036 		atomic_inc(&conf->mirrors[d].rdev->nr_pending);
2037 		atomic_inc(&r10_bio->remaining);
2038 		md_sync_acct(conf->mirrors[d].rdev->bdev, bio_sectors(tbio));
2039 
2040 		tbio->bi_iter.bi_sector += conf->mirrors[d].rdev->data_offset;
2041 		tbio->bi_bdev = conf->mirrors[d].rdev->bdev;
2042 		generic_make_request(tbio);
2043 	}
2044 
2045 	/* Now write out to any replacement devices
2046 	 * that are active
2047 	 */
2048 	for (i = 0; i < conf->copies; i++) {
2049 		int d;
2050 
2051 		tbio = r10_bio->devs[i].repl_bio;
2052 		if (!tbio || !tbio->bi_end_io)
2053 			continue;
2054 		if (r10_bio->devs[i].bio->bi_end_io != end_sync_write
2055 		    && r10_bio->devs[i].bio != fbio)
2056 			bio_copy_data(tbio, fbio);
2057 		d = r10_bio->devs[i].devnum;
2058 		atomic_inc(&r10_bio->remaining);
2059 		md_sync_acct(conf->mirrors[d].replacement->bdev,
2060 			     bio_sectors(tbio));
2061 		generic_make_request(tbio);
2062 	}
2063 
2064 done:
2065 	if (atomic_dec_and_test(&r10_bio->remaining)) {
2066 		md_done_sync(mddev, r10_bio->sectors, 1);
2067 		put_buf(r10_bio);
2068 	}
2069 }
2070 
2071 /*
2072  * Now for the recovery code.
2073  * Recovery happens across physical sectors.
2074  * We recover all non-is_sync drives by finding the virtual address of
2075  * each, and then choose a working drive that also has that virt address.
2076  * There is a separate r10_bio for each non-in_sync drive.
2077  * Only the first two slots are in use. The first for reading,
2078  * The second for writing.
2079  *
2080  */
fix_recovery_read_error(struct r10bio * r10_bio)2081 static void fix_recovery_read_error(struct r10bio *r10_bio)
2082 {
2083 	/* We got a read error during recovery.
2084 	 * We repeat the read in smaller page-sized sections.
2085 	 * If a read succeeds, write it to the new device or record
2086 	 * a bad block if we cannot.
2087 	 * If a read fails, record a bad block on both old and
2088 	 * new devices.
2089 	 */
2090 	struct mddev *mddev = r10_bio->mddev;
2091 	struct r10conf *conf = mddev->private;
2092 	struct bio *bio = r10_bio->devs[0].bio;
2093 	sector_t sect = 0;
2094 	int sectors = r10_bio->sectors;
2095 	int idx = 0;
2096 	int dr = r10_bio->devs[0].devnum;
2097 	int dw = r10_bio->devs[1].devnum;
2098 
2099 	while (sectors) {
2100 		int s = sectors;
2101 		struct md_rdev *rdev;
2102 		sector_t addr;
2103 		int ok;
2104 
2105 		if (s > (PAGE_SIZE>>9))
2106 			s = PAGE_SIZE >> 9;
2107 
2108 		rdev = conf->mirrors[dr].rdev;
2109 		addr = r10_bio->devs[0].addr + sect,
2110 		ok = sync_page_io(rdev,
2111 				  addr,
2112 				  s << 9,
2113 				  bio->bi_io_vec[idx].bv_page,
2114 				  READ, false);
2115 		if (ok) {
2116 			rdev = conf->mirrors[dw].rdev;
2117 			addr = r10_bio->devs[1].addr + sect;
2118 			ok = sync_page_io(rdev,
2119 					  addr,
2120 					  s << 9,
2121 					  bio->bi_io_vec[idx].bv_page,
2122 					  WRITE, false);
2123 			if (!ok) {
2124 				set_bit(WriteErrorSeen, &rdev->flags);
2125 				if (!test_and_set_bit(WantReplacement,
2126 						      &rdev->flags))
2127 					set_bit(MD_RECOVERY_NEEDED,
2128 						&rdev->mddev->recovery);
2129 			}
2130 		}
2131 		if (!ok) {
2132 			/* We don't worry if we cannot set a bad block -
2133 			 * it really is bad so there is no loss in not
2134 			 * recording it yet
2135 			 */
2136 			rdev_set_badblocks(rdev, addr, s, 0);
2137 
2138 			if (rdev != conf->mirrors[dw].rdev) {
2139 				/* need bad block on destination too */
2140 				struct md_rdev *rdev2 = conf->mirrors[dw].rdev;
2141 				addr = r10_bio->devs[1].addr + sect;
2142 				ok = rdev_set_badblocks(rdev2, addr, s, 0);
2143 				if (!ok) {
2144 					/* just abort the recovery */
2145 					printk(KERN_NOTICE
2146 					       "md/raid10:%s: recovery aborted"
2147 					       " due to read error\n",
2148 					       mdname(mddev));
2149 
2150 					conf->mirrors[dw].recovery_disabled
2151 						= mddev->recovery_disabled;
2152 					set_bit(MD_RECOVERY_INTR,
2153 						&mddev->recovery);
2154 					break;
2155 				}
2156 			}
2157 		}
2158 
2159 		sectors -= s;
2160 		sect += s;
2161 		idx++;
2162 	}
2163 }
2164 
recovery_request_write(struct mddev * mddev,struct r10bio * r10_bio)2165 static void recovery_request_write(struct mddev *mddev, struct r10bio *r10_bio)
2166 {
2167 	struct r10conf *conf = mddev->private;
2168 	int d;
2169 	struct bio *wbio, *wbio2;
2170 
2171 	if (!test_bit(R10BIO_Uptodate, &r10_bio->state)) {
2172 		fix_recovery_read_error(r10_bio);
2173 		end_sync_request(r10_bio);
2174 		return;
2175 	}
2176 
2177 	/*
2178 	 * share the pages with the first bio
2179 	 * and submit the write request
2180 	 */
2181 	d = r10_bio->devs[1].devnum;
2182 	wbio = r10_bio->devs[1].bio;
2183 	wbio2 = r10_bio->devs[1].repl_bio;
2184 	/* Need to test wbio2->bi_end_io before we call
2185 	 * generic_make_request as if the former is NULL,
2186 	 * the latter is free to free wbio2.
2187 	 */
2188 	if (wbio2 && !wbio2->bi_end_io)
2189 		wbio2 = NULL;
2190 	if (wbio->bi_end_io) {
2191 		atomic_inc(&conf->mirrors[d].rdev->nr_pending);
2192 		md_sync_acct(conf->mirrors[d].rdev->bdev, bio_sectors(wbio));
2193 		generic_make_request(wbio);
2194 	}
2195 	if (wbio2) {
2196 		atomic_inc(&conf->mirrors[d].replacement->nr_pending);
2197 		md_sync_acct(conf->mirrors[d].replacement->bdev,
2198 			     bio_sectors(wbio2));
2199 		generic_make_request(wbio2);
2200 	}
2201 }
2202 
2203 /*
2204  * Used by fix_read_error() to decay the per rdev read_errors.
2205  * We halve the read error count for every hour that has elapsed
2206  * since the last recorded read error.
2207  *
2208  */
check_decay_read_errors(struct mddev * mddev,struct md_rdev * rdev)2209 static void check_decay_read_errors(struct mddev *mddev, struct md_rdev *rdev)
2210 {
2211 	struct timespec cur_time_mon;
2212 	unsigned long hours_since_last;
2213 	unsigned int read_errors = atomic_read(&rdev->read_errors);
2214 
2215 	ktime_get_ts(&cur_time_mon);
2216 
2217 	if (rdev->last_read_error.tv_sec == 0 &&
2218 	    rdev->last_read_error.tv_nsec == 0) {
2219 		/* first time we've seen a read error */
2220 		rdev->last_read_error = cur_time_mon;
2221 		return;
2222 	}
2223 
2224 	hours_since_last = (cur_time_mon.tv_sec -
2225 			    rdev->last_read_error.tv_sec) / 3600;
2226 
2227 	rdev->last_read_error = cur_time_mon;
2228 
2229 	/*
2230 	 * if hours_since_last is > the number of bits in read_errors
2231 	 * just set read errors to 0. We do this to avoid
2232 	 * overflowing the shift of read_errors by hours_since_last.
2233 	 */
2234 	if (hours_since_last >= 8 * sizeof(read_errors))
2235 		atomic_set(&rdev->read_errors, 0);
2236 	else
2237 		atomic_set(&rdev->read_errors, read_errors >> hours_since_last);
2238 }
2239 
r10_sync_page_io(struct md_rdev * rdev,sector_t sector,int sectors,struct page * page,int rw)2240 static int r10_sync_page_io(struct md_rdev *rdev, sector_t sector,
2241 			    int sectors, struct page *page, int rw)
2242 {
2243 	sector_t first_bad;
2244 	int bad_sectors;
2245 
2246 	if (is_badblock(rdev, sector, sectors, &first_bad, &bad_sectors)
2247 	    && (rw == READ || test_bit(WriteErrorSeen, &rdev->flags)))
2248 		return -1;
2249 	if (sync_page_io(rdev, sector, sectors << 9, page, rw, false))
2250 		/* success */
2251 		return 1;
2252 	if (rw == WRITE) {
2253 		set_bit(WriteErrorSeen, &rdev->flags);
2254 		if (!test_and_set_bit(WantReplacement, &rdev->flags))
2255 			set_bit(MD_RECOVERY_NEEDED,
2256 				&rdev->mddev->recovery);
2257 	}
2258 	/* need to record an error - either for the block or the device */
2259 	if (!rdev_set_badblocks(rdev, sector, sectors, 0))
2260 		md_error(rdev->mddev, rdev);
2261 	return 0;
2262 }
2263 
2264 /*
2265  * This is a kernel thread which:
2266  *
2267  *	1.	Retries failed read operations on working mirrors.
2268  *	2.	Updates the raid superblock when problems encounter.
2269  *	3.	Performs writes following reads for array synchronising.
2270  */
2271 
fix_read_error(struct r10conf * conf,struct mddev * mddev,struct r10bio * r10_bio)2272 static void fix_read_error(struct r10conf *conf, struct mddev *mddev, struct r10bio *r10_bio)
2273 {
2274 	int sect = 0; /* Offset from r10_bio->sector */
2275 	int sectors = r10_bio->sectors;
2276 	struct md_rdev*rdev;
2277 	int max_read_errors = atomic_read(&mddev->max_corr_read_errors);
2278 	int d = r10_bio->devs[r10_bio->read_slot].devnum;
2279 
2280 	/* still own a reference to this rdev, so it cannot
2281 	 * have been cleared recently.
2282 	 */
2283 	rdev = conf->mirrors[d].rdev;
2284 
2285 	if (test_bit(Faulty, &rdev->flags))
2286 		/* drive has already been failed, just ignore any
2287 		   more fix_read_error() attempts */
2288 		return;
2289 
2290 	check_decay_read_errors(mddev, rdev);
2291 	atomic_inc(&rdev->read_errors);
2292 	if (atomic_read(&rdev->read_errors) > max_read_errors) {
2293 		char b[BDEVNAME_SIZE];
2294 		bdevname(rdev->bdev, b);
2295 
2296 		printk(KERN_NOTICE
2297 		       "md/raid10:%s: %s: Raid device exceeded "
2298 		       "read_error threshold [cur %d:max %d]\n",
2299 		       mdname(mddev), b,
2300 		       atomic_read(&rdev->read_errors), max_read_errors);
2301 		printk(KERN_NOTICE
2302 		       "md/raid10:%s: %s: Failing raid device\n",
2303 		       mdname(mddev), b);
2304 		md_error(mddev, conf->mirrors[d].rdev);
2305 		r10_bio->devs[r10_bio->read_slot].bio = IO_BLOCKED;
2306 		return;
2307 	}
2308 
2309 	while(sectors) {
2310 		int s = sectors;
2311 		int sl = r10_bio->read_slot;
2312 		int success = 0;
2313 		int start;
2314 
2315 		if (s > (PAGE_SIZE>>9))
2316 			s = PAGE_SIZE >> 9;
2317 
2318 		rcu_read_lock();
2319 		do {
2320 			sector_t first_bad;
2321 			int bad_sectors;
2322 
2323 			d = r10_bio->devs[sl].devnum;
2324 			rdev = rcu_dereference(conf->mirrors[d].rdev);
2325 			if (rdev &&
2326 			    test_bit(In_sync, &rdev->flags) &&
2327 			    is_badblock(rdev, r10_bio->devs[sl].addr + sect, s,
2328 					&first_bad, &bad_sectors) == 0) {
2329 				atomic_inc(&rdev->nr_pending);
2330 				rcu_read_unlock();
2331 				success = sync_page_io(rdev,
2332 						       r10_bio->devs[sl].addr +
2333 						       sect,
2334 						       s<<9,
2335 						       conf->tmppage, READ, false);
2336 				rdev_dec_pending(rdev, mddev);
2337 				rcu_read_lock();
2338 				if (success)
2339 					break;
2340 			}
2341 			sl++;
2342 			if (sl == conf->copies)
2343 				sl = 0;
2344 		} while (!success && sl != r10_bio->read_slot);
2345 		rcu_read_unlock();
2346 
2347 		if (!success) {
2348 			/* Cannot read from anywhere, just mark the block
2349 			 * as bad on the first device to discourage future
2350 			 * reads.
2351 			 */
2352 			int dn = r10_bio->devs[r10_bio->read_slot].devnum;
2353 			rdev = conf->mirrors[dn].rdev;
2354 
2355 			if (!rdev_set_badblocks(
2356 				    rdev,
2357 				    r10_bio->devs[r10_bio->read_slot].addr
2358 				    + sect,
2359 				    s, 0)) {
2360 				md_error(mddev, rdev);
2361 				r10_bio->devs[r10_bio->read_slot].bio
2362 					= IO_BLOCKED;
2363 			}
2364 			break;
2365 		}
2366 
2367 		start = sl;
2368 		/* write it back and re-read */
2369 		rcu_read_lock();
2370 		while (sl != r10_bio->read_slot) {
2371 			char b[BDEVNAME_SIZE];
2372 
2373 			if (sl==0)
2374 				sl = conf->copies;
2375 			sl--;
2376 			d = r10_bio->devs[sl].devnum;
2377 			rdev = rcu_dereference(conf->mirrors[d].rdev);
2378 			if (!rdev ||
2379 			    !test_bit(In_sync, &rdev->flags))
2380 				continue;
2381 
2382 			atomic_inc(&rdev->nr_pending);
2383 			rcu_read_unlock();
2384 			if (r10_sync_page_io(rdev,
2385 					     r10_bio->devs[sl].addr +
2386 					     sect,
2387 					     s, conf->tmppage, WRITE)
2388 			    == 0) {
2389 				/* Well, this device is dead */
2390 				printk(KERN_NOTICE
2391 				       "md/raid10:%s: read correction "
2392 				       "write failed"
2393 				       " (%d sectors at %llu on %s)\n",
2394 				       mdname(mddev), s,
2395 				       (unsigned long long)(
2396 					       sect +
2397 					       choose_data_offset(r10_bio,
2398 								  rdev)),
2399 				       bdevname(rdev->bdev, b));
2400 				printk(KERN_NOTICE "md/raid10:%s: %s: failing "
2401 				       "drive\n",
2402 				       mdname(mddev),
2403 				       bdevname(rdev->bdev, b));
2404 			}
2405 			rdev_dec_pending(rdev, mddev);
2406 			rcu_read_lock();
2407 		}
2408 		sl = start;
2409 		while (sl != r10_bio->read_slot) {
2410 			char b[BDEVNAME_SIZE];
2411 
2412 			if (sl==0)
2413 				sl = conf->copies;
2414 			sl--;
2415 			d = r10_bio->devs[sl].devnum;
2416 			rdev = rcu_dereference(conf->mirrors[d].rdev);
2417 			if (!rdev ||
2418 			    !test_bit(In_sync, &rdev->flags))
2419 				continue;
2420 
2421 			atomic_inc(&rdev->nr_pending);
2422 			rcu_read_unlock();
2423 			switch (r10_sync_page_io(rdev,
2424 					     r10_bio->devs[sl].addr +
2425 					     sect,
2426 					     s, conf->tmppage,
2427 						 READ)) {
2428 			case 0:
2429 				/* Well, this device is dead */
2430 				printk(KERN_NOTICE
2431 				       "md/raid10:%s: unable to read back "
2432 				       "corrected sectors"
2433 				       " (%d sectors at %llu on %s)\n",
2434 				       mdname(mddev), s,
2435 				       (unsigned long long)(
2436 					       sect +
2437 					       choose_data_offset(r10_bio, rdev)),
2438 				       bdevname(rdev->bdev, b));
2439 				printk(KERN_NOTICE "md/raid10:%s: %s: failing "
2440 				       "drive\n",
2441 				       mdname(mddev),
2442 				       bdevname(rdev->bdev, b));
2443 				break;
2444 			case 1:
2445 				printk(KERN_INFO
2446 				       "md/raid10:%s: read error corrected"
2447 				       " (%d sectors at %llu on %s)\n",
2448 				       mdname(mddev), s,
2449 				       (unsigned long long)(
2450 					       sect +
2451 					       choose_data_offset(r10_bio, rdev)),
2452 				       bdevname(rdev->bdev, b));
2453 				atomic_add(s, &rdev->corrected_errors);
2454 			}
2455 
2456 			rdev_dec_pending(rdev, mddev);
2457 			rcu_read_lock();
2458 		}
2459 		rcu_read_unlock();
2460 
2461 		sectors -= s;
2462 		sect += s;
2463 	}
2464 }
2465 
narrow_write_error(struct r10bio * r10_bio,int i)2466 static int narrow_write_error(struct r10bio *r10_bio, int i)
2467 {
2468 	struct bio *bio = r10_bio->master_bio;
2469 	struct mddev *mddev = r10_bio->mddev;
2470 	struct r10conf *conf = mddev->private;
2471 	struct md_rdev *rdev = conf->mirrors[r10_bio->devs[i].devnum].rdev;
2472 	/* bio has the data to be written to slot 'i' where
2473 	 * we just recently had a write error.
2474 	 * We repeatedly clone the bio and trim down to one block,
2475 	 * then try the write.  Where the write fails we record
2476 	 * a bad block.
2477 	 * It is conceivable that the bio doesn't exactly align with
2478 	 * blocks.  We must handle this.
2479 	 *
2480 	 * We currently own a reference to the rdev.
2481 	 */
2482 
2483 	int block_sectors;
2484 	sector_t sector;
2485 	int sectors;
2486 	int sect_to_write = r10_bio->sectors;
2487 	int ok = 1;
2488 
2489 	if (rdev->badblocks.shift < 0)
2490 		return 0;
2491 
2492 	block_sectors = roundup(1 << rdev->badblocks.shift,
2493 				bdev_logical_block_size(rdev->bdev) >> 9);
2494 	sector = r10_bio->sector;
2495 	sectors = ((r10_bio->sector + block_sectors)
2496 		   & ~(sector_t)(block_sectors - 1))
2497 		- sector;
2498 
2499 	while (sect_to_write) {
2500 		struct bio *wbio;
2501 		if (sectors > sect_to_write)
2502 			sectors = sect_to_write;
2503 		/* Write at 'sector' for 'sectors' */
2504 		wbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
2505 		bio_trim(wbio, sector - bio->bi_iter.bi_sector, sectors);
2506 		wbio->bi_iter.bi_sector = (r10_bio->devs[i].addr+
2507 				   choose_data_offset(r10_bio, rdev) +
2508 				   (sector - r10_bio->sector));
2509 		wbio->bi_bdev = rdev->bdev;
2510 		if (submit_bio_wait(WRITE, wbio) < 0)
2511 			/* Failure! */
2512 			ok = rdev_set_badblocks(rdev, sector,
2513 						sectors, 0)
2514 				&& ok;
2515 
2516 		bio_put(wbio);
2517 		sect_to_write -= sectors;
2518 		sector += sectors;
2519 		sectors = block_sectors;
2520 	}
2521 	return ok;
2522 }
2523 
handle_read_error(struct mddev * mddev,struct r10bio * r10_bio)2524 static void handle_read_error(struct mddev *mddev, struct r10bio *r10_bio)
2525 {
2526 	int slot = r10_bio->read_slot;
2527 	struct bio *bio;
2528 	struct r10conf *conf = mddev->private;
2529 	struct md_rdev *rdev = r10_bio->devs[slot].rdev;
2530 	char b[BDEVNAME_SIZE];
2531 	unsigned long do_sync;
2532 	int max_sectors;
2533 
2534 	/* we got a read error. Maybe the drive is bad.  Maybe just
2535 	 * the block and we can fix it.
2536 	 * We freeze all other IO, and try reading the block from
2537 	 * other devices.  When we find one, we re-write
2538 	 * and check it that fixes the read error.
2539 	 * This is all done synchronously while the array is
2540 	 * frozen.
2541 	 */
2542 	bio = r10_bio->devs[slot].bio;
2543 	bdevname(bio->bi_bdev, b);
2544 	bio_put(bio);
2545 	r10_bio->devs[slot].bio = NULL;
2546 
2547 	if (mddev->ro == 0) {
2548 		freeze_array(conf, 1);
2549 		fix_read_error(conf, mddev, r10_bio);
2550 		unfreeze_array(conf);
2551 	} else
2552 		r10_bio->devs[slot].bio = IO_BLOCKED;
2553 
2554 	rdev_dec_pending(rdev, mddev);
2555 
2556 read_more:
2557 	rdev = read_balance(conf, r10_bio, &max_sectors);
2558 	if (rdev == NULL) {
2559 		printk(KERN_ALERT "md/raid10:%s: %s: unrecoverable I/O"
2560 		       " read error for block %llu\n",
2561 		       mdname(mddev), b,
2562 		       (unsigned long long)r10_bio->sector);
2563 		raid_end_bio_io(r10_bio);
2564 		return;
2565 	}
2566 
2567 	do_sync = (r10_bio->master_bio->bi_rw & REQ_SYNC);
2568 	slot = r10_bio->read_slot;
2569 	printk_ratelimited(
2570 		KERN_ERR
2571 		"md/raid10:%s: %s: redirecting "
2572 		"sector %llu to another mirror\n",
2573 		mdname(mddev),
2574 		bdevname(rdev->bdev, b),
2575 		(unsigned long long)r10_bio->sector);
2576 	bio = bio_clone_mddev(r10_bio->master_bio,
2577 			      GFP_NOIO, mddev);
2578 	bio_trim(bio, r10_bio->sector - bio->bi_iter.bi_sector, max_sectors);
2579 	r10_bio->devs[slot].bio = bio;
2580 	r10_bio->devs[slot].rdev = rdev;
2581 	bio->bi_iter.bi_sector = r10_bio->devs[slot].addr
2582 		+ choose_data_offset(r10_bio, rdev);
2583 	bio->bi_bdev = rdev->bdev;
2584 	bio->bi_rw = READ | do_sync;
2585 	bio->bi_private = r10_bio;
2586 	bio->bi_end_io = raid10_end_read_request;
2587 	if (max_sectors < r10_bio->sectors) {
2588 		/* Drat - have to split this up more */
2589 		struct bio *mbio = r10_bio->master_bio;
2590 		int sectors_handled =
2591 			r10_bio->sector + max_sectors
2592 			- mbio->bi_iter.bi_sector;
2593 		r10_bio->sectors = max_sectors;
2594 		spin_lock_irq(&conf->device_lock);
2595 		if (mbio->bi_phys_segments == 0)
2596 			mbio->bi_phys_segments = 2;
2597 		else
2598 			mbio->bi_phys_segments++;
2599 		spin_unlock_irq(&conf->device_lock);
2600 		generic_make_request(bio);
2601 
2602 		r10_bio = mempool_alloc(conf->r10bio_pool,
2603 					GFP_NOIO);
2604 		r10_bio->master_bio = mbio;
2605 		r10_bio->sectors = bio_sectors(mbio) - sectors_handled;
2606 		r10_bio->state = 0;
2607 		set_bit(R10BIO_ReadError,
2608 			&r10_bio->state);
2609 		r10_bio->mddev = mddev;
2610 		r10_bio->sector = mbio->bi_iter.bi_sector
2611 			+ sectors_handled;
2612 
2613 		goto read_more;
2614 	} else
2615 		generic_make_request(bio);
2616 }
2617 
handle_write_completed(struct r10conf * conf,struct r10bio * r10_bio)2618 static void handle_write_completed(struct r10conf *conf, struct r10bio *r10_bio)
2619 {
2620 	/* Some sort of write request has finished and it
2621 	 * succeeded in writing where we thought there was a
2622 	 * bad block.  So forget the bad block.
2623 	 * Or possibly if failed and we need to record
2624 	 * a bad block.
2625 	 */
2626 	int m;
2627 	struct md_rdev *rdev;
2628 
2629 	if (test_bit(R10BIO_IsSync, &r10_bio->state) ||
2630 	    test_bit(R10BIO_IsRecover, &r10_bio->state)) {
2631 		for (m = 0; m < conf->copies; m++) {
2632 			int dev = r10_bio->devs[m].devnum;
2633 			rdev = conf->mirrors[dev].rdev;
2634 			if (r10_bio->devs[m].bio == NULL ||
2635 				r10_bio->devs[m].bio->bi_end_io == NULL)
2636 				continue;
2637 			if (!r10_bio->devs[m].bio->bi_error) {
2638 				rdev_clear_badblocks(
2639 					rdev,
2640 					r10_bio->devs[m].addr,
2641 					r10_bio->sectors, 0);
2642 			} else {
2643 				if (!rdev_set_badblocks(
2644 					    rdev,
2645 					    r10_bio->devs[m].addr,
2646 					    r10_bio->sectors, 0))
2647 					md_error(conf->mddev, rdev);
2648 			}
2649 			rdev = conf->mirrors[dev].replacement;
2650 			if (r10_bio->devs[m].repl_bio == NULL ||
2651 				r10_bio->devs[m].repl_bio->bi_end_io == NULL)
2652 				continue;
2653 
2654 			if (!r10_bio->devs[m].repl_bio->bi_error) {
2655 				rdev_clear_badblocks(
2656 					rdev,
2657 					r10_bio->devs[m].addr,
2658 					r10_bio->sectors, 0);
2659 			} else {
2660 				if (!rdev_set_badblocks(
2661 					    rdev,
2662 					    r10_bio->devs[m].addr,
2663 					    r10_bio->sectors, 0))
2664 					md_error(conf->mddev, rdev);
2665 			}
2666 		}
2667 		put_buf(r10_bio);
2668 	} else {
2669 		bool fail = false;
2670 		for (m = 0; m < conf->copies; m++) {
2671 			int dev = r10_bio->devs[m].devnum;
2672 			struct bio *bio = r10_bio->devs[m].bio;
2673 			rdev = conf->mirrors[dev].rdev;
2674 			if (bio == IO_MADE_GOOD) {
2675 				rdev_clear_badblocks(
2676 					rdev,
2677 					r10_bio->devs[m].addr,
2678 					r10_bio->sectors, 0);
2679 				rdev_dec_pending(rdev, conf->mddev);
2680 			} else if (bio != NULL && bio->bi_error) {
2681 				fail = true;
2682 				if (!narrow_write_error(r10_bio, m)) {
2683 					md_error(conf->mddev, rdev);
2684 					set_bit(R10BIO_Degraded,
2685 						&r10_bio->state);
2686 				}
2687 				rdev_dec_pending(rdev, conf->mddev);
2688 			}
2689 			bio = r10_bio->devs[m].repl_bio;
2690 			rdev = conf->mirrors[dev].replacement;
2691 			if (rdev && bio == IO_MADE_GOOD) {
2692 				rdev_clear_badblocks(
2693 					rdev,
2694 					r10_bio->devs[m].addr,
2695 					r10_bio->sectors, 0);
2696 				rdev_dec_pending(rdev, conf->mddev);
2697 			}
2698 		}
2699 		if (fail) {
2700 			spin_lock_irq(&conf->device_lock);
2701 			list_add(&r10_bio->retry_list, &conf->bio_end_io_list);
2702 			conf->nr_queued++;
2703 			spin_unlock_irq(&conf->device_lock);
2704 			/*
2705 			 * In case freeze_array() is waiting for condition
2706 			 * nr_pending == nr_queued + extra to be true.
2707 			 */
2708 			wake_up(&conf->wait_barrier);
2709 			md_wakeup_thread(conf->mddev->thread);
2710 		} else {
2711 			if (test_bit(R10BIO_WriteError,
2712 				     &r10_bio->state))
2713 				close_write(r10_bio);
2714 			raid_end_bio_io(r10_bio);
2715 		}
2716 	}
2717 }
2718 
raid10d(struct md_thread * thread)2719 static void raid10d(struct md_thread *thread)
2720 {
2721 	struct mddev *mddev = thread->mddev;
2722 	struct r10bio *r10_bio;
2723 	unsigned long flags;
2724 	struct r10conf *conf = mddev->private;
2725 	struct list_head *head = &conf->retry_list;
2726 	struct blk_plug plug;
2727 
2728 	md_check_recovery(mddev);
2729 
2730 	if (!list_empty_careful(&conf->bio_end_io_list) &&
2731 	    !test_bit(MD_CHANGE_PENDING, &mddev->flags)) {
2732 		LIST_HEAD(tmp);
2733 		spin_lock_irqsave(&conf->device_lock, flags);
2734 		if (!test_bit(MD_CHANGE_PENDING, &mddev->flags)) {
2735 			while (!list_empty(&conf->bio_end_io_list)) {
2736 				list_move(conf->bio_end_io_list.prev, &tmp);
2737 				conf->nr_queued--;
2738 			}
2739 		}
2740 		spin_unlock_irqrestore(&conf->device_lock, flags);
2741 		while (!list_empty(&tmp)) {
2742 			r10_bio = list_first_entry(&tmp, struct r10bio,
2743 						   retry_list);
2744 			list_del(&r10_bio->retry_list);
2745 			if (mddev->degraded)
2746 				set_bit(R10BIO_Degraded, &r10_bio->state);
2747 
2748 			if (test_bit(R10BIO_WriteError,
2749 				     &r10_bio->state))
2750 				close_write(r10_bio);
2751 			raid_end_bio_io(r10_bio);
2752 		}
2753 	}
2754 
2755 	blk_start_plug(&plug);
2756 	for (;;) {
2757 
2758 		flush_pending_writes(conf);
2759 
2760 		spin_lock_irqsave(&conf->device_lock, flags);
2761 		if (list_empty(head)) {
2762 			spin_unlock_irqrestore(&conf->device_lock, flags);
2763 			break;
2764 		}
2765 		r10_bio = list_entry(head->prev, struct r10bio, retry_list);
2766 		list_del(head->prev);
2767 		conf->nr_queued--;
2768 		spin_unlock_irqrestore(&conf->device_lock, flags);
2769 
2770 		mddev = r10_bio->mddev;
2771 		conf = mddev->private;
2772 		if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
2773 		    test_bit(R10BIO_WriteError, &r10_bio->state))
2774 			handle_write_completed(conf, r10_bio);
2775 		else if (test_bit(R10BIO_IsReshape, &r10_bio->state))
2776 			reshape_request_write(mddev, r10_bio);
2777 		else if (test_bit(R10BIO_IsSync, &r10_bio->state))
2778 			sync_request_write(mddev, r10_bio);
2779 		else if (test_bit(R10BIO_IsRecover, &r10_bio->state))
2780 			recovery_request_write(mddev, r10_bio);
2781 		else if (test_bit(R10BIO_ReadError, &r10_bio->state))
2782 			handle_read_error(mddev, r10_bio);
2783 		else {
2784 			/* just a partial read to be scheduled from a
2785 			 * separate context
2786 			 */
2787 			int slot = r10_bio->read_slot;
2788 			generic_make_request(r10_bio->devs[slot].bio);
2789 		}
2790 
2791 		cond_resched();
2792 		if (mddev->flags & ~(1<<MD_CHANGE_PENDING))
2793 			md_check_recovery(mddev);
2794 	}
2795 	blk_finish_plug(&plug);
2796 }
2797 
init_resync(struct r10conf * conf)2798 static int init_resync(struct r10conf *conf)
2799 {
2800 	int buffs;
2801 	int i;
2802 
2803 	buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
2804 	BUG_ON(conf->r10buf_pool);
2805 	conf->have_replacement = 0;
2806 	for (i = 0; i < conf->geo.raid_disks; i++)
2807 		if (conf->mirrors[i].replacement)
2808 			conf->have_replacement = 1;
2809 	conf->r10buf_pool = mempool_create(buffs, r10buf_pool_alloc, r10buf_pool_free, conf);
2810 	if (!conf->r10buf_pool)
2811 		return -ENOMEM;
2812 	conf->next_resync = 0;
2813 	return 0;
2814 }
2815 
2816 /*
2817  * perform a "sync" on one "block"
2818  *
2819  * We need to make sure that no normal I/O request - particularly write
2820  * requests - conflict with active sync requests.
2821  *
2822  * This is achieved by tracking pending requests and a 'barrier' concept
2823  * that can be installed to exclude normal IO requests.
2824  *
2825  * Resync and recovery are handled very differently.
2826  * We differentiate by looking at MD_RECOVERY_SYNC in mddev->recovery.
2827  *
2828  * For resync, we iterate over virtual addresses, read all copies,
2829  * and update if there are differences.  If only one copy is live,
2830  * skip it.
2831  * For recovery, we iterate over physical addresses, read a good
2832  * value for each non-in_sync drive, and over-write.
2833  *
2834  * So, for recovery we may have several outstanding complex requests for a
2835  * given address, one for each out-of-sync device.  We model this by allocating
2836  * a number of r10_bio structures, one for each out-of-sync device.
2837  * As we setup these structures, we collect all bio's together into a list
2838  * which we then process collectively to add pages, and then process again
2839  * to pass to generic_make_request.
2840  *
2841  * The r10_bio structures are linked using a borrowed master_bio pointer.
2842  * This link is counted in ->remaining.  When the r10_bio that points to NULL
2843  * has its remaining count decremented to 0, the whole complex operation
2844  * is complete.
2845  *
2846  */
2847 
sync_request(struct mddev * mddev,sector_t sector_nr,int * skipped)2848 static sector_t sync_request(struct mddev *mddev, sector_t sector_nr,
2849 			     int *skipped)
2850 {
2851 	struct r10conf *conf = mddev->private;
2852 	struct r10bio *r10_bio;
2853 	struct bio *biolist = NULL, *bio;
2854 	sector_t max_sector, nr_sectors;
2855 	int i;
2856 	int max_sync;
2857 	sector_t sync_blocks;
2858 	sector_t sectors_skipped = 0;
2859 	int chunks_skipped = 0;
2860 	sector_t chunk_mask = conf->geo.chunk_mask;
2861 
2862 	if (!conf->r10buf_pool)
2863 		if (init_resync(conf))
2864 			return 0;
2865 
2866 	/*
2867 	 * Allow skipping a full rebuild for incremental assembly
2868 	 * of a clean array, like RAID1 does.
2869 	 */
2870 	if (mddev->bitmap == NULL &&
2871 	    mddev->recovery_cp == MaxSector &&
2872 	    mddev->reshape_position == MaxSector &&
2873 	    !test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
2874 	    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
2875 	    !test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
2876 	    conf->fullsync == 0) {
2877 		*skipped = 1;
2878 		return mddev->dev_sectors - sector_nr;
2879 	}
2880 
2881  skipped:
2882 	max_sector = mddev->dev_sectors;
2883 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
2884 	    test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
2885 		max_sector = mddev->resync_max_sectors;
2886 	if (sector_nr >= max_sector) {
2887 		/* If we aborted, we need to abort the
2888 		 * sync on the 'current' bitmap chucks (there can
2889 		 * be several when recovering multiple devices).
2890 		 * as we may have started syncing it but not finished.
2891 		 * We can find the current address in
2892 		 * mddev->curr_resync, but for recovery,
2893 		 * we need to convert that to several
2894 		 * virtual addresses.
2895 		 */
2896 		if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
2897 			end_reshape(conf);
2898 			close_sync(conf);
2899 			return 0;
2900 		}
2901 
2902 		if (mddev->curr_resync < max_sector) { /* aborted */
2903 			if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
2904 				bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
2905 						&sync_blocks, 1);
2906 			else for (i = 0; i < conf->geo.raid_disks; i++) {
2907 				sector_t sect =
2908 					raid10_find_virt(conf, mddev->curr_resync, i);
2909 				bitmap_end_sync(mddev->bitmap, sect,
2910 						&sync_blocks, 1);
2911 			}
2912 		} else {
2913 			/* completed sync */
2914 			if ((!mddev->bitmap || conf->fullsync)
2915 			    && conf->have_replacement
2916 			    && test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2917 				/* Completed a full sync so the replacements
2918 				 * are now fully recovered.
2919 				 */
2920 				for (i = 0; i < conf->geo.raid_disks; i++)
2921 					if (conf->mirrors[i].replacement)
2922 						conf->mirrors[i].replacement
2923 							->recovery_offset
2924 							= MaxSector;
2925 			}
2926 			conf->fullsync = 0;
2927 		}
2928 		bitmap_close_sync(mddev->bitmap);
2929 		close_sync(conf);
2930 		*skipped = 1;
2931 		return sectors_skipped;
2932 	}
2933 
2934 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
2935 		return reshape_request(mddev, sector_nr, skipped);
2936 
2937 	if (chunks_skipped >= conf->geo.raid_disks) {
2938 		/* if there has been nothing to do on any drive,
2939 		 * then there is nothing to do at all..
2940 		 */
2941 		*skipped = 1;
2942 		return (max_sector - sector_nr) + sectors_skipped;
2943 	}
2944 
2945 	if (max_sector > mddev->resync_max)
2946 		max_sector = mddev->resync_max; /* Don't do IO beyond here */
2947 
2948 	/* make sure whole request will fit in a chunk - if chunks
2949 	 * are meaningful
2950 	 */
2951 	if (conf->geo.near_copies < conf->geo.raid_disks &&
2952 	    max_sector > (sector_nr | chunk_mask))
2953 		max_sector = (sector_nr | chunk_mask) + 1;
2954 
2955 	/* Again, very different code for resync and recovery.
2956 	 * Both must result in an r10bio with a list of bios that
2957 	 * have bi_end_io, bi_sector, bi_bdev set,
2958 	 * and bi_private set to the r10bio.
2959 	 * For recovery, we may actually create several r10bios
2960 	 * with 2 bios in each, that correspond to the bios in the main one.
2961 	 * In this case, the subordinate r10bios link back through a
2962 	 * borrowed master_bio pointer, and the counter in the master
2963 	 * includes a ref from each subordinate.
2964 	 */
2965 	/* First, we decide what to do and set ->bi_end_io
2966 	 * To end_sync_read if we want to read, and
2967 	 * end_sync_write if we will want to write.
2968 	 */
2969 
2970 	max_sync = RESYNC_PAGES << (PAGE_SHIFT-9);
2971 	if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2972 		/* recovery... the complicated one */
2973 		int j;
2974 		r10_bio = NULL;
2975 
2976 		for (i = 0 ; i < conf->geo.raid_disks; i++) {
2977 			int still_degraded;
2978 			struct r10bio *rb2;
2979 			sector_t sect;
2980 			int must_sync;
2981 			int any_working;
2982 			struct raid10_info *mirror = &conf->mirrors[i];
2983 
2984 			if ((mirror->rdev == NULL ||
2985 			     test_bit(In_sync, &mirror->rdev->flags))
2986 			    &&
2987 			    (mirror->replacement == NULL ||
2988 			     test_bit(Faulty,
2989 				      &mirror->replacement->flags)))
2990 				continue;
2991 
2992 			still_degraded = 0;
2993 			/* want to reconstruct this device */
2994 			rb2 = r10_bio;
2995 			sect = raid10_find_virt(conf, sector_nr, i);
2996 			if (sect >= mddev->resync_max_sectors) {
2997 				/* last stripe is not complete - don't
2998 				 * try to recover this sector.
2999 				 */
3000 				continue;
3001 			}
3002 			/* Unless we are doing a full sync, or a replacement
3003 			 * we only need to recover the block if it is set in
3004 			 * the bitmap
3005 			 */
3006 			must_sync = bitmap_start_sync(mddev->bitmap, sect,
3007 						      &sync_blocks, 1);
3008 			if (sync_blocks < max_sync)
3009 				max_sync = sync_blocks;
3010 			if (!must_sync &&
3011 			    mirror->replacement == NULL &&
3012 			    !conf->fullsync) {
3013 				/* yep, skip the sync_blocks here, but don't assume
3014 				 * that there will never be anything to do here
3015 				 */
3016 				chunks_skipped = -1;
3017 				continue;
3018 			}
3019 
3020 			r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
3021 			r10_bio->state = 0;
3022 			raise_barrier(conf, rb2 != NULL);
3023 			atomic_set(&r10_bio->remaining, 0);
3024 
3025 			r10_bio->master_bio = (struct bio*)rb2;
3026 			if (rb2)
3027 				atomic_inc(&rb2->remaining);
3028 			r10_bio->mddev = mddev;
3029 			set_bit(R10BIO_IsRecover, &r10_bio->state);
3030 			r10_bio->sector = sect;
3031 
3032 			raid10_find_phys(conf, r10_bio);
3033 
3034 			/* Need to check if the array will still be
3035 			 * degraded
3036 			 */
3037 			for (j = 0; j < conf->geo.raid_disks; j++)
3038 				if (conf->mirrors[j].rdev == NULL ||
3039 				    test_bit(Faulty, &conf->mirrors[j].rdev->flags)) {
3040 					still_degraded = 1;
3041 					break;
3042 				}
3043 
3044 			must_sync = bitmap_start_sync(mddev->bitmap, sect,
3045 						      &sync_blocks, still_degraded);
3046 
3047 			any_working = 0;
3048 			for (j=0; j<conf->copies;j++) {
3049 				int k;
3050 				int d = r10_bio->devs[j].devnum;
3051 				sector_t from_addr, to_addr;
3052 				struct md_rdev *rdev;
3053 				sector_t sector, first_bad;
3054 				int bad_sectors;
3055 				if (!conf->mirrors[d].rdev ||
3056 				    !test_bit(In_sync, &conf->mirrors[d].rdev->flags))
3057 					continue;
3058 				/* This is where we read from */
3059 				any_working = 1;
3060 				rdev = conf->mirrors[d].rdev;
3061 				sector = r10_bio->devs[j].addr;
3062 
3063 				if (is_badblock(rdev, sector, max_sync,
3064 						&first_bad, &bad_sectors)) {
3065 					if (first_bad > sector)
3066 						max_sync = first_bad - sector;
3067 					else {
3068 						bad_sectors -= (sector
3069 								- first_bad);
3070 						if (max_sync > bad_sectors)
3071 							max_sync = bad_sectors;
3072 						continue;
3073 					}
3074 				}
3075 				bio = r10_bio->devs[0].bio;
3076 				bio_reset(bio);
3077 				bio->bi_next = biolist;
3078 				biolist = bio;
3079 				bio->bi_private = r10_bio;
3080 				bio->bi_end_io = end_sync_read;
3081 				bio->bi_rw = READ;
3082 				from_addr = r10_bio->devs[j].addr;
3083 				bio->bi_iter.bi_sector = from_addr +
3084 					rdev->data_offset;
3085 				bio->bi_bdev = rdev->bdev;
3086 				atomic_inc(&rdev->nr_pending);
3087 				/* and we write to 'i' (if not in_sync) */
3088 
3089 				for (k=0; k<conf->copies; k++)
3090 					if (r10_bio->devs[k].devnum == i)
3091 						break;
3092 				BUG_ON(k == conf->copies);
3093 				to_addr = r10_bio->devs[k].addr;
3094 				r10_bio->devs[0].devnum = d;
3095 				r10_bio->devs[0].addr = from_addr;
3096 				r10_bio->devs[1].devnum = i;
3097 				r10_bio->devs[1].addr = to_addr;
3098 
3099 				rdev = mirror->rdev;
3100 				if (!test_bit(In_sync, &rdev->flags)) {
3101 					bio = r10_bio->devs[1].bio;
3102 					bio_reset(bio);
3103 					bio->bi_next = biolist;
3104 					biolist = bio;
3105 					bio->bi_private = r10_bio;
3106 					bio->bi_end_io = end_sync_write;
3107 					bio->bi_rw = WRITE;
3108 					bio->bi_iter.bi_sector = to_addr
3109 						+ rdev->data_offset;
3110 					bio->bi_bdev = rdev->bdev;
3111 					atomic_inc(&r10_bio->remaining);
3112 				} else
3113 					r10_bio->devs[1].bio->bi_end_io = NULL;
3114 
3115 				/* and maybe write to replacement */
3116 				bio = r10_bio->devs[1].repl_bio;
3117 				if (bio)
3118 					bio->bi_end_io = NULL;
3119 				rdev = mirror->replacement;
3120 				/* Note: if rdev != NULL, then bio
3121 				 * cannot be NULL as r10buf_pool_alloc will
3122 				 * have allocated it.
3123 				 * So the second test here is pointless.
3124 				 * But it keeps semantic-checkers happy, and
3125 				 * this comment keeps human reviewers
3126 				 * happy.
3127 				 */
3128 				if (rdev == NULL || bio == NULL ||
3129 				    test_bit(Faulty, &rdev->flags))
3130 					break;
3131 				bio_reset(bio);
3132 				bio->bi_next = biolist;
3133 				biolist = bio;
3134 				bio->bi_private = r10_bio;
3135 				bio->bi_end_io = end_sync_write;
3136 				bio->bi_rw = WRITE;
3137 				bio->bi_iter.bi_sector = to_addr +
3138 					rdev->data_offset;
3139 				bio->bi_bdev = rdev->bdev;
3140 				atomic_inc(&r10_bio->remaining);
3141 				break;
3142 			}
3143 			if (j == conf->copies) {
3144 				/* Cannot recover, so abort the recovery or
3145 				 * record a bad block */
3146 				if (any_working) {
3147 					/* problem is that there are bad blocks
3148 					 * on other device(s)
3149 					 */
3150 					int k;
3151 					for (k = 0; k < conf->copies; k++)
3152 						if (r10_bio->devs[k].devnum == i)
3153 							break;
3154 					if (!test_bit(In_sync,
3155 						      &mirror->rdev->flags)
3156 					    && !rdev_set_badblocks(
3157 						    mirror->rdev,
3158 						    r10_bio->devs[k].addr,
3159 						    max_sync, 0))
3160 						any_working = 0;
3161 					if (mirror->replacement &&
3162 					    !rdev_set_badblocks(
3163 						    mirror->replacement,
3164 						    r10_bio->devs[k].addr,
3165 						    max_sync, 0))
3166 						any_working = 0;
3167 				}
3168 				if (!any_working)  {
3169 					if (!test_and_set_bit(MD_RECOVERY_INTR,
3170 							      &mddev->recovery))
3171 						printk(KERN_INFO "md/raid10:%s: insufficient "
3172 						       "working devices for recovery.\n",
3173 						       mdname(mddev));
3174 					mirror->recovery_disabled
3175 						= mddev->recovery_disabled;
3176 				}
3177 				put_buf(r10_bio);
3178 				if (rb2)
3179 					atomic_dec(&rb2->remaining);
3180 				r10_bio = rb2;
3181 				break;
3182 			}
3183 		}
3184 		if (biolist == NULL) {
3185 			while (r10_bio) {
3186 				struct r10bio *rb2 = r10_bio;
3187 				r10_bio = (struct r10bio*) rb2->master_bio;
3188 				rb2->master_bio = NULL;
3189 				put_buf(rb2);
3190 			}
3191 			goto giveup;
3192 		}
3193 	} else {
3194 		/* resync. Schedule a read for every block at this virt offset */
3195 		int count = 0;
3196 
3197 		bitmap_cond_end_sync(mddev->bitmap, sector_nr, 0);
3198 
3199 		if (!bitmap_start_sync(mddev->bitmap, sector_nr,
3200 				       &sync_blocks, mddev->degraded) &&
3201 		    !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED,
3202 						 &mddev->recovery)) {
3203 			/* We can skip this block */
3204 			*skipped = 1;
3205 			return sync_blocks + sectors_skipped;
3206 		}
3207 		if (sync_blocks < max_sync)
3208 			max_sync = sync_blocks;
3209 		r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
3210 		r10_bio->state = 0;
3211 
3212 		r10_bio->mddev = mddev;
3213 		atomic_set(&r10_bio->remaining, 0);
3214 		raise_barrier(conf, 0);
3215 		conf->next_resync = sector_nr;
3216 
3217 		r10_bio->master_bio = NULL;
3218 		r10_bio->sector = sector_nr;
3219 		set_bit(R10BIO_IsSync, &r10_bio->state);
3220 		raid10_find_phys(conf, r10_bio);
3221 		r10_bio->sectors = (sector_nr | chunk_mask) - sector_nr + 1;
3222 
3223 		for (i = 0; i < conf->copies; i++) {
3224 			int d = r10_bio->devs[i].devnum;
3225 			sector_t first_bad, sector;
3226 			int bad_sectors;
3227 
3228 			if (r10_bio->devs[i].repl_bio)
3229 				r10_bio->devs[i].repl_bio->bi_end_io = NULL;
3230 
3231 			bio = r10_bio->devs[i].bio;
3232 			bio_reset(bio);
3233 			bio->bi_error = -EIO;
3234 			if (conf->mirrors[d].rdev == NULL ||
3235 			    test_bit(Faulty, &conf->mirrors[d].rdev->flags))
3236 				continue;
3237 			sector = r10_bio->devs[i].addr;
3238 			if (is_badblock(conf->mirrors[d].rdev,
3239 					sector, max_sync,
3240 					&first_bad, &bad_sectors)) {
3241 				if (first_bad > sector)
3242 					max_sync = first_bad - sector;
3243 				else {
3244 					bad_sectors -= (sector - first_bad);
3245 					if (max_sync > bad_sectors)
3246 						max_sync = bad_sectors;
3247 					continue;
3248 				}
3249 			}
3250 			atomic_inc(&conf->mirrors[d].rdev->nr_pending);
3251 			atomic_inc(&r10_bio->remaining);
3252 			bio->bi_next = biolist;
3253 			biolist = bio;
3254 			bio->bi_private = r10_bio;
3255 			bio->bi_end_io = end_sync_read;
3256 			bio->bi_rw = READ;
3257 			bio->bi_iter.bi_sector = sector +
3258 				conf->mirrors[d].rdev->data_offset;
3259 			bio->bi_bdev = conf->mirrors[d].rdev->bdev;
3260 			count++;
3261 
3262 			if (conf->mirrors[d].replacement == NULL ||
3263 			    test_bit(Faulty,
3264 				     &conf->mirrors[d].replacement->flags))
3265 				continue;
3266 
3267 			/* Need to set up for writing to the replacement */
3268 			bio = r10_bio->devs[i].repl_bio;
3269 			bio_reset(bio);
3270 			bio->bi_error = -EIO;
3271 
3272 			sector = r10_bio->devs[i].addr;
3273 			atomic_inc(&conf->mirrors[d].rdev->nr_pending);
3274 			bio->bi_next = biolist;
3275 			biolist = bio;
3276 			bio->bi_private = r10_bio;
3277 			bio->bi_end_io = end_sync_write;
3278 			bio->bi_rw = WRITE;
3279 			bio->bi_iter.bi_sector = sector +
3280 				conf->mirrors[d].replacement->data_offset;
3281 			bio->bi_bdev = conf->mirrors[d].replacement->bdev;
3282 			count++;
3283 		}
3284 
3285 		if (count < 2) {
3286 			for (i=0; i<conf->copies; i++) {
3287 				int d = r10_bio->devs[i].devnum;
3288 				if (r10_bio->devs[i].bio->bi_end_io)
3289 					rdev_dec_pending(conf->mirrors[d].rdev,
3290 							 mddev);
3291 				if (r10_bio->devs[i].repl_bio &&
3292 				    r10_bio->devs[i].repl_bio->bi_end_io)
3293 					rdev_dec_pending(
3294 						conf->mirrors[d].replacement,
3295 						mddev);
3296 			}
3297 			put_buf(r10_bio);
3298 			biolist = NULL;
3299 			goto giveup;
3300 		}
3301 	}
3302 
3303 	nr_sectors = 0;
3304 	if (sector_nr + max_sync < max_sector)
3305 		max_sector = sector_nr + max_sync;
3306 	do {
3307 		struct page *page;
3308 		int len = PAGE_SIZE;
3309 		if (sector_nr + (len>>9) > max_sector)
3310 			len = (max_sector - sector_nr) << 9;
3311 		if (len == 0)
3312 			break;
3313 		for (bio= biolist ; bio ; bio=bio->bi_next) {
3314 			struct bio *bio2;
3315 			page = bio->bi_io_vec[bio->bi_vcnt].bv_page;
3316 			if (bio_add_page(bio, page, len, 0))
3317 				continue;
3318 
3319 			/* stop here */
3320 			bio->bi_io_vec[bio->bi_vcnt].bv_page = page;
3321 			for (bio2 = biolist;
3322 			     bio2 && bio2 != bio;
3323 			     bio2 = bio2->bi_next) {
3324 				/* remove last page from this bio */
3325 				bio2->bi_vcnt--;
3326 				bio2->bi_iter.bi_size -= len;
3327 				bio_clear_flag(bio2, BIO_SEG_VALID);
3328 			}
3329 			goto bio_full;
3330 		}
3331 		nr_sectors += len>>9;
3332 		sector_nr += len>>9;
3333 	} while (biolist->bi_vcnt < RESYNC_PAGES);
3334  bio_full:
3335 	r10_bio->sectors = nr_sectors;
3336 
3337 	while (biolist) {
3338 		bio = biolist;
3339 		biolist = biolist->bi_next;
3340 
3341 		bio->bi_next = NULL;
3342 		r10_bio = bio->bi_private;
3343 		r10_bio->sectors = nr_sectors;
3344 
3345 		if (bio->bi_end_io == end_sync_read) {
3346 			md_sync_acct(bio->bi_bdev, nr_sectors);
3347 			bio->bi_error = 0;
3348 			generic_make_request(bio);
3349 		}
3350 	}
3351 
3352 	if (sectors_skipped)
3353 		/* pretend they weren't skipped, it makes
3354 		 * no important difference in this case
3355 		 */
3356 		md_done_sync(mddev, sectors_skipped, 1);
3357 
3358 	return sectors_skipped + nr_sectors;
3359  giveup:
3360 	/* There is nowhere to write, so all non-sync
3361 	 * drives must be failed or in resync, all drives
3362 	 * have a bad block, so try the next chunk...
3363 	 */
3364 	if (sector_nr + max_sync < max_sector)
3365 		max_sector = sector_nr + max_sync;
3366 
3367 	sectors_skipped += (max_sector - sector_nr);
3368 	chunks_skipped ++;
3369 	sector_nr = max_sector;
3370 	goto skipped;
3371 }
3372 
3373 static sector_t
raid10_size(struct mddev * mddev,sector_t sectors,int raid_disks)3374 raid10_size(struct mddev *mddev, sector_t sectors, int raid_disks)
3375 {
3376 	sector_t size;
3377 	struct r10conf *conf = mddev->private;
3378 
3379 	if (!raid_disks)
3380 		raid_disks = min(conf->geo.raid_disks,
3381 				 conf->prev.raid_disks);
3382 	if (!sectors)
3383 		sectors = conf->dev_sectors;
3384 
3385 	size = sectors >> conf->geo.chunk_shift;
3386 	sector_div(size, conf->geo.far_copies);
3387 	size = size * raid_disks;
3388 	sector_div(size, conf->geo.near_copies);
3389 
3390 	return size << conf->geo.chunk_shift;
3391 }
3392 
calc_sectors(struct r10conf * conf,sector_t size)3393 static void calc_sectors(struct r10conf *conf, sector_t size)
3394 {
3395 	/* Calculate the number of sectors-per-device that will
3396 	 * actually be used, and set conf->dev_sectors and
3397 	 * conf->stride
3398 	 */
3399 
3400 	size = size >> conf->geo.chunk_shift;
3401 	sector_div(size, conf->geo.far_copies);
3402 	size = size * conf->geo.raid_disks;
3403 	sector_div(size, conf->geo.near_copies);
3404 	/* 'size' is now the number of chunks in the array */
3405 	/* calculate "used chunks per device" */
3406 	size = size * conf->copies;
3407 
3408 	/* We need to round up when dividing by raid_disks to
3409 	 * get the stride size.
3410 	 */
3411 	size = DIV_ROUND_UP_SECTOR_T(size, conf->geo.raid_disks);
3412 
3413 	conf->dev_sectors = size << conf->geo.chunk_shift;
3414 
3415 	if (conf->geo.far_offset)
3416 		conf->geo.stride = 1 << conf->geo.chunk_shift;
3417 	else {
3418 		sector_div(size, conf->geo.far_copies);
3419 		conf->geo.stride = size << conf->geo.chunk_shift;
3420 	}
3421 }
3422 
3423 enum geo_type {geo_new, geo_old, geo_start};
setup_geo(struct geom * geo,struct mddev * mddev,enum geo_type new)3424 static int setup_geo(struct geom *geo, struct mddev *mddev, enum geo_type new)
3425 {
3426 	int nc, fc, fo;
3427 	int layout, chunk, disks;
3428 	switch (new) {
3429 	case geo_old:
3430 		layout = mddev->layout;
3431 		chunk = mddev->chunk_sectors;
3432 		disks = mddev->raid_disks - mddev->delta_disks;
3433 		break;
3434 	case geo_new:
3435 		layout = mddev->new_layout;
3436 		chunk = mddev->new_chunk_sectors;
3437 		disks = mddev->raid_disks;
3438 		break;
3439 	default: /* avoid 'may be unused' warnings */
3440 	case geo_start: /* new when starting reshape - raid_disks not
3441 			 * updated yet. */
3442 		layout = mddev->new_layout;
3443 		chunk = mddev->new_chunk_sectors;
3444 		disks = mddev->raid_disks + mddev->delta_disks;
3445 		break;
3446 	}
3447 	if (layout >> 19)
3448 		return -1;
3449 	if (chunk < (PAGE_SIZE >> 9) ||
3450 	    !is_power_of_2(chunk))
3451 		return -2;
3452 	nc = layout & 255;
3453 	fc = (layout >> 8) & 255;
3454 	fo = layout & (1<<16);
3455 	geo->raid_disks = disks;
3456 	geo->near_copies = nc;
3457 	geo->far_copies = fc;
3458 	geo->far_offset = fo;
3459 	switch (layout >> 17) {
3460 	case 0:	/* original layout.  simple but not always optimal */
3461 		geo->far_set_size = disks;
3462 		break;
3463 	case 1: /* "improved" layout which was buggy.  Hopefully no-one is
3464 		 * actually using this, but leave code here just in case.*/
3465 		geo->far_set_size = disks/fc;
3466 		WARN(geo->far_set_size < fc,
3467 		     "This RAID10 layout does not provide data safety - please backup and create new array\n");
3468 		break;
3469 	case 2: /* "improved" layout fixed to match documentation */
3470 		geo->far_set_size = fc * nc;
3471 		break;
3472 	default: /* Not a valid layout */
3473 		return -1;
3474 	}
3475 	geo->chunk_mask = chunk - 1;
3476 	geo->chunk_shift = ffz(~chunk);
3477 	return nc*fc;
3478 }
3479 
setup_conf(struct mddev * mddev)3480 static struct r10conf *setup_conf(struct mddev *mddev)
3481 {
3482 	struct r10conf *conf = NULL;
3483 	int err = -EINVAL;
3484 	struct geom geo;
3485 	int copies;
3486 
3487 	copies = setup_geo(&geo, mddev, geo_new);
3488 
3489 	if (copies == -2) {
3490 		printk(KERN_ERR "md/raid10:%s: chunk size must be "
3491 		       "at least PAGE_SIZE(%ld) and be a power of 2.\n",
3492 		       mdname(mddev), PAGE_SIZE);
3493 		goto out;
3494 	}
3495 
3496 	if (copies < 2 || copies > mddev->raid_disks) {
3497 		printk(KERN_ERR "md/raid10:%s: unsupported raid10 layout: 0x%8x\n",
3498 		       mdname(mddev), mddev->new_layout);
3499 		goto out;
3500 	}
3501 
3502 	err = -ENOMEM;
3503 	conf = kzalloc(sizeof(struct r10conf), GFP_KERNEL);
3504 	if (!conf)
3505 		goto out;
3506 
3507 	/* FIXME calc properly */
3508 	conf->mirrors = kzalloc(sizeof(struct raid10_info)*(mddev->raid_disks +
3509 							    max(0,-mddev->delta_disks)),
3510 				GFP_KERNEL);
3511 	if (!conf->mirrors)
3512 		goto out;
3513 
3514 	conf->tmppage = alloc_page(GFP_KERNEL);
3515 	if (!conf->tmppage)
3516 		goto out;
3517 
3518 	conf->geo = geo;
3519 	conf->copies = copies;
3520 	conf->r10bio_pool = mempool_create(NR_RAID10_BIOS, r10bio_pool_alloc,
3521 					   r10bio_pool_free, conf);
3522 	if (!conf->r10bio_pool)
3523 		goto out;
3524 
3525 	calc_sectors(conf, mddev->dev_sectors);
3526 	if (mddev->reshape_position == MaxSector) {
3527 		conf->prev = conf->geo;
3528 		conf->reshape_progress = MaxSector;
3529 	} else {
3530 		if (setup_geo(&conf->prev, mddev, geo_old) != conf->copies) {
3531 			err = -EINVAL;
3532 			goto out;
3533 		}
3534 		conf->reshape_progress = mddev->reshape_position;
3535 		if (conf->prev.far_offset)
3536 			conf->prev.stride = 1 << conf->prev.chunk_shift;
3537 		else
3538 			/* far_copies must be 1 */
3539 			conf->prev.stride = conf->dev_sectors;
3540 	}
3541 	conf->reshape_safe = conf->reshape_progress;
3542 	spin_lock_init(&conf->device_lock);
3543 	INIT_LIST_HEAD(&conf->retry_list);
3544 	INIT_LIST_HEAD(&conf->bio_end_io_list);
3545 
3546 	spin_lock_init(&conf->resync_lock);
3547 	init_waitqueue_head(&conf->wait_barrier);
3548 
3549 	conf->thread = md_register_thread(raid10d, mddev, "raid10");
3550 	if (!conf->thread)
3551 		goto out;
3552 
3553 	conf->mddev = mddev;
3554 	return conf;
3555 
3556  out:
3557 	if (err == -ENOMEM)
3558 		printk(KERN_ERR "md/raid10:%s: couldn't allocate memory.\n",
3559 		       mdname(mddev));
3560 	if (conf) {
3561 		mempool_destroy(conf->r10bio_pool);
3562 		kfree(conf->mirrors);
3563 		safe_put_page(conf->tmppage);
3564 		kfree(conf);
3565 	}
3566 	return ERR_PTR(err);
3567 }
3568 
run(struct mddev * mddev)3569 static int run(struct mddev *mddev)
3570 {
3571 	struct r10conf *conf;
3572 	int i, disk_idx, chunk_size;
3573 	struct raid10_info *disk;
3574 	struct md_rdev *rdev;
3575 	sector_t size;
3576 	sector_t min_offset_diff = 0;
3577 	int first = 1;
3578 	bool discard_supported = false;
3579 
3580 	if (mddev->private == NULL) {
3581 		conf = setup_conf(mddev);
3582 		if (IS_ERR(conf))
3583 			return PTR_ERR(conf);
3584 		mddev->private = conf;
3585 	}
3586 	conf = mddev->private;
3587 	if (!conf)
3588 		goto out;
3589 
3590 	mddev->thread = conf->thread;
3591 	conf->thread = NULL;
3592 
3593 	chunk_size = mddev->chunk_sectors << 9;
3594 	if (mddev->queue) {
3595 		blk_queue_max_discard_sectors(mddev->queue,
3596 					      mddev->chunk_sectors);
3597 		blk_queue_max_write_same_sectors(mddev->queue, 0);
3598 		blk_queue_io_min(mddev->queue, chunk_size);
3599 		if (conf->geo.raid_disks % conf->geo.near_copies)
3600 			blk_queue_io_opt(mddev->queue, chunk_size * conf->geo.raid_disks);
3601 		else
3602 			blk_queue_io_opt(mddev->queue, chunk_size *
3603 					 (conf->geo.raid_disks / conf->geo.near_copies));
3604 	}
3605 
3606 	rdev_for_each(rdev, mddev) {
3607 		long long diff;
3608 		struct request_queue *q;
3609 
3610 		disk_idx = rdev->raid_disk;
3611 		if (disk_idx < 0)
3612 			continue;
3613 		if (disk_idx >= conf->geo.raid_disks &&
3614 		    disk_idx >= conf->prev.raid_disks)
3615 			continue;
3616 		disk = conf->mirrors + disk_idx;
3617 
3618 		if (test_bit(Replacement, &rdev->flags)) {
3619 			if (disk->replacement)
3620 				goto out_free_conf;
3621 			disk->replacement = rdev;
3622 		} else {
3623 			if (disk->rdev)
3624 				goto out_free_conf;
3625 			disk->rdev = rdev;
3626 		}
3627 		q = bdev_get_queue(rdev->bdev);
3628 		diff = (rdev->new_data_offset - rdev->data_offset);
3629 		if (!mddev->reshape_backwards)
3630 			diff = -diff;
3631 		if (diff < 0)
3632 			diff = 0;
3633 		if (first || diff < min_offset_diff)
3634 			min_offset_diff = diff;
3635 
3636 		if (mddev->gendisk)
3637 			disk_stack_limits(mddev->gendisk, rdev->bdev,
3638 					  rdev->data_offset << 9);
3639 
3640 		disk->head_position = 0;
3641 
3642 		if (blk_queue_discard(bdev_get_queue(rdev->bdev)))
3643 			discard_supported = true;
3644 		first = 0;
3645 	}
3646 
3647 	if (mddev->queue) {
3648 		if (discard_supported)
3649 			queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
3650 						mddev->queue);
3651 		else
3652 			queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
3653 						  mddev->queue);
3654 	}
3655 	/* need to check that every block has at least one working mirror */
3656 	if (!enough(conf, -1)) {
3657 		printk(KERN_ERR "md/raid10:%s: not enough operational mirrors.\n",
3658 		       mdname(mddev));
3659 		goto out_free_conf;
3660 	}
3661 
3662 	if (conf->reshape_progress != MaxSector) {
3663 		/* must ensure that shape change is supported */
3664 		if (conf->geo.far_copies != 1 &&
3665 		    conf->geo.far_offset == 0)
3666 			goto out_free_conf;
3667 		if (conf->prev.far_copies != 1 &&
3668 		    conf->prev.far_offset == 0)
3669 			goto out_free_conf;
3670 	}
3671 
3672 	mddev->degraded = 0;
3673 	for (i = 0;
3674 	     i < conf->geo.raid_disks
3675 		     || i < conf->prev.raid_disks;
3676 	     i++) {
3677 
3678 		disk = conf->mirrors + i;
3679 
3680 		if (!disk->rdev && disk->replacement) {
3681 			/* The replacement is all we have - use it */
3682 			disk->rdev = disk->replacement;
3683 			disk->replacement = NULL;
3684 			clear_bit(Replacement, &disk->rdev->flags);
3685 		}
3686 
3687 		if (!disk->rdev ||
3688 		    !test_bit(In_sync, &disk->rdev->flags)) {
3689 			disk->head_position = 0;
3690 			mddev->degraded++;
3691 			if (disk->rdev &&
3692 			    disk->rdev->saved_raid_disk < 0)
3693 				conf->fullsync = 1;
3694 		}
3695 
3696 		if (disk->replacement &&
3697 		    !test_bit(In_sync, &disk->replacement->flags) &&
3698 		    disk->replacement->saved_raid_disk < 0) {
3699 			conf->fullsync = 1;
3700 		}
3701 
3702 		disk->recovery_disabled = mddev->recovery_disabled - 1;
3703 	}
3704 
3705 	if (mddev->recovery_cp != MaxSector)
3706 		printk(KERN_NOTICE "md/raid10:%s: not clean"
3707 		       " -- starting background reconstruction\n",
3708 		       mdname(mddev));
3709 	printk(KERN_INFO
3710 		"md/raid10:%s: active with %d out of %d devices\n",
3711 		mdname(mddev), conf->geo.raid_disks - mddev->degraded,
3712 		conf->geo.raid_disks);
3713 	/*
3714 	 * Ok, everything is just fine now
3715 	 */
3716 	mddev->dev_sectors = conf->dev_sectors;
3717 	size = raid10_size(mddev, 0, 0);
3718 	md_set_array_sectors(mddev, size);
3719 	mddev->resync_max_sectors = size;
3720 
3721 	if (mddev->queue) {
3722 		int stripe = conf->geo.raid_disks *
3723 			((mddev->chunk_sectors << 9) / PAGE_SIZE);
3724 
3725 		/* Calculate max read-ahead size.
3726 		 * We need to readahead at least twice a whole stripe....
3727 		 * maybe...
3728 		 */
3729 		stripe /= conf->geo.near_copies;
3730 		if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
3731 			mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
3732 	}
3733 
3734 	if (md_integrity_register(mddev))
3735 		goto out_free_conf;
3736 
3737 	if (conf->reshape_progress != MaxSector) {
3738 		unsigned long before_length, after_length;
3739 
3740 		before_length = ((1 << conf->prev.chunk_shift) *
3741 				 conf->prev.far_copies);
3742 		after_length = ((1 << conf->geo.chunk_shift) *
3743 				conf->geo.far_copies);
3744 
3745 		if (max(before_length, after_length) > min_offset_diff) {
3746 			/* This cannot work */
3747 			printk("md/raid10: offset difference not enough to continue reshape\n");
3748 			goto out_free_conf;
3749 		}
3750 		conf->offset_diff = min_offset_diff;
3751 
3752 		clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3753 		clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
3754 		set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
3755 		set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
3756 		mddev->sync_thread = md_register_thread(md_do_sync, mddev,
3757 							"reshape");
3758 		if (!mddev->sync_thread)
3759 			goto out_free_conf;
3760 	}
3761 
3762 	return 0;
3763 
3764 out_free_conf:
3765 	md_unregister_thread(&mddev->thread);
3766 	mempool_destroy(conf->r10bio_pool);
3767 	safe_put_page(conf->tmppage);
3768 	kfree(conf->mirrors);
3769 	kfree(conf);
3770 	mddev->private = NULL;
3771 out:
3772 	return -EIO;
3773 }
3774 
raid10_free(struct mddev * mddev,void * priv)3775 static void raid10_free(struct mddev *mddev, void *priv)
3776 {
3777 	struct r10conf *conf = priv;
3778 
3779 	mempool_destroy(conf->r10bio_pool);
3780 	safe_put_page(conf->tmppage);
3781 	kfree(conf->mirrors);
3782 	kfree(conf->mirrors_old);
3783 	kfree(conf->mirrors_new);
3784 	kfree(conf);
3785 }
3786 
raid10_quiesce(struct mddev * mddev,int state)3787 static void raid10_quiesce(struct mddev *mddev, int state)
3788 {
3789 	struct r10conf *conf = mddev->private;
3790 
3791 	switch(state) {
3792 	case 1:
3793 		raise_barrier(conf, 0);
3794 		break;
3795 	case 0:
3796 		lower_barrier(conf);
3797 		break;
3798 	}
3799 }
3800 
raid10_resize(struct mddev * mddev,sector_t sectors)3801 static int raid10_resize(struct mddev *mddev, sector_t sectors)
3802 {
3803 	/* Resize of 'far' arrays is not supported.
3804 	 * For 'near' and 'offset' arrays we can set the
3805 	 * number of sectors used to be an appropriate multiple
3806 	 * of the chunk size.
3807 	 * For 'offset', this is far_copies*chunksize.
3808 	 * For 'near' the multiplier is the LCM of
3809 	 * near_copies and raid_disks.
3810 	 * So if far_copies > 1 && !far_offset, fail.
3811 	 * Else find LCM(raid_disks, near_copy)*far_copies and
3812 	 * multiply by chunk_size.  Then round to this number.
3813 	 * This is mostly done by raid10_size()
3814 	 */
3815 	struct r10conf *conf = mddev->private;
3816 	sector_t oldsize, size;
3817 
3818 	if (mddev->reshape_position != MaxSector)
3819 		return -EBUSY;
3820 
3821 	if (conf->geo.far_copies > 1 && !conf->geo.far_offset)
3822 		return -EINVAL;
3823 
3824 	oldsize = raid10_size(mddev, 0, 0);
3825 	size = raid10_size(mddev, sectors, 0);
3826 	if (mddev->external_size &&
3827 	    mddev->array_sectors > size)
3828 		return -EINVAL;
3829 	if (mddev->bitmap) {
3830 		int ret = bitmap_resize(mddev->bitmap, size, 0, 0);
3831 		if (ret)
3832 			return ret;
3833 	}
3834 	md_set_array_sectors(mddev, size);
3835 	set_capacity(mddev->gendisk, mddev->array_sectors);
3836 	revalidate_disk(mddev->gendisk);
3837 	if (sectors > mddev->dev_sectors &&
3838 	    mddev->recovery_cp > oldsize) {
3839 		mddev->recovery_cp = oldsize;
3840 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3841 	}
3842 	calc_sectors(conf, sectors);
3843 	mddev->dev_sectors = conf->dev_sectors;
3844 	mddev->resync_max_sectors = size;
3845 	return 0;
3846 }
3847 
raid10_takeover_raid0(struct mddev * mddev,sector_t size,int devs)3848 static void *raid10_takeover_raid0(struct mddev *mddev, sector_t size, int devs)
3849 {
3850 	struct md_rdev *rdev;
3851 	struct r10conf *conf;
3852 
3853 	if (mddev->degraded > 0) {
3854 		printk(KERN_ERR "md/raid10:%s: Error: degraded raid0!\n",
3855 		       mdname(mddev));
3856 		return ERR_PTR(-EINVAL);
3857 	}
3858 	sector_div(size, devs);
3859 
3860 	/* Set new parameters */
3861 	mddev->new_level = 10;
3862 	/* new layout: far_copies = 1, near_copies = 2 */
3863 	mddev->new_layout = (1<<8) + 2;
3864 	mddev->new_chunk_sectors = mddev->chunk_sectors;
3865 	mddev->delta_disks = mddev->raid_disks;
3866 	mddev->raid_disks *= 2;
3867 	/* make sure it will be not marked as dirty */
3868 	mddev->recovery_cp = MaxSector;
3869 	mddev->dev_sectors = size;
3870 
3871 	conf = setup_conf(mddev);
3872 	if (!IS_ERR(conf)) {
3873 		rdev_for_each(rdev, mddev)
3874 			if (rdev->raid_disk >= 0) {
3875 				rdev->new_raid_disk = rdev->raid_disk * 2;
3876 				rdev->sectors = size;
3877 			}
3878 		conf->barrier = 1;
3879 	}
3880 
3881 	return conf;
3882 }
3883 
raid10_takeover(struct mddev * mddev)3884 static void *raid10_takeover(struct mddev *mddev)
3885 {
3886 	struct r0conf *raid0_conf;
3887 
3888 	/* raid10 can take over:
3889 	 *  raid0 - providing it has only two drives
3890 	 */
3891 	if (mddev->level == 0) {
3892 		/* for raid0 takeover only one zone is supported */
3893 		raid0_conf = mddev->private;
3894 		if (raid0_conf->nr_strip_zones > 1) {
3895 			printk(KERN_ERR "md/raid10:%s: cannot takeover raid 0"
3896 			       " with more than one zone.\n",
3897 			       mdname(mddev));
3898 			return ERR_PTR(-EINVAL);
3899 		}
3900 		return raid10_takeover_raid0(mddev,
3901 			raid0_conf->strip_zone->zone_end,
3902 			raid0_conf->strip_zone->nb_dev);
3903 	}
3904 	return ERR_PTR(-EINVAL);
3905 }
3906 
raid10_check_reshape(struct mddev * mddev)3907 static int raid10_check_reshape(struct mddev *mddev)
3908 {
3909 	/* Called when there is a request to change
3910 	 * - layout (to ->new_layout)
3911 	 * - chunk size (to ->new_chunk_sectors)
3912 	 * - raid_disks (by delta_disks)
3913 	 * or when trying to restart a reshape that was ongoing.
3914 	 *
3915 	 * We need to validate the request and possibly allocate
3916 	 * space if that might be an issue later.
3917 	 *
3918 	 * Currently we reject any reshape of a 'far' mode array,
3919 	 * allow chunk size to change if new is generally acceptable,
3920 	 * allow raid_disks to increase, and allow
3921 	 * a switch between 'near' mode and 'offset' mode.
3922 	 */
3923 	struct r10conf *conf = mddev->private;
3924 	struct geom geo;
3925 
3926 	if (conf->geo.far_copies != 1 && !conf->geo.far_offset)
3927 		return -EINVAL;
3928 
3929 	if (setup_geo(&geo, mddev, geo_start) != conf->copies)
3930 		/* mustn't change number of copies */
3931 		return -EINVAL;
3932 	if (geo.far_copies > 1 && !geo.far_offset)
3933 		/* Cannot switch to 'far' mode */
3934 		return -EINVAL;
3935 
3936 	if (mddev->array_sectors & geo.chunk_mask)
3937 			/* not factor of array size */
3938 			return -EINVAL;
3939 
3940 	if (!enough(conf, -1))
3941 		return -EINVAL;
3942 
3943 	kfree(conf->mirrors_new);
3944 	conf->mirrors_new = NULL;
3945 	if (mddev->delta_disks > 0) {
3946 		/* allocate new 'mirrors' list */
3947 		conf->mirrors_new = kzalloc(
3948 			sizeof(struct raid10_info)
3949 			*(mddev->raid_disks +
3950 			  mddev->delta_disks),
3951 			GFP_KERNEL);
3952 		if (!conf->mirrors_new)
3953 			return -ENOMEM;
3954 	}
3955 	return 0;
3956 }
3957 
3958 /*
3959  * Need to check if array has failed when deciding whether to:
3960  *  - start an array
3961  *  - remove non-faulty devices
3962  *  - add a spare
3963  *  - allow a reshape
3964  * This determination is simple when no reshape is happening.
3965  * However if there is a reshape, we need to carefully check
3966  * both the before and after sections.
3967  * This is because some failed devices may only affect one
3968  * of the two sections, and some non-in_sync devices may
3969  * be insync in the section most affected by failed devices.
3970  */
calc_degraded(struct r10conf * conf)3971 static int calc_degraded(struct r10conf *conf)
3972 {
3973 	int degraded, degraded2;
3974 	int i;
3975 
3976 	rcu_read_lock();
3977 	degraded = 0;
3978 	/* 'prev' section first */
3979 	for (i = 0; i < conf->prev.raid_disks; i++) {
3980 		struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
3981 		if (!rdev || test_bit(Faulty, &rdev->flags))
3982 			degraded++;
3983 		else if (!test_bit(In_sync, &rdev->flags))
3984 			/* When we can reduce the number of devices in
3985 			 * an array, this might not contribute to
3986 			 * 'degraded'.  It does now.
3987 			 */
3988 			degraded++;
3989 	}
3990 	rcu_read_unlock();
3991 	if (conf->geo.raid_disks == conf->prev.raid_disks)
3992 		return degraded;
3993 	rcu_read_lock();
3994 	degraded2 = 0;
3995 	for (i = 0; i < conf->geo.raid_disks; i++) {
3996 		struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
3997 		if (!rdev || test_bit(Faulty, &rdev->flags))
3998 			degraded2++;
3999 		else if (!test_bit(In_sync, &rdev->flags)) {
4000 			/* If reshape is increasing the number of devices,
4001 			 * this section has already been recovered, so
4002 			 * it doesn't contribute to degraded.
4003 			 * else it does.
4004 			 */
4005 			if (conf->geo.raid_disks <= conf->prev.raid_disks)
4006 				degraded2++;
4007 		}
4008 	}
4009 	rcu_read_unlock();
4010 	if (degraded2 > degraded)
4011 		return degraded2;
4012 	return degraded;
4013 }
4014 
raid10_start_reshape(struct mddev * mddev)4015 static int raid10_start_reshape(struct mddev *mddev)
4016 {
4017 	/* A 'reshape' has been requested. This commits
4018 	 * the various 'new' fields and sets MD_RECOVER_RESHAPE
4019 	 * This also checks if there are enough spares and adds them
4020 	 * to the array.
4021 	 * We currently require enough spares to make the final
4022 	 * array non-degraded.  We also require that the difference
4023 	 * between old and new data_offset - on each device - is
4024 	 * enough that we never risk over-writing.
4025 	 */
4026 
4027 	unsigned long before_length, after_length;
4028 	sector_t min_offset_diff = 0;
4029 	int first = 1;
4030 	struct geom new;
4031 	struct r10conf *conf = mddev->private;
4032 	struct md_rdev *rdev;
4033 	int spares = 0;
4034 	int ret;
4035 
4036 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4037 		return -EBUSY;
4038 
4039 	if (setup_geo(&new, mddev, geo_start) != conf->copies)
4040 		return -EINVAL;
4041 
4042 	before_length = ((1 << conf->prev.chunk_shift) *
4043 			 conf->prev.far_copies);
4044 	after_length = ((1 << conf->geo.chunk_shift) *
4045 			conf->geo.far_copies);
4046 
4047 	rdev_for_each(rdev, mddev) {
4048 		if (!test_bit(In_sync, &rdev->flags)
4049 		    && !test_bit(Faulty, &rdev->flags))
4050 			spares++;
4051 		if (rdev->raid_disk >= 0) {
4052 			long long diff = (rdev->new_data_offset
4053 					  - rdev->data_offset);
4054 			if (!mddev->reshape_backwards)
4055 				diff = -diff;
4056 			if (diff < 0)
4057 				diff = 0;
4058 			if (first || diff < min_offset_diff)
4059 				min_offset_diff = diff;
4060 			first = 0;
4061 		}
4062 	}
4063 
4064 	if (max(before_length, after_length) > min_offset_diff)
4065 		return -EINVAL;
4066 
4067 	if (spares < mddev->delta_disks)
4068 		return -EINVAL;
4069 
4070 	conf->offset_diff = min_offset_diff;
4071 	spin_lock_irq(&conf->device_lock);
4072 	if (conf->mirrors_new) {
4073 		memcpy(conf->mirrors_new, conf->mirrors,
4074 		       sizeof(struct raid10_info)*conf->prev.raid_disks);
4075 		smp_mb();
4076 		kfree(conf->mirrors_old);
4077 		conf->mirrors_old = conf->mirrors;
4078 		conf->mirrors = conf->mirrors_new;
4079 		conf->mirrors_new = NULL;
4080 	}
4081 	setup_geo(&conf->geo, mddev, geo_start);
4082 	smp_mb();
4083 	if (mddev->reshape_backwards) {
4084 		sector_t size = raid10_size(mddev, 0, 0);
4085 		if (size < mddev->array_sectors) {
4086 			spin_unlock_irq(&conf->device_lock);
4087 			printk(KERN_ERR "md/raid10:%s: array size must be reduce before number of disks\n",
4088 			       mdname(mddev));
4089 			return -EINVAL;
4090 		}
4091 		mddev->resync_max_sectors = size;
4092 		conf->reshape_progress = size;
4093 	} else
4094 		conf->reshape_progress = 0;
4095 	conf->reshape_safe = conf->reshape_progress;
4096 	spin_unlock_irq(&conf->device_lock);
4097 
4098 	if (mddev->delta_disks && mddev->bitmap) {
4099 		ret = bitmap_resize(mddev->bitmap,
4100 				    raid10_size(mddev, 0,
4101 						conf->geo.raid_disks),
4102 				    0, 0);
4103 		if (ret)
4104 			goto abort;
4105 	}
4106 	if (mddev->delta_disks > 0) {
4107 		rdev_for_each(rdev, mddev)
4108 			if (rdev->raid_disk < 0 &&
4109 			    !test_bit(Faulty, &rdev->flags)) {
4110 				if (raid10_add_disk(mddev, rdev) == 0) {
4111 					if (rdev->raid_disk >=
4112 					    conf->prev.raid_disks)
4113 						set_bit(In_sync, &rdev->flags);
4114 					else
4115 						rdev->recovery_offset = 0;
4116 
4117 					if (sysfs_link_rdev(mddev, rdev))
4118 						/* Failure here  is OK */;
4119 				}
4120 			} else if (rdev->raid_disk >= conf->prev.raid_disks
4121 				   && !test_bit(Faulty, &rdev->flags)) {
4122 				/* This is a spare that was manually added */
4123 				set_bit(In_sync, &rdev->flags);
4124 			}
4125 	}
4126 	/* When a reshape changes the number of devices,
4127 	 * ->degraded is measured against the larger of the
4128 	 * pre and  post numbers.
4129 	 */
4130 	spin_lock_irq(&conf->device_lock);
4131 	mddev->degraded = calc_degraded(conf);
4132 	spin_unlock_irq(&conf->device_lock);
4133 	mddev->raid_disks = conf->geo.raid_disks;
4134 	mddev->reshape_position = conf->reshape_progress;
4135 	set_bit(MD_CHANGE_DEVS, &mddev->flags);
4136 
4137 	clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4138 	clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4139 	clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
4140 	set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
4141 	set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
4142 
4143 	mddev->sync_thread = md_register_thread(md_do_sync, mddev,
4144 						"reshape");
4145 	if (!mddev->sync_thread) {
4146 		ret = -EAGAIN;
4147 		goto abort;
4148 	}
4149 	conf->reshape_checkpoint = jiffies;
4150 	md_wakeup_thread(mddev->sync_thread);
4151 	md_new_event(mddev);
4152 	return 0;
4153 
4154 abort:
4155 	mddev->recovery = 0;
4156 	spin_lock_irq(&conf->device_lock);
4157 	conf->geo = conf->prev;
4158 	mddev->raid_disks = conf->geo.raid_disks;
4159 	rdev_for_each(rdev, mddev)
4160 		rdev->new_data_offset = rdev->data_offset;
4161 	smp_wmb();
4162 	conf->reshape_progress = MaxSector;
4163 	conf->reshape_safe = MaxSector;
4164 	mddev->reshape_position = MaxSector;
4165 	spin_unlock_irq(&conf->device_lock);
4166 	return ret;
4167 }
4168 
4169 /* Calculate the last device-address that could contain
4170  * any block from the chunk that includes the array-address 's'
4171  * and report the next address.
4172  * i.e. the address returned will be chunk-aligned and after
4173  * any data that is in the chunk containing 's'.
4174  */
last_dev_address(sector_t s,struct geom * geo)4175 static sector_t last_dev_address(sector_t s, struct geom *geo)
4176 {
4177 	s = (s | geo->chunk_mask) + 1;
4178 	s >>= geo->chunk_shift;
4179 	s *= geo->near_copies;
4180 	s = DIV_ROUND_UP_SECTOR_T(s, geo->raid_disks);
4181 	s *= geo->far_copies;
4182 	s <<= geo->chunk_shift;
4183 	return s;
4184 }
4185 
4186 /* Calculate the first device-address that could contain
4187  * any block from the chunk that includes the array-address 's'.
4188  * This too will be the start of a chunk
4189  */
first_dev_address(sector_t s,struct geom * geo)4190 static sector_t first_dev_address(sector_t s, struct geom *geo)
4191 {
4192 	s >>= geo->chunk_shift;
4193 	s *= geo->near_copies;
4194 	sector_div(s, geo->raid_disks);
4195 	s *= geo->far_copies;
4196 	s <<= geo->chunk_shift;
4197 	return s;
4198 }
4199 
reshape_request(struct mddev * mddev,sector_t sector_nr,int * skipped)4200 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr,
4201 				int *skipped)
4202 {
4203 	/* We simply copy at most one chunk (smallest of old and new)
4204 	 * at a time, possibly less if that exceeds RESYNC_PAGES,
4205 	 * or we hit a bad block or something.
4206 	 * This might mean we pause for normal IO in the middle of
4207 	 * a chunk, but that is not a problem as mddev->reshape_position
4208 	 * can record any location.
4209 	 *
4210 	 * If we will want to write to a location that isn't
4211 	 * yet recorded as 'safe' (i.e. in metadata on disk) then
4212 	 * we need to flush all reshape requests and update the metadata.
4213 	 *
4214 	 * When reshaping forwards (e.g. to more devices), we interpret
4215 	 * 'safe' as the earliest block which might not have been copied
4216 	 * down yet.  We divide this by previous stripe size and multiply
4217 	 * by previous stripe length to get lowest device offset that we
4218 	 * cannot write to yet.
4219 	 * We interpret 'sector_nr' as an address that we want to write to.
4220 	 * From this we use last_device_address() to find where we might
4221 	 * write to, and first_device_address on the  'safe' position.
4222 	 * If this 'next' write position is after the 'safe' position,
4223 	 * we must update the metadata to increase the 'safe' position.
4224 	 *
4225 	 * When reshaping backwards, we round in the opposite direction
4226 	 * and perform the reverse test:  next write position must not be
4227 	 * less than current safe position.
4228 	 *
4229 	 * In all this the minimum difference in data offsets
4230 	 * (conf->offset_diff - always positive) allows a bit of slack,
4231 	 * so next can be after 'safe', but not by more than offset_diff
4232 	 *
4233 	 * We need to prepare all the bios here before we start any IO
4234 	 * to ensure the size we choose is acceptable to all devices.
4235 	 * The means one for each copy for write-out and an extra one for
4236 	 * read-in.
4237 	 * We store the read-in bio in ->master_bio and the others in
4238 	 * ->devs[x].bio and ->devs[x].repl_bio.
4239 	 */
4240 	struct r10conf *conf = mddev->private;
4241 	struct r10bio *r10_bio;
4242 	sector_t next, safe, last;
4243 	int max_sectors;
4244 	int nr_sectors;
4245 	int s;
4246 	struct md_rdev *rdev;
4247 	int need_flush = 0;
4248 	struct bio *blist;
4249 	struct bio *bio, *read_bio;
4250 	int sectors_done = 0;
4251 
4252 	if (sector_nr == 0) {
4253 		/* If restarting in the middle, skip the initial sectors */
4254 		if (mddev->reshape_backwards &&
4255 		    conf->reshape_progress < raid10_size(mddev, 0, 0)) {
4256 			sector_nr = (raid10_size(mddev, 0, 0)
4257 				     - conf->reshape_progress);
4258 		} else if (!mddev->reshape_backwards &&
4259 			   conf->reshape_progress > 0)
4260 			sector_nr = conf->reshape_progress;
4261 		if (sector_nr) {
4262 			mddev->curr_resync_completed = sector_nr;
4263 			sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4264 			*skipped = 1;
4265 			return sector_nr;
4266 		}
4267 	}
4268 
4269 	/* We don't use sector_nr to track where we are up to
4270 	 * as that doesn't work well for ->reshape_backwards.
4271 	 * So just use ->reshape_progress.
4272 	 */
4273 	if (mddev->reshape_backwards) {
4274 		/* 'next' is the earliest device address that we might
4275 		 * write to for this chunk in the new layout
4276 		 */
4277 		next = first_dev_address(conf->reshape_progress - 1,
4278 					 &conf->geo);
4279 
4280 		/* 'safe' is the last device address that we might read from
4281 		 * in the old layout after a restart
4282 		 */
4283 		safe = last_dev_address(conf->reshape_safe - 1,
4284 					&conf->prev);
4285 
4286 		if (next + conf->offset_diff < safe)
4287 			need_flush = 1;
4288 
4289 		last = conf->reshape_progress - 1;
4290 		sector_nr = last & ~(sector_t)(conf->geo.chunk_mask
4291 					       & conf->prev.chunk_mask);
4292 		if (sector_nr + RESYNC_BLOCK_SIZE/512 < last)
4293 			sector_nr = last + 1 - RESYNC_BLOCK_SIZE/512;
4294 	} else {
4295 		/* 'next' is after the last device address that we
4296 		 * might write to for this chunk in the new layout
4297 		 */
4298 		next = last_dev_address(conf->reshape_progress, &conf->geo);
4299 
4300 		/* 'safe' is the earliest device address that we might
4301 		 * read from in the old layout after a restart
4302 		 */
4303 		safe = first_dev_address(conf->reshape_safe, &conf->prev);
4304 
4305 		/* Need to update metadata if 'next' might be beyond 'safe'
4306 		 * as that would possibly corrupt data
4307 		 */
4308 		if (next > safe + conf->offset_diff)
4309 			need_flush = 1;
4310 
4311 		sector_nr = conf->reshape_progress;
4312 		last  = sector_nr | (conf->geo.chunk_mask
4313 				     & conf->prev.chunk_mask);
4314 
4315 		if (sector_nr + RESYNC_BLOCK_SIZE/512 <= last)
4316 			last = sector_nr + RESYNC_BLOCK_SIZE/512 - 1;
4317 	}
4318 
4319 	if (need_flush ||
4320 	    time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
4321 		/* Need to update reshape_position in metadata */
4322 		wait_barrier(conf);
4323 		mddev->reshape_position = conf->reshape_progress;
4324 		if (mddev->reshape_backwards)
4325 			mddev->curr_resync_completed = raid10_size(mddev, 0, 0)
4326 				- conf->reshape_progress;
4327 		else
4328 			mddev->curr_resync_completed = conf->reshape_progress;
4329 		conf->reshape_checkpoint = jiffies;
4330 		set_bit(MD_CHANGE_DEVS, &mddev->flags);
4331 		md_wakeup_thread(mddev->thread);
4332 		wait_event(mddev->sb_wait, mddev->flags == 0 ||
4333 			   test_bit(MD_RECOVERY_INTR, &mddev->recovery));
4334 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
4335 			allow_barrier(conf);
4336 			return sectors_done;
4337 		}
4338 		conf->reshape_safe = mddev->reshape_position;
4339 		allow_barrier(conf);
4340 	}
4341 
4342 	raise_barrier(conf, 0);
4343 read_more:
4344 	/* Now schedule reads for blocks from sector_nr to last */
4345 	r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
4346 	r10_bio->state = 0;
4347 	raise_barrier(conf, 1);
4348 	atomic_set(&r10_bio->remaining, 0);
4349 	r10_bio->mddev = mddev;
4350 	r10_bio->sector = sector_nr;
4351 	set_bit(R10BIO_IsReshape, &r10_bio->state);
4352 	r10_bio->sectors = last - sector_nr + 1;
4353 	rdev = read_balance(conf, r10_bio, &max_sectors);
4354 	BUG_ON(!test_bit(R10BIO_Previous, &r10_bio->state));
4355 
4356 	if (!rdev) {
4357 		/* Cannot read from here, so need to record bad blocks
4358 		 * on all the target devices.
4359 		 */
4360 		// FIXME
4361 		mempool_free(r10_bio, conf->r10buf_pool);
4362 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4363 		return sectors_done;
4364 	}
4365 
4366 	read_bio = bio_alloc_mddev(GFP_KERNEL, RESYNC_PAGES, mddev);
4367 
4368 	read_bio->bi_bdev = rdev->bdev;
4369 	read_bio->bi_iter.bi_sector = (r10_bio->devs[r10_bio->read_slot].addr
4370 			       + rdev->data_offset);
4371 	read_bio->bi_private = r10_bio;
4372 	read_bio->bi_end_io = end_sync_read;
4373 	read_bio->bi_rw = READ;
4374 	read_bio->bi_flags &= (~0UL << BIO_RESET_BITS);
4375 	read_bio->bi_error = 0;
4376 	read_bio->bi_vcnt = 0;
4377 	read_bio->bi_iter.bi_size = 0;
4378 	r10_bio->master_bio = read_bio;
4379 	r10_bio->read_slot = r10_bio->devs[r10_bio->read_slot].devnum;
4380 
4381 	/* Now find the locations in the new layout */
4382 	__raid10_find_phys(&conf->geo, r10_bio);
4383 
4384 	blist = read_bio;
4385 	read_bio->bi_next = NULL;
4386 
4387 	for (s = 0; s < conf->copies*2; s++) {
4388 		struct bio *b;
4389 		int d = r10_bio->devs[s/2].devnum;
4390 		struct md_rdev *rdev2;
4391 		if (s&1) {
4392 			rdev2 = conf->mirrors[d].replacement;
4393 			b = r10_bio->devs[s/2].repl_bio;
4394 		} else {
4395 			rdev2 = conf->mirrors[d].rdev;
4396 			b = r10_bio->devs[s/2].bio;
4397 		}
4398 		if (!rdev2 || test_bit(Faulty, &rdev2->flags))
4399 			continue;
4400 
4401 		bio_reset(b);
4402 		b->bi_bdev = rdev2->bdev;
4403 		b->bi_iter.bi_sector = r10_bio->devs[s/2].addr +
4404 			rdev2->new_data_offset;
4405 		b->bi_private = r10_bio;
4406 		b->bi_end_io = end_reshape_write;
4407 		b->bi_rw = WRITE;
4408 		b->bi_next = blist;
4409 		blist = b;
4410 	}
4411 
4412 	/* Now add as many pages as possible to all of these bios. */
4413 
4414 	nr_sectors = 0;
4415 	for (s = 0 ; s < max_sectors; s += PAGE_SIZE >> 9) {
4416 		struct page *page = r10_bio->devs[0].bio->bi_io_vec[s/(PAGE_SIZE>>9)].bv_page;
4417 		int len = (max_sectors - s) << 9;
4418 		if (len > PAGE_SIZE)
4419 			len = PAGE_SIZE;
4420 		for (bio = blist; bio ; bio = bio->bi_next) {
4421 			struct bio *bio2;
4422 			if (bio_add_page(bio, page, len, 0))
4423 				continue;
4424 
4425 			/* Didn't fit, must stop */
4426 			for (bio2 = blist;
4427 			     bio2 && bio2 != bio;
4428 			     bio2 = bio2->bi_next) {
4429 				/* Remove last page from this bio */
4430 				bio2->bi_vcnt--;
4431 				bio2->bi_iter.bi_size -= len;
4432 				bio_clear_flag(bio2, BIO_SEG_VALID);
4433 			}
4434 			goto bio_full;
4435 		}
4436 		sector_nr += len >> 9;
4437 		nr_sectors += len >> 9;
4438 	}
4439 bio_full:
4440 	r10_bio->sectors = nr_sectors;
4441 
4442 	/* Now submit the read */
4443 	md_sync_acct(read_bio->bi_bdev, r10_bio->sectors);
4444 	atomic_inc(&r10_bio->remaining);
4445 	read_bio->bi_next = NULL;
4446 	generic_make_request(read_bio);
4447 	sectors_done += nr_sectors;
4448 	if (sector_nr <= last)
4449 		goto read_more;
4450 
4451 	lower_barrier(conf);
4452 
4453 	/* Now that we have done the whole section we can
4454 	 * update reshape_progress
4455 	 */
4456 	if (mddev->reshape_backwards)
4457 		conf->reshape_progress -= sectors_done;
4458 	else
4459 		conf->reshape_progress += sectors_done;
4460 
4461 	return sectors_done;
4462 }
4463 
4464 static void end_reshape_request(struct r10bio *r10_bio);
4465 static int handle_reshape_read_error(struct mddev *mddev,
4466 				     struct r10bio *r10_bio);
reshape_request_write(struct mddev * mddev,struct r10bio * r10_bio)4467 static void reshape_request_write(struct mddev *mddev, struct r10bio *r10_bio)
4468 {
4469 	/* Reshape read completed.  Hopefully we have a block
4470 	 * to write out.
4471 	 * If we got a read error then we do sync 1-page reads from
4472 	 * elsewhere until we find the data - or give up.
4473 	 */
4474 	struct r10conf *conf = mddev->private;
4475 	int s;
4476 
4477 	if (!test_bit(R10BIO_Uptodate, &r10_bio->state))
4478 		if (handle_reshape_read_error(mddev, r10_bio) < 0) {
4479 			/* Reshape has been aborted */
4480 			md_done_sync(mddev, r10_bio->sectors, 0);
4481 			return;
4482 		}
4483 
4484 	/* We definitely have the data in the pages, schedule the
4485 	 * writes.
4486 	 */
4487 	atomic_set(&r10_bio->remaining, 1);
4488 	for (s = 0; s < conf->copies*2; s++) {
4489 		struct bio *b;
4490 		int d = r10_bio->devs[s/2].devnum;
4491 		struct md_rdev *rdev;
4492 		if (s&1) {
4493 			rdev = conf->mirrors[d].replacement;
4494 			b = r10_bio->devs[s/2].repl_bio;
4495 		} else {
4496 			rdev = conf->mirrors[d].rdev;
4497 			b = r10_bio->devs[s/2].bio;
4498 		}
4499 		if (!rdev || test_bit(Faulty, &rdev->flags))
4500 			continue;
4501 		atomic_inc(&rdev->nr_pending);
4502 		md_sync_acct(b->bi_bdev, r10_bio->sectors);
4503 		atomic_inc(&r10_bio->remaining);
4504 		b->bi_next = NULL;
4505 		generic_make_request(b);
4506 	}
4507 	end_reshape_request(r10_bio);
4508 }
4509 
end_reshape(struct r10conf * conf)4510 static void end_reshape(struct r10conf *conf)
4511 {
4512 	if (test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery))
4513 		return;
4514 
4515 	spin_lock_irq(&conf->device_lock);
4516 	conf->prev = conf->geo;
4517 	md_finish_reshape(conf->mddev);
4518 	smp_wmb();
4519 	conf->reshape_progress = MaxSector;
4520 	conf->reshape_safe = MaxSector;
4521 	spin_unlock_irq(&conf->device_lock);
4522 
4523 	/* read-ahead size must cover two whole stripes, which is
4524 	 * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
4525 	 */
4526 	if (conf->mddev->queue) {
4527 		int stripe = conf->geo.raid_disks *
4528 			((conf->mddev->chunk_sectors << 9) / PAGE_SIZE);
4529 		stripe /= conf->geo.near_copies;
4530 		if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
4531 			conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
4532 	}
4533 	conf->fullsync = 0;
4534 }
4535 
handle_reshape_read_error(struct mddev * mddev,struct r10bio * r10_bio)4536 static int handle_reshape_read_error(struct mddev *mddev,
4537 				     struct r10bio *r10_bio)
4538 {
4539 	/* Use sync reads to get the blocks from somewhere else */
4540 	int sectors = r10_bio->sectors;
4541 	struct r10conf *conf = mddev->private;
4542 	struct {
4543 		struct r10bio r10_bio;
4544 		struct r10dev devs[conf->copies];
4545 	} on_stack;
4546 	struct r10bio *r10b = &on_stack.r10_bio;
4547 	int slot = 0;
4548 	int idx = 0;
4549 	struct bio_vec *bvec = r10_bio->master_bio->bi_io_vec;
4550 
4551 	r10b->sector = r10_bio->sector;
4552 	__raid10_find_phys(&conf->prev, r10b);
4553 
4554 	while (sectors) {
4555 		int s = sectors;
4556 		int success = 0;
4557 		int first_slot = slot;
4558 
4559 		if (s > (PAGE_SIZE >> 9))
4560 			s = PAGE_SIZE >> 9;
4561 
4562 		while (!success) {
4563 			int d = r10b->devs[slot].devnum;
4564 			struct md_rdev *rdev = conf->mirrors[d].rdev;
4565 			sector_t addr;
4566 			if (rdev == NULL ||
4567 			    test_bit(Faulty, &rdev->flags) ||
4568 			    !test_bit(In_sync, &rdev->flags))
4569 				goto failed;
4570 
4571 			addr = r10b->devs[slot].addr + idx * PAGE_SIZE;
4572 			success = sync_page_io(rdev,
4573 					       addr,
4574 					       s << 9,
4575 					       bvec[idx].bv_page,
4576 					       READ, false);
4577 			if (success)
4578 				break;
4579 		failed:
4580 			slot++;
4581 			if (slot >= conf->copies)
4582 				slot = 0;
4583 			if (slot == first_slot)
4584 				break;
4585 		}
4586 		if (!success) {
4587 			/* couldn't read this block, must give up */
4588 			set_bit(MD_RECOVERY_INTR,
4589 				&mddev->recovery);
4590 			return -EIO;
4591 		}
4592 		sectors -= s;
4593 		idx++;
4594 	}
4595 	return 0;
4596 }
4597 
end_reshape_write(struct bio * bio)4598 static void end_reshape_write(struct bio *bio)
4599 {
4600 	struct r10bio *r10_bio = bio->bi_private;
4601 	struct mddev *mddev = r10_bio->mddev;
4602 	struct r10conf *conf = mddev->private;
4603 	int d;
4604 	int slot;
4605 	int repl;
4606 	struct md_rdev *rdev = NULL;
4607 
4608 	d = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
4609 	if (repl)
4610 		rdev = conf->mirrors[d].replacement;
4611 	if (!rdev) {
4612 		smp_mb();
4613 		rdev = conf->mirrors[d].rdev;
4614 	}
4615 
4616 	if (bio->bi_error) {
4617 		/* FIXME should record badblock */
4618 		md_error(mddev, rdev);
4619 	}
4620 
4621 	rdev_dec_pending(rdev, mddev);
4622 	end_reshape_request(r10_bio);
4623 }
4624 
end_reshape_request(struct r10bio * r10_bio)4625 static void end_reshape_request(struct r10bio *r10_bio)
4626 {
4627 	if (!atomic_dec_and_test(&r10_bio->remaining))
4628 		return;
4629 	md_done_sync(r10_bio->mddev, r10_bio->sectors, 1);
4630 	bio_put(r10_bio->master_bio);
4631 	put_buf(r10_bio);
4632 }
4633 
raid10_finish_reshape(struct mddev * mddev)4634 static void raid10_finish_reshape(struct mddev *mddev)
4635 {
4636 	struct r10conf *conf = mddev->private;
4637 
4638 	if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
4639 		return;
4640 
4641 	if (mddev->delta_disks > 0) {
4642 		sector_t size = raid10_size(mddev, 0, 0);
4643 		md_set_array_sectors(mddev, size);
4644 		if (mddev->recovery_cp > mddev->resync_max_sectors) {
4645 			mddev->recovery_cp = mddev->resync_max_sectors;
4646 			set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4647 		}
4648 		mddev->resync_max_sectors = size;
4649 		set_capacity(mddev->gendisk, mddev->array_sectors);
4650 		revalidate_disk(mddev->gendisk);
4651 	} else {
4652 		int d;
4653 		for (d = conf->geo.raid_disks ;
4654 		     d < conf->geo.raid_disks - mddev->delta_disks;
4655 		     d++) {
4656 			struct md_rdev *rdev = conf->mirrors[d].rdev;
4657 			if (rdev)
4658 				clear_bit(In_sync, &rdev->flags);
4659 			rdev = conf->mirrors[d].replacement;
4660 			if (rdev)
4661 				clear_bit(In_sync, &rdev->flags);
4662 		}
4663 	}
4664 	mddev->layout = mddev->new_layout;
4665 	mddev->chunk_sectors = 1 << conf->geo.chunk_shift;
4666 	mddev->reshape_position = MaxSector;
4667 	mddev->delta_disks = 0;
4668 	mddev->reshape_backwards = 0;
4669 }
4670 
4671 static struct md_personality raid10_personality =
4672 {
4673 	.name		= "raid10",
4674 	.level		= 10,
4675 	.owner		= THIS_MODULE,
4676 	.make_request	= make_request,
4677 	.run		= run,
4678 	.free		= raid10_free,
4679 	.status		= status,
4680 	.error_handler	= error,
4681 	.hot_add_disk	= raid10_add_disk,
4682 	.hot_remove_disk= raid10_remove_disk,
4683 	.spare_active	= raid10_spare_active,
4684 	.sync_request	= sync_request,
4685 	.quiesce	= raid10_quiesce,
4686 	.size		= raid10_size,
4687 	.resize		= raid10_resize,
4688 	.takeover	= raid10_takeover,
4689 	.check_reshape	= raid10_check_reshape,
4690 	.start_reshape	= raid10_start_reshape,
4691 	.finish_reshape	= raid10_finish_reshape,
4692 	.congested	= raid10_congested,
4693 };
4694 
raid_init(void)4695 static int __init raid_init(void)
4696 {
4697 	return register_md_personality(&raid10_personality);
4698 }
4699 
raid_exit(void)4700 static void raid_exit(void)
4701 {
4702 	unregister_md_personality(&raid10_personality);
4703 }
4704 
4705 module_init(raid_init);
4706 module_exit(raid_exit);
4707 MODULE_LICENSE("GPL");
4708 MODULE_DESCRIPTION("RAID10 (striped mirror) personality for MD");
4709 MODULE_ALIAS("md-personality-9"); /* RAID10 */
4710 MODULE_ALIAS("md-raid10");
4711 MODULE_ALIAS("md-level-10");
4712 
4713 module_param(max_queued_requests, int, S_IRUGO|S_IWUSR);
4714