xref: /openbmc/linux/drivers/md/dm-raid.c (revision 7490ca1e)
1 /*
2  * Copyright (C) 2010-2011 Neil Brown
3  * Copyright (C) 2010-2011 Red Hat, Inc. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7 
8 #include <linux/slab.h>
9 #include <linux/module.h>
10 
11 #include "md.h"
12 #include "raid1.h"
13 #include "raid5.h"
14 #include "bitmap.h"
15 
16 #include <linux/device-mapper.h>
17 
18 #define DM_MSG_PREFIX "raid"
19 
20 /*
21  * The following flags are used by dm-raid.c to set up the array state.
22  * They must be cleared before md_run is called.
23  */
24 #define FirstUse 10             /* rdev flag */
25 
26 struct raid_dev {
27 	/*
28 	 * Two DM devices, one to hold metadata and one to hold the
29 	 * actual data/parity.  The reason for this is to not confuse
30 	 * ti->len and give more flexibility in altering size and
31 	 * characteristics.
32 	 *
33 	 * While it is possible for this device to be associated
34 	 * with a different physical device than the data_dev, it
35 	 * is intended for it to be the same.
36 	 *    |--------- Physical Device ---------|
37 	 *    |- meta_dev -|------ data_dev ------|
38 	 */
39 	struct dm_dev *meta_dev;
40 	struct dm_dev *data_dev;
41 	struct md_rdev rdev;
42 };
43 
44 /*
45  * Flags for rs->print_flags field.
46  */
47 #define DMPF_SYNC              0x1
48 #define DMPF_NOSYNC            0x2
49 #define DMPF_REBUILD           0x4
50 #define DMPF_DAEMON_SLEEP      0x8
51 #define DMPF_MIN_RECOVERY_RATE 0x10
52 #define DMPF_MAX_RECOVERY_RATE 0x20
53 #define DMPF_MAX_WRITE_BEHIND  0x40
54 #define DMPF_STRIPE_CACHE      0x80
55 #define DMPF_REGION_SIZE       0X100
56 struct raid_set {
57 	struct dm_target *ti;
58 
59 	uint32_t bitmap_loaded;
60 	uint32_t print_flags;
61 
62 	struct mddev md;
63 	struct raid_type *raid_type;
64 	struct dm_target_callbacks callbacks;
65 
66 	struct raid_dev dev[0];
67 };
68 
69 /* Supported raid types and properties. */
70 static struct raid_type {
71 	const char *name;		/* RAID algorithm. */
72 	const char *descr;		/* Descriptor text for logging. */
73 	const unsigned parity_devs;	/* # of parity devices. */
74 	const unsigned minimal_devs;	/* minimal # of devices in set. */
75 	const unsigned level;		/* RAID level. */
76 	const unsigned algorithm;	/* RAID algorithm. */
77 } raid_types[] = {
78 	{"raid1",    "RAID1 (mirroring)",               0, 2, 1, 0 /* NONE */},
79 	{"raid4",    "RAID4 (dedicated parity disk)",	1, 2, 5, ALGORITHM_PARITY_0},
80 	{"raid5_la", "RAID5 (left asymmetric)",		1, 2, 5, ALGORITHM_LEFT_ASYMMETRIC},
81 	{"raid5_ra", "RAID5 (right asymmetric)",	1, 2, 5, ALGORITHM_RIGHT_ASYMMETRIC},
82 	{"raid5_ls", "RAID5 (left symmetric)",		1, 2, 5, ALGORITHM_LEFT_SYMMETRIC},
83 	{"raid5_rs", "RAID5 (right symmetric)",		1, 2, 5, ALGORITHM_RIGHT_SYMMETRIC},
84 	{"raid6_zr", "RAID6 (zero restart)",		2, 4, 6, ALGORITHM_ROTATING_ZERO_RESTART},
85 	{"raid6_nr", "RAID6 (N restart)",		2, 4, 6, ALGORITHM_ROTATING_N_RESTART},
86 	{"raid6_nc", "RAID6 (N continue)",		2, 4, 6, ALGORITHM_ROTATING_N_CONTINUE}
87 };
88 
89 static struct raid_type *get_raid_type(char *name)
90 {
91 	int i;
92 
93 	for (i = 0; i < ARRAY_SIZE(raid_types); i++)
94 		if (!strcmp(raid_types[i].name, name))
95 			return &raid_types[i];
96 
97 	return NULL;
98 }
99 
100 static struct raid_set *context_alloc(struct dm_target *ti, struct raid_type *raid_type, unsigned raid_devs)
101 {
102 	unsigned i;
103 	struct raid_set *rs;
104 	sector_t sectors_per_dev;
105 
106 	if (raid_devs <= raid_type->parity_devs) {
107 		ti->error = "Insufficient number of devices";
108 		return ERR_PTR(-EINVAL);
109 	}
110 
111 	sectors_per_dev = ti->len;
112 	if ((raid_type->level > 1) &&
113 	    sector_div(sectors_per_dev, (raid_devs - raid_type->parity_devs))) {
114 		ti->error = "Target length not divisible by number of data devices";
115 		return ERR_PTR(-EINVAL);
116 	}
117 
118 	rs = kzalloc(sizeof(*rs) + raid_devs * sizeof(rs->dev[0]), GFP_KERNEL);
119 	if (!rs) {
120 		ti->error = "Cannot allocate raid context";
121 		return ERR_PTR(-ENOMEM);
122 	}
123 
124 	mddev_init(&rs->md);
125 
126 	rs->ti = ti;
127 	rs->raid_type = raid_type;
128 	rs->md.raid_disks = raid_devs;
129 	rs->md.level = raid_type->level;
130 	rs->md.new_level = rs->md.level;
131 	rs->md.dev_sectors = sectors_per_dev;
132 	rs->md.layout = raid_type->algorithm;
133 	rs->md.new_layout = rs->md.layout;
134 	rs->md.delta_disks = 0;
135 	rs->md.recovery_cp = 0;
136 
137 	for (i = 0; i < raid_devs; i++)
138 		md_rdev_init(&rs->dev[i].rdev);
139 
140 	/*
141 	 * Remaining items to be initialized by further RAID params:
142 	 *  rs->md.persistent
143 	 *  rs->md.external
144 	 *  rs->md.chunk_sectors
145 	 *  rs->md.new_chunk_sectors
146 	 */
147 
148 	return rs;
149 }
150 
151 static void context_free(struct raid_set *rs)
152 {
153 	int i;
154 
155 	for (i = 0; i < rs->md.raid_disks; i++) {
156 		if (rs->dev[i].meta_dev)
157 			dm_put_device(rs->ti, rs->dev[i].meta_dev);
158 		if (rs->dev[i].rdev.sb_page)
159 			put_page(rs->dev[i].rdev.sb_page);
160 		rs->dev[i].rdev.sb_page = NULL;
161 		rs->dev[i].rdev.sb_loaded = 0;
162 		if (rs->dev[i].data_dev)
163 			dm_put_device(rs->ti, rs->dev[i].data_dev);
164 	}
165 
166 	kfree(rs);
167 }
168 
169 /*
170  * For every device we have two words
171  *  <meta_dev>: meta device name or '-' if missing
172  *  <data_dev>: data device name or '-' if missing
173  *
174  * The following are permitted:
175  *    - -
176  *    - <data_dev>
177  *    <meta_dev> <data_dev>
178  *
179  * The following is not allowed:
180  *    <meta_dev> -
181  *
182  * This code parses those words.  If there is a failure,
183  * the caller must use context_free to unwind the operations.
184  */
185 static int dev_parms(struct raid_set *rs, char **argv)
186 {
187 	int i;
188 	int rebuild = 0;
189 	int metadata_available = 0;
190 	int ret = 0;
191 
192 	for (i = 0; i < rs->md.raid_disks; i++, argv += 2) {
193 		rs->dev[i].rdev.raid_disk = i;
194 
195 		rs->dev[i].meta_dev = NULL;
196 		rs->dev[i].data_dev = NULL;
197 
198 		/*
199 		 * There are no offsets, since there is a separate device
200 		 * for data and metadata.
201 		 */
202 		rs->dev[i].rdev.data_offset = 0;
203 		rs->dev[i].rdev.mddev = &rs->md;
204 
205 		if (strcmp(argv[0], "-")) {
206 			ret = dm_get_device(rs->ti, argv[0],
207 					    dm_table_get_mode(rs->ti->table),
208 					    &rs->dev[i].meta_dev);
209 			rs->ti->error = "RAID metadata device lookup failure";
210 			if (ret)
211 				return ret;
212 
213 			rs->dev[i].rdev.sb_page = alloc_page(GFP_KERNEL);
214 			if (!rs->dev[i].rdev.sb_page)
215 				return -ENOMEM;
216 		}
217 
218 		if (!strcmp(argv[1], "-")) {
219 			if (!test_bit(In_sync, &rs->dev[i].rdev.flags) &&
220 			    (!rs->dev[i].rdev.recovery_offset)) {
221 				rs->ti->error = "Drive designated for rebuild not specified";
222 				return -EINVAL;
223 			}
224 
225 			rs->ti->error = "No data device supplied with metadata device";
226 			if (rs->dev[i].meta_dev)
227 				return -EINVAL;
228 
229 			continue;
230 		}
231 
232 		ret = dm_get_device(rs->ti, argv[1],
233 				    dm_table_get_mode(rs->ti->table),
234 				    &rs->dev[i].data_dev);
235 		if (ret) {
236 			rs->ti->error = "RAID device lookup failure";
237 			return ret;
238 		}
239 
240 		if (rs->dev[i].meta_dev) {
241 			metadata_available = 1;
242 			rs->dev[i].rdev.meta_bdev = rs->dev[i].meta_dev->bdev;
243 		}
244 		rs->dev[i].rdev.bdev = rs->dev[i].data_dev->bdev;
245 		list_add(&rs->dev[i].rdev.same_set, &rs->md.disks);
246 		if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
247 			rebuild++;
248 	}
249 
250 	if (metadata_available) {
251 		rs->md.external = 0;
252 		rs->md.persistent = 1;
253 		rs->md.major_version = 2;
254 	} else if (rebuild && !rs->md.recovery_cp) {
255 		/*
256 		 * Without metadata, we will not be able to tell if the array
257 		 * is in-sync or not - we must assume it is not.  Therefore,
258 		 * it is impossible to rebuild a drive.
259 		 *
260 		 * Even if there is metadata, the on-disk information may
261 		 * indicate that the array is not in-sync and it will then
262 		 * fail at that time.
263 		 *
264 		 * User could specify 'nosync' option if desperate.
265 		 */
266 		DMERR("Unable to rebuild drive while array is not in-sync");
267 		rs->ti->error = "RAID device lookup failure";
268 		return -EINVAL;
269 	}
270 
271 	return 0;
272 }
273 
274 /*
275  * validate_region_size
276  * @rs
277  * @region_size:  region size in sectors.  If 0, pick a size (4MiB default).
278  *
279  * Set rs->md.bitmap_info.chunksize (which really refers to 'region size').
280  * Ensure that (ti->len/region_size < 2^21) - required by MD bitmap.
281  *
282  * Returns: 0 on success, -EINVAL on failure.
283  */
284 static int validate_region_size(struct raid_set *rs, unsigned long region_size)
285 {
286 	unsigned long min_region_size = rs->ti->len / (1 << 21);
287 
288 	if (!region_size) {
289 		/*
290 		 * Choose a reasonable default.  All figures in sectors.
291 		 */
292 		if (min_region_size > (1 << 13)) {
293 			DMINFO("Choosing default region size of %lu sectors",
294 			       region_size);
295 			region_size = min_region_size;
296 		} else {
297 			DMINFO("Choosing default region size of 4MiB");
298 			region_size = 1 << 13; /* sectors */
299 		}
300 	} else {
301 		/*
302 		 * Validate user-supplied value.
303 		 */
304 		if (region_size > rs->ti->len) {
305 			rs->ti->error = "Supplied region size is too large";
306 			return -EINVAL;
307 		}
308 
309 		if (region_size < min_region_size) {
310 			DMERR("Supplied region_size (%lu sectors) below minimum (%lu)",
311 			      region_size, min_region_size);
312 			rs->ti->error = "Supplied region size is too small";
313 			return -EINVAL;
314 		}
315 
316 		if (!is_power_of_2(region_size)) {
317 			rs->ti->error = "Region size is not a power of 2";
318 			return -EINVAL;
319 		}
320 
321 		if (region_size < rs->md.chunk_sectors) {
322 			rs->ti->error = "Region size is smaller than the chunk size";
323 			return -EINVAL;
324 		}
325 	}
326 
327 	/*
328 	 * Convert sectors to bytes.
329 	 */
330 	rs->md.bitmap_info.chunksize = (region_size << 9);
331 
332 	return 0;
333 }
334 
335 /*
336  * Possible arguments are...
337  *	<chunk_size> [optional_args]
338  *
339  * Argument definitions
340  *    <chunk_size>			The number of sectors per disk that
341  *                                      will form the "stripe"
342  *    [[no]sync]			Force or prevent recovery of the
343  *                                      entire array
344  *    [rebuild <idx>]			Rebuild the drive indicated by the index
345  *    [daemon_sleep <ms>]		Time between bitmap daemon work to
346  *                                      clear bits
347  *    [min_recovery_rate <kB/sec/disk>]	Throttle RAID initialization
348  *    [max_recovery_rate <kB/sec/disk>]	Throttle RAID initialization
349  *    [write_mostly <idx>]		Indicate a write mostly drive via index
350  *    [max_write_behind <sectors>]	See '-write-behind=' (man mdadm)
351  *    [stripe_cache <sectors>]		Stripe cache size for higher RAIDs
352  *    [region_size <sectors>]           Defines granularity of bitmap
353  */
354 static int parse_raid_params(struct raid_set *rs, char **argv,
355 			     unsigned num_raid_params)
356 {
357 	unsigned i, rebuild_cnt = 0;
358 	unsigned long value, region_size = 0;
359 	char *key;
360 
361 	/*
362 	 * First, parse the in-order required arguments
363 	 * "chunk_size" is the only argument of this type.
364 	 */
365 	if ((strict_strtoul(argv[0], 10, &value) < 0)) {
366 		rs->ti->error = "Bad chunk size";
367 		return -EINVAL;
368 	} else if (rs->raid_type->level == 1) {
369 		if (value)
370 			DMERR("Ignoring chunk size parameter for RAID 1");
371 		value = 0;
372 	} else if (!is_power_of_2(value)) {
373 		rs->ti->error = "Chunk size must be a power of 2";
374 		return -EINVAL;
375 	} else if (value < 8) {
376 		rs->ti->error = "Chunk size value is too small";
377 		return -EINVAL;
378 	}
379 
380 	rs->md.new_chunk_sectors = rs->md.chunk_sectors = value;
381 	argv++;
382 	num_raid_params--;
383 
384 	/*
385 	 * We set each individual device as In_sync with a completed
386 	 * 'recovery_offset'.  If there has been a device failure or
387 	 * replacement then one of the following cases applies:
388 	 *
389 	 *   1) User specifies 'rebuild'.
390 	 *      - Device is reset when param is read.
391 	 *   2) A new device is supplied.
392 	 *      - No matching superblock found, resets device.
393 	 *   3) Device failure was transient and returns on reload.
394 	 *      - Failure noticed, resets device for bitmap replay.
395 	 *   4) Device hadn't completed recovery after previous failure.
396 	 *      - Superblock is read and overrides recovery_offset.
397 	 *
398 	 * What is found in the superblocks of the devices is always
399 	 * authoritative, unless 'rebuild' or '[no]sync' was specified.
400 	 */
401 	for (i = 0; i < rs->md.raid_disks; i++) {
402 		set_bit(In_sync, &rs->dev[i].rdev.flags);
403 		rs->dev[i].rdev.recovery_offset = MaxSector;
404 	}
405 
406 	/*
407 	 * Second, parse the unordered optional arguments
408 	 */
409 	for (i = 0; i < num_raid_params; i++) {
410 		if (!strcasecmp(argv[i], "nosync")) {
411 			rs->md.recovery_cp = MaxSector;
412 			rs->print_flags |= DMPF_NOSYNC;
413 			continue;
414 		}
415 		if (!strcasecmp(argv[i], "sync")) {
416 			rs->md.recovery_cp = 0;
417 			rs->print_flags |= DMPF_SYNC;
418 			continue;
419 		}
420 
421 		/* The rest of the optional arguments come in key/value pairs */
422 		if ((i + 1) >= num_raid_params) {
423 			rs->ti->error = "Wrong number of raid parameters given";
424 			return -EINVAL;
425 		}
426 
427 		key = argv[i++];
428 		if (strict_strtoul(argv[i], 10, &value) < 0) {
429 			rs->ti->error = "Bad numerical argument given in raid params";
430 			return -EINVAL;
431 		}
432 
433 		if (!strcasecmp(key, "rebuild")) {
434 			rebuild_cnt++;
435 			if (((rs->raid_type->level != 1) &&
436 			     (rebuild_cnt > rs->raid_type->parity_devs)) ||
437 			    ((rs->raid_type->level == 1) &&
438 			     (rebuild_cnt > (rs->md.raid_disks - 1)))) {
439 				rs->ti->error = "Too many rebuild devices specified for given RAID type";
440 				return -EINVAL;
441 			}
442 			if (value > rs->md.raid_disks) {
443 				rs->ti->error = "Invalid rebuild index given";
444 				return -EINVAL;
445 			}
446 			clear_bit(In_sync, &rs->dev[value].rdev.flags);
447 			rs->dev[value].rdev.recovery_offset = 0;
448 			rs->print_flags |= DMPF_REBUILD;
449 		} else if (!strcasecmp(key, "write_mostly")) {
450 			if (rs->raid_type->level != 1) {
451 				rs->ti->error = "write_mostly option is only valid for RAID1";
452 				return -EINVAL;
453 			}
454 			if (value >= rs->md.raid_disks) {
455 				rs->ti->error = "Invalid write_mostly drive index given";
456 				return -EINVAL;
457 			}
458 			set_bit(WriteMostly, &rs->dev[value].rdev.flags);
459 		} else if (!strcasecmp(key, "max_write_behind")) {
460 			if (rs->raid_type->level != 1) {
461 				rs->ti->error = "max_write_behind option is only valid for RAID1";
462 				return -EINVAL;
463 			}
464 			rs->print_flags |= DMPF_MAX_WRITE_BEHIND;
465 
466 			/*
467 			 * In device-mapper, we specify things in sectors, but
468 			 * MD records this value in kB
469 			 */
470 			value /= 2;
471 			if (value > COUNTER_MAX) {
472 				rs->ti->error = "Max write-behind limit out of range";
473 				return -EINVAL;
474 			}
475 			rs->md.bitmap_info.max_write_behind = value;
476 		} else if (!strcasecmp(key, "daemon_sleep")) {
477 			rs->print_flags |= DMPF_DAEMON_SLEEP;
478 			if (!value || (value > MAX_SCHEDULE_TIMEOUT)) {
479 				rs->ti->error = "daemon sleep period out of range";
480 				return -EINVAL;
481 			}
482 			rs->md.bitmap_info.daemon_sleep = value;
483 		} else if (!strcasecmp(key, "stripe_cache")) {
484 			rs->print_flags |= DMPF_STRIPE_CACHE;
485 
486 			/*
487 			 * In device-mapper, we specify things in sectors, but
488 			 * MD records this value in kB
489 			 */
490 			value /= 2;
491 
492 			if (rs->raid_type->level < 5) {
493 				rs->ti->error = "Inappropriate argument: stripe_cache";
494 				return -EINVAL;
495 			}
496 			if (raid5_set_cache_size(&rs->md, (int)value)) {
497 				rs->ti->error = "Bad stripe_cache size";
498 				return -EINVAL;
499 			}
500 		} else if (!strcasecmp(key, "min_recovery_rate")) {
501 			rs->print_flags |= DMPF_MIN_RECOVERY_RATE;
502 			if (value > INT_MAX) {
503 				rs->ti->error = "min_recovery_rate out of range";
504 				return -EINVAL;
505 			}
506 			rs->md.sync_speed_min = (int)value;
507 		} else if (!strcasecmp(key, "max_recovery_rate")) {
508 			rs->print_flags |= DMPF_MAX_RECOVERY_RATE;
509 			if (value > INT_MAX) {
510 				rs->ti->error = "max_recovery_rate out of range";
511 				return -EINVAL;
512 			}
513 			rs->md.sync_speed_max = (int)value;
514 		} else if (!strcasecmp(key, "region_size")) {
515 			rs->print_flags |= DMPF_REGION_SIZE;
516 			region_size = value;
517 		} else {
518 			DMERR("Unable to parse RAID parameter: %s", key);
519 			rs->ti->error = "Unable to parse RAID parameters";
520 			return -EINVAL;
521 		}
522 	}
523 
524 	if (validate_region_size(rs, region_size))
525 		return -EINVAL;
526 
527 	if (rs->md.chunk_sectors)
528 		rs->ti->split_io = rs->md.chunk_sectors;
529 	else
530 		rs->ti->split_io = region_size;
531 
532 	if (rs->md.chunk_sectors)
533 		rs->ti->split_io = rs->md.chunk_sectors;
534 	else
535 		rs->ti->split_io = region_size;
536 
537 	/* Assume there are no metadata devices until the drives are parsed */
538 	rs->md.persistent = 0;
539 	rs->md.external = 1;
540 
541 	return 0;
542 }
543 
544 static void do_table_event(struct work_struct *ws)
545 {
546 	struct raid_set *rs = container_of(ws, struct raid_set, md.event_work);
547 
548 	dm_table_event(rs->ti->table);
549 }
550 
551 static int raid_is_congested(struct dm_target_callbacks *cb, int bits)
552 {
553 	struct raid_set *rs = container_of(cb, struct raid_set, callbacks);
554 
555 	if (rs->raid_type->level == 1)
556 		return md_raid1_congested(&rs->md, bits);
557 
558 	return md_raid5_congested(&rs->md, bits);
559 }
560 
561 /*
562  * This structure is never routinely used by userspace, unlike md superblocks.
563  * Devices with this superblock should only ever be accessed via device-mapper.
564  */
565 #define DM_RAID_MAGIC 0x64526D44
566 struct dm_raid_superblock {
567 	__le32 magic;		/* "DmRd" */
568 	__le32 features;	/* Used to indicate possible future changes */
569 
570 	__le32 num_devices;	/* Number of devices in this array. (Max 64) */
571 	__le32 array_position;	/* The position of this drive in the array */
572 
573 	__le64 events;		/* Incremented by md when superblock updated */
574 	__le64 failed_devices;	/* Bit field of devices to indicate failures */
575 
576 	/*
577 	 * This offset tracks the progress of the repair or replacement of
578 	 * an individual drive.
579 	 */
580 	__le64 disk_recovery_offset;
581 
582 	/*
583 	 * This offset tracks the progress of the initial array
584 	 * synchronisation/parity calculation.
585 	 */
586 	__le64 array_resync_offset;
587 
588 	/*
589 	 * RAID characteristics
590 	 */
591 	__le32 level;
592 	__le32 layout;
593 	__le32 stripe_sectors;
594 
595 	__u8 pad[452];		/* Round struct to 512 bytes. */
596 				/* Always set to 0 when writing. */
597 } __packed;
598 
599 static int read_disk_sb(struct md_rdev *rdev, int size)
600 {
601 	BUG_ON(!rdev->sb_page);
602 
603 	if (rdev->sb_loaded)
604 		return 0;
605 
606 	if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, 1)) {
607 		DMERR("Failed to read device superblock");
608 		return -EINVAL;
609 	}
610 
611 	rdev->sb_loaded = 1;
612 
613 	return 0;
614 }
615 
616 static void super_sync(struct mddev *mddev, struct md_rdev *rdev)
617 {
618 	struct md_rdev *r, *t;
619 	uint64_t failed_devices;
620 	struct dm_raid_superblock *sb;
621 
622 	sb = page_address(rdev->sb_page);
623 	failed_devices = le64_to_cpu(sb->failed_devices);
624 
625 	rdev_for_each(r, t, mddev)
626 		if ((r->raid_disk >= 0) && test_bit(Faulty, &r->flags))
627 			failed_devices |= (1ULL << r->raid_disk);
628 
629 	memset(sb, 0, sizeof(*sb));
630 
631 	sb->magic = cpu_to_le32(DM_RAID_MAGIC);
632 	sb->features = cpu_to_le32(0);	/* No features yet */
633 
634 	sb->num_devices = cpu_to_le32(mddev->raid_disks);
635 	sb->array_position = cpu_to_le32(rdev->raid_disk);
636 
637 	sb->events = cpu_to_le64(mddev->events);
638 	sb->failed_devices = cpu_to_le64(failed_devices);
639 
640 	sb->disk_recovery_offset = cpu_to_le64(rdev->recovery_offset);
641 	sb->array_resync_offset = cpu_to_le64(mddev->recovery_cp);
642 
643 	sb->level = cpu_to_le32(mddev->level);
644 	sb->layout = cpu_to_le32(mddev->layout);
645 	sb->stripe_sectors = cpu_to_le32(mddev->chunk_sectors);
646 }
647 
648 /*
649  * super_load
650  *
651  * This function creates a superblock if one is not found on the device
652  * and will decide which superblock to use if there's a choice.
653  *
654  * Return: 1 if use rdev, 0 if use refdev, -Exxx otherwise
655  */
656 static int super_load(struct md_rdev *rdev, struct md_rdev *refdev)
657 {
658 	int ret;
659 	struct dm_raid_superblock *sb;
660 	struct dm_raid_superblock *refsb;
661 	uint64_t events_sb, events_refsb;
662 
663 	rdev->sb_start = 0;
664 	rdev->sb_size = sizeof(*sb);
665 
666 	ret = read_disk_sb(rdev, rdev->sb_size);
667 	if (ret)
668 		return ret;
669 
670 	sb = page_address(rdev->sb_page);
671 	if (sb->magic != cpu_to_le32(DM_RAID_MAGIC)) {
672 		super_sync(rdev->mddev, rdev);
673 
674 		set_bit(FirstUse, &rdev->flags);
675 
676 		/* Force writing of superblocks to disk */
677 		set_bit(MD_CHANGE_DEVS, &rdev->mddev->flags);
678 
679 		/* Any superblock is better than none, choose that if given */
680 		return refdev ? 0 : 1;
681 	}
682 
683 	if (!refdev)
684 		return 1;
685 
686 	events_sb = le64_to_cpu(sb->events);
687 
688 	refsb = page_address(refdev->sb_page);
689 	events_refsb = le64_to_cpu(refsb->events);
690 
691 	return (events_sb > events_refsb) ? 1 : 0;
692 }
693 
694 static int super_init_validation(struct mddev *mddev, struct md_rdev *rdev)
695 {
696 	int role;
697 	struct raid_set *rs = container_of(mddev, struct raid_set, md);
698 	uint64_t events_sb;
699 	uint64_t failed_devices;
700 	struct dm_raid_superblock *sb;
701 	uint32_t new_devs = 0;
702 	uint32_t rebuilds = 0;
703 	struct md_rdev *r, *t;
704 	struct dm_raid_superblock *sb2;
705 
706 	sb = page_address(rdev->sb_page);
707 	events_sb = le64_to_cpu(sb->events);
708 	failed_devices = le64_to_cpu(sb->failed_devices);
709 
710 	/*
711 	 * Initialise to 1 if this is a new superblock.
712 	 */
713 	mddev->events = events_sb ? : 1;
714 
715 	/*
716 	 * Reshaping is not currently allowed
717 	 */
718 	if ((le32_to_cpu(sb->level) != mddev->level) ||
719 	    (le32_to_cpu(sb->layout) != mddev->layout) ||
720 	    (le32_to_cpu(sb->stripe_sectors) != mddev->chunk_sectors)) {
721 		DMERR("Reshaping arrays not yet supported.");
722 		return -EINVAL;
723 	}
724 
725 	/* We can only change the number of devices in RAID1 right now */
726 	if ((rs->raid_type->level != 1) &&
727 	    (le32_to_cpu(sb->num_devices) != mddev->raid_disks)) {
728 		DMERR("Reshaping arrays not yet supported.");
729 		return -EINVAL;
730 	}
731 
732 	if (!(rs->print_flags & (DMPF_SYNC | DMPF_NOSYNC)))
733 		mddev->recovery_cp = le64_to_cpu(sb->array_resync_offset);
734 
735 	/*
736 	 * During load, we set FirstUse if a new superblock was written.
737 	 * There are two reasons we might not have a superblock:
738 	 * 1) The array is brand new - in which case, all of the
739 	 *    devices must have their In_sync bit set.  Also,
740 	 *    recovery_cp must be 0, unless forced.
741 	 * 2) This is a new device being added to an old array
742 	 *    and the new device needs to be rebuilt - in which
743 	 *    case the In_sync bit will /not/ be set and
744 	 *    recovery_cp must be MaxSector.
745 	 */
746 	rdev_for_each(r, t, mddev) {
747 		if (!test_bit(In_sync, &r->flags)) {
748 			if (!test_bit(FirstUse, &r->flags))
749 				DMERR("Superblock area of "
750 				      "rebuild device %d should have been "
751 				      "cleared.", r->raid_disk);
752 			set_bit(FirstUse, &r->flags);
753 			rebuilds++;
754 		} else if (test_bit(FirstUse, &r->flags))
755 			new_devs++;
756 	}
757 
758 	if (!rebuilds) {
759 		if (new_devs == mddev->raid_disks) {
760 			DMINFO("Superblocks created for new array");
761 			set_bit(MD_ARRAY_FIRST_USE, &mddev->flags);
762 		} else if (new_devs) {
763 			DMERR("New device injected "
764 			      "into existing array without 'rebuild' "
765 			      "parameter specified");
766 			return -EINVAL;
767 		}
768 	} else if (new_devs) {
769 		DMERR("'rebuild' devices cannot be "
770 		      "injected into an array with other first-time devices");
771 		return -EINVAL;
772 	} else if (mddev->recovery_cp != MaxSector) {
773 		DMERR("'rebuild' specified while array is not in-sync");
774 		return -EINVAL;
775 	}
776 
777 	/*
778 	 * Now we set the Faulty bit for those devices that are
779 	 * recorded in the superblock as failed.
780 	 */
781 	rdev_for_each(r, t, mddev) {
782 		if (!r->sb_page)
783 			continue;
784 		sb2 = page_address(r->sb_page);
785 		sb2->failed_devices = 0;
786 
787 		/*
788 		 * Check for any device re-ordering.
789 		 */
790 		if (!test_bit(FirstUse, &r->flags) && (r->raid_disk >= 0)) {
791 			role = le32_to_cpu(sb2->array_position);
792 			if (role != r->raid_disk) {
793 				if (rs->raid_type->level != 1) {
794 					rs->ti->error = "Cannot change device "
795 						"positions in RAID array";
796 					return -EINVAL;
797 				}
798 				DMINFO("RAID1 device #%d now at position #%d",
799 				       role, r->raid_disk);
800 			}
801 
802 			/*
803 			 * Partial recovery is performed on
804 			 * returning failed devices.
805 			 */
806 			if (failed_devices & (1 << role))
807 				set_bit(Faulty, &r->flags);
808 		}
809 	}
810 
811 	return 0;
812 }
813 
814 static int super_validate(struct mddev *mddev, struct md_rdev *rdev)
815 {
816 	struct dm_raid_superblock *sb = page_address(rdev->sb_page);
817 
818 	/*
819 	 * If mddev->events is not set, we know we have not yet initialized
820 	 * the array.
821 	 */
822 	if (!mddev->events && super_init_validation(mddev, rdev))
823 		return -EINVAL;
824 
825 	mddev->bitmap_info.offset = 4096 >> 9; /* Enable bitmap creation */
826 	rdev->mddev->bitmap_info.default_offset = 4096 >> 9;
827 	if (!test_bit(FirstUse, &rdev->flags)) {
828 		rdev->recovery_offset = le64_to_cpu(sb->disk_recovery_offset);
829 		if (rdev->recovery_offset != MaxSector)
830 			clear_bit(In_sync, &rdev->flags);
831 	}
832 
833 	/*
834 	 * If a device comes back, set it as not In_sync and no longer faulty.
835 	 */
836 	if (test_bit(Faulty, &rdev->flags)) {
837 		clear_bit(Faulty, &rdev->flags);
838 		clear_bit(In_sync, &rdev->flags);
839 		rdev->saved_raid_disk = rdev->raid_disk;
840 		rdev->recovery_offset = 0;
841 	}
842 
843 	clear_bit(FirstUse, &rdev->flags);
844 
845 	return 0;
846 }
847 
848 /*
849  * Analyse superblocks and select the freshest.
850  */
851 static int analyse_superblocks(struct dm_target *ti, struct raid_set *rs)
852 {
853 	int ret;
854 	struct md_rdev *rdev, *freshest, *tmp;
855 	struct mddev *mddev = &rs->md;
856 
857 	freshest = NULL;
858 	rdev_for_each(rdev, tmp, mddev) {
859 		if (!rdev->meta_bdev)
860 			continue;
861 
862 		ret = super_load(rdev, freshest);
863 
864 		switch (ret) {
865 		case 1:
866 			freshest = rdev;
867 			break;
868 		case 0:
869 			break;
870 		default:
871 			ti->error = "Failed to load superblock";
872 			return ret;
873 		}
874 	}
875 
876 	if (!freshest)
877 		return 0;
878 
879 	/*
880 	 * Validation of the freshest device provides the source of
881 	 * validation for the remaining devices.
882 	 */
883 	ti->error = "Unable to assemble array: Invalid superblocks";
884 	if (super_validate(mddev, freshest))
885 		return -EINVAL;
886 
887 	rdev_for_each(rdev, tmp, mddev)
888 		if ((rdev != freshest) && super_validate(mddev, rdev))
889 			return -EINVAL;
890 
891 	return 0;
892 }
893 
894 /*
895  * Construct a RAID4/5/6 mapping:
896  * Args:
897  *	<raid_type> <#raid_params> <raid_params>		\
898  *	<#raid_devs> { <meta_dev1> <dev1> .. <meta_devN> <devN> }
899  *
900  * <raid_params> varies by <raid_type>.  See 'parse_raid_params' for
901  * details on possible <raid_params>.
902  */
903 static int raid_ctr(struct dm_target *ti, unsigned argc, char **argv)
904 {
905 	int ret;
906 	struct raid_type *rt;
907 	unsigned long num_raid_params, num_raid_devs;
908 	struct raid_set *rs = NULL;
909 
910 	/* Must have at least <raid_type> <#raid_params> */
911 	if (argc < 2) {
912 		ti->error = "Too few arguments";
913 		return -EINVAL;
914 	}
915 
916 	/* raid type */
917 	rt = get_raid_type(argv[0]);
918 	if (!rt) {
919 		ti->error = "Unrecognised raid_type";
920 		return -EINVAL;
921 	}
922 	argc--;
923 	argv++;
924 
925 	/* number of RAID parameters */
926 	if (strict_strtoul(argv[0], 10, &num_raid_params) < 0) {
927 		ti->error = "Cannot understand number of RAID parameters";
928 		return -EINVAL;
929 	}
930 	argc--;
931 	argv++;
932 
933 	/* Skip over RAID params for now and find out # of devices */
934 	if (num_raid_params + 1 > argc) {
935 		ti->error = "Arguments do not agree with counts given";
936 		return -EINVAL;
937 	}
938 
939 	if ((strict_strtoul(argv[num_raid_params], 10, &num_raid_devs) < 0) ||
940 	    (num_raid_devs >= INT_MAX)) {
941 		ti->error = "Cannot understand number of raid devices";
942 		return -EINVAL;
943 	}
944 
945 	rs = context_alloc(ti, rt, (unsigned)num_raid_devs);
946 	if (IS_ERR(rs))
947 		return PTR_ERR(rs);
948 
949 	ret = parse_raid_params(rs, argv, (unsigned)num_raid_params);
950 	if (ret)
951 		goto bad;
952 
953 	ret = -EINVAL;
954 
955 	argc -= num_raid_params + 1; /* +1: we already have num_raid_devs */
956 	argv += num_raid_params + 1;
957 
958 	if (argc != (num_raid_devs * 2)) {
959 		ti->error = "Supplied RAID devices does not match the count given";
960 		goto bad;
961 	}
962 
963 	ret = dev_parms(rs, argv);
964 	if (ret)
965 		goto bad;
966 
967 	rs->md.sync_super = super_sync;
968 	ret = analyse_superblocks(ti, rs);
969 	if (ret)
970 		goto bad;
971 
972 	INIT_WORK(&rs->md.event_work, do_table_event);
973 	ti->private = rs;
974 
975 	mutex_lock(&rs->md.reconfig_mutex);
976 	ret = md_run(&rs->md);
977 	rs->md.in_sync = 0; /* Assume already marked dirty */
978 	mutex_unlock(&rs->md.reconfig_mutex);
979 
980 	if (ret) {
981 		ti->error = "Fail to run raid array";
982 		goto bad;
983 	}
984 
985 	rs->callbacks.congested_fn = raid_is_congested;
986 	dm_table_add_target_callbacks(ti->table, &rs->callbacks);
987 
988 	mddev_suspend(&rs->md);
989 	return 0;
990 
991 bad:
992 	context_free(rs);
993 
994 	return ret;
995 }
996 
997 static void raid_dtr(struct dm_target *ti)
998 {
999 	struct raid_set *rs = ti->private;
1000 
1001 	list_del_init(&rs->callbacks.list);
1002 	md_stop(&rs->md);
1003 	context_free(rs);
1004 }
1005 
1006 static int raid_map(struct dm_target *ti, struct bio *bio, union map_info *map_context)
1007 {
1008 	struct raid_set *rs = ti->private;
1009 	struct mddev *mddev = &rs->md;
1010 
1011 	mddev->pers->make_request(mddev, bio);
1012 
1013 	return DM_MAPIO_SUBMITTED;
1014 }
1015 
1016 static int raid_status(struct dm_target *ti, status_type_t type,
1017 		       char *result, unsigned maxlen)
1018 {
1019 	struct raid_set *rs = ti->private;
1020 	unsigned raid_param_cnt = 1; /* at least 1 for chunksize */
1021 	unsigned sz = 0;
1022 	int i, array_in_sync = 0;
1023 	sector_t sync;
1024 
1025 	switch (type) {
1026 	case STATUSTYPE_INFO:
1027 		DMEMIT("%s %d ", rs->raid_type->name, rs->md.raid_disks);
1028 
1029 		if (test_bit(MD_RECOVERY_RUNNING, &rs->md.recovery))
1030 			sync = rs->md.curr_resync_completed;
1031 		else
1032 			sync = rs->md.recovery_cp;
1033 
1034 		if (sync >= rs->md.resync_max_sectors) {
1035 			array_in_sync = 1;
1036 			sync = rs->md.resync_max_sectors;
1037 		} else {
1038 			/*
1039 			 * The array may be doing an initial sync, or it may
1040 			 * be rebuilding individual components.  If all the
1041 			 * devices are In_sync, then it is the array that is
1042 			 * being initialized.
1043 			 */
1044 			for (i = 0; i < rs->md.raid_disks; i++)
1045 				if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
1046 					array_in_sync = 1;
1047 		}
1048 		/*
1049 		 * Status characters:
1050 		 *  'D' = Dead/Failed device
1051 		 *  'a' = Alive but not in-sync
1052 		 *  'A' = Alive and in-sync
1053 		 */
1054 		for (i = 0; i < rs->md.raid_disks; i++) {
1055 			if (test_bit(Faulty, &rs->dev[i].rdev.flags))
1056 				DMEMIT("D");
1057 			else if (!array_in_sync ||
1058 				 !test_bit(In_sync, &rs->dev[i].rdev.flags))
1059 				DMEMIT("a");
1060 			else
1061 				DMEMIT("A");
1062 		}
1063 
1064 		/*
1065 		 * In-sync ratio:
1066 		 *  The in-sync ratio shows the progress of:
1067 		 *   - Initializing the array
1068 		 *   - Rebuilding a subset of devices of the array
1069 		 *  The user can distinguish between the two by referring
1070 		 *  to the status characters.
1071 		 */
1072 		DMEMIT(" %llu/%llu",
1073 		       (unsigned long long) sync,
1074 		       (unsigned long long) rs->md.resync_max_sectors);
1075 
1076 		break;
1077 	case STATUSTYPE_TABLE:
1078 		/* The string you would use to construct this array */
1079 		for (i = 0; i < rs->md.raid_disks; i++) {
1080 			if ((rs->print_flags & DMPF_REBUILD) &&
1081 			    rs->dev[i].data_dev &&
1082 			    !test_bit(In_sync, &rs->dev[i].rdev.flags))
1083 				raid_param_cnt += 2; /* for rebuilds */
1084 			if (rs->dev[i].data_dev &&
1085 			    test_bit(WriteMostly, &rs->dev[i].rdev.flags))
1086 				raid_param_cnt += 2;
1087 		}
1088 
1089 		raid_param_cnt += (hweight32(rs->print_flags & ~DMPF_REBUILD) * 2);
1090 		if (rs->print_flags & (DMPF_SYNC | DMPF_NOSYNC))
1091 			raid_param_cnt--;
1092 
1093 		DMEMIT("%s %u %u", rs->raid_type->name,
1094 		       raid_param_cnt, rs->md.chunk_sectors);
1095 
1096 		if ((rs->print_flags & DMPF_SYNC) &&
1097 		    (rs->md.recovery_cp == MaxSector))
1098 			DMEMIT(" sync");
1099 		if (rs->print_flags & DMPF_NOSYNC)
1100 			DMEMIT(" nosync");
1101 
1102 		for (i = 0; i < rs->md.raid_disks; i++)
1103 			if ((rs->print_flags & DMPF_REBUILD) &&
1104 			    rs->dev[i].data_dev &&
1105 			    !test_bit(In_sync, &rs->dev[i].rdev.flags))
1106 				DMEMIT(" rebuild %u", i);
1107 
1108 		if (rs->print_flags & DMPF_DAEMON_SLEEP)
1109 			DMEMIT(" daemon_sleep %lu",
1110 			       rs->md.bitmap_info.daemon_sleep);
1111 
1112 		if (rs->print_flags & DMPF_MIN_RECOVERY_RATE)
1113 			DMEMIT(" min_recovery_rate %d", rs->md.sync_speed_min);
1114 
1115 		if (rs->print_flags & DMPF_MAX_RECOVERY_RATE)
1116 			DMEMIT(" max_recovery_rate %d", rs->md.sync_speed_max);
1117 
1118 		for (i = 0; i < rs->md.raid_disks; i++)
1119 			if (rs->dev[i].data_dev &&
1120 			    test_bit(WriteMostly, &rs->dev[i].rdev.flags))
1121 				DMEMIT(" write_mostly %u", i);
1122 
1123 		if (rs->print_flags & DMPF_MAX_WRITE_BEHIND)
1124 			DMEMIT(" max_write_behind %lu",
1125 			       rs->md.bitmap_info.max_write_behind);
1126 
1127 		if (rs->print_flags & DMPF_STRIPE_CACHE) {
1128 			struct r5conf *conf = rs->md.private;
1129 
1130 			/* convert from kiB to sectors */
1131 			DMEMIT(" stripe_cache %d",
1132 			       conf ? conf->max_nr_stripes * 2 : 0);
1133 		}
1134 
1135 		if (rs->print_flags & DMPF_REGION_SIZE)
1136 			DMEMIT(" region_size %lu",
1137 			       rs->md.bitmap_info.chunksize >> 9);
1138 
1139 		DMEMIT(" %d", rs->md.raid_disks);
1140 		for (i = 0; i < rs->md.raid_disks; i++) {
1141 			if (rs->dev[i].meta_dev)
1142 				DMEMIT(" %s", rs->dev[i].meta_dev->name);
1143 			else
1144 				DMEMIT(" -");
1145 
1146 			if (rs->dev[i].data_dev)
1147 				DMEMIT(" %s", rs->dev[i].data_dev->name);
1148 			else
1149 				DMEMIT(" -");
1150 		}
1151 	}
1152 
1153 	return 0;
1154 }
1155 
1156 static int raid_iterate_devices(struct dm_target *ti, iterate_devices_callout_fn fn, void *data)
1157 {
1158 	struct raid_set *rs = ti->private;
1159 	unsigned i;
1160 	int ret = 0;
1161 
1162 	for (i = 0; !ret && i < rs->md.raid_disks; i++)
1163 		if (rs->dev[i].data_dev)
1164 			ret = fn(ti,
1165 				 rs->dev[i].data_dev,
1166 				 0, /* No offset on data devs */
1167 				 rs->md.dev_sectors,
1168 				 data);
1169 
1170 	return ret;
1171 }
1172 
1173 static void raid_io_hints(struct dm_target *ti, struct queue_limits *limits)
1174 {
1175 	struct raid_set *rs = ti->private;
1176 	unsigned chunk_size = rs->md.chunk_sectors << 9;
1177 	struct r5conf *conf = rs->md.private;
1178 
1179 	blk_limits_io_min(limits, chunk_size);
1180 	blk_limits_io_opt(limits, chunk_size * (conf->raid_disks - conf->max_degraded));
1181 }
1182 
1183 static void raid_presuspend(struct dm_target *ti)
1184 {
1185 	struct raid_set *rs = ti->private;
1186 
1187 	md_stop_writes(&rs->md);
1188 }
1189 
1190 static void raid_postsuspend(struct dm_target *ti)
1191 {
1192 	struct raid_set *rs = ti->private;
1193 
1194 	mddev_suspend(&rs->md);
1195 }
1196 
1197 static void raid_resume(struct dm_target *ti)
1198 {
1199 	struct raid_set *rs = ti->private;
1200 
1201 	if (!rs->bitmap_loaded) {
1202 		bitmap_load(&rs->md);
1203 		rs->bitmap_loaded = 1;
1204 	} else
1205 		md_wakeup_thread(rs->md.thread);
1206 
1207 	mddev_resume(&rs->md);
1208 }
1209 
1210 static struct target_type raid_target = {
1211 	.name = "raid",
1212 	.version = {1, 1, 0},
1213 	.module = THIS_MODULE,
1214 	.ctr = raid_ctr,
1215 	.dtr = raid_dtr,
1216 	.map = raid_map,
1217 	.status = raid_status,
1218 	.iterate_devices = raid_iterate_devices,
1219 	.io_hints = raid_io_hints,
1220 	.presuspend = raid_presuspend,
1221 	.postsuspend = raid_postsuspend,
1222 	.resume = raid_resume,
1223 };
1224 
1225 static int __init dm_raid_init(void)
1226 {
1227 	return dm_register_target(&raid_target);
1228 }
1229 
1230 static void __exit dm_raid_exit(void)
1231 {
1232 	dm_unregister_target(&raid_target);
1233 }
1234 
1235 module_init(dm_raid_init);
1236 module_exit(dm_raid_exit);
1237 
1238 MODULE_DESCRIPTION(DM_NAME " raid4/5/6 target");
1239 MODULE_ALIAS("dm-raid4");
1240 MODULE_ALIAS("dm-raid5");
1241 MODULE_ALIAS("dm-raid6");
1242 MODULE_AUTHOR("Neil Brown <dm-devel@redhat.com>");
1243 MODULE_LICENSE("GPL");
1244