Linux Audio

Check our new training course

Loading...
v3.1
   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
  10#include "md.h"
  11#include "raid1.h"
  12#include "raid5.h"
 
  13#include "bitmap.h"
  14
  15#include <linux/device-mapper.h>
  16
  17#define DM_MSG_PREFIX "raid"
 
 
 
  18
  19/*
  20 * The following flags are used by dm-raid.c to set up the array state.
  21 * They must be cleared before md_run is called.
  22 */
  23#define FirstUse 10             /* rdev flag */
  24
  25struct raid_dev {
  26	/*
  27	 * Two DM devices, one to hold metadata and one to hold the
  28	 * actual data/parity.  The reason for this is to not confuse
  29	 * ti->len and give more flexibility in altering size and
  30	 * characteristics.
  31	 *
  32	 * While it is possible for this device to be associated
  33	 * with a different physical device than the data_dev, it
  34	 * is intended for it to be the same.
  35	 *    |--------- Physical Device ---------|
  36	 *    |- meta_dev -|------ data_dev ------|
  37	 */
  38	struct dm_dev *meta_dev;
  39	struct dm_dev *data_dev;
  40	struct mdk_rdev_s rdev;
  41};
  42
  43/*
  44 * Flags for rs->print_flags field.
  45 */
  46#define DMPF_SYNC              0x1
  47#define DMPF_NOSYNC            0x2
  48#define DMPF_REBUILD           0x4
  49#define DMPF_DAEMON_SLEEP      0x8
  50#define DMPF_MIN_RECOVERY_RATE 0x10
  51#define DMPF_MAX_RECOVERY_RATE 0x20
  52#define DMPF_MAX_WRITE_BEHIND  0x40
  53#define DMPF_STRIPE_CACHE      0x80
  54#define DMPF_REGION_SIZE       0X100
 
 
 
  55struct raid_set {
  56	struct dm_target *ti;
  57
  58	uint64_t print_flags;
 
  59
  60	struct mddev_s md;
  61	struct raid_type *raid_type;
  62	struct dm_target_callbacks callbacks;
  63
  64	struct raid_dev dev[0];
  65};
  66
  67/* Supported raid types and properties. */
  68static struct raid_type {
  69	const char *name;		/* RAID algorithm. */
  70	const char *descr;		/* Descriptor text for logging. */
  71	const unsigned parity_devs;	/* # of parity devices. */
  72	const unsigned minimal_devs;	/* minimal # of devices in set. */
  73	const unsigned level;		/* RAID level. */
  74	const unsigned algorithm;	/* RAID algorithm. */
  75} raid_types[] = {
 
  76	{"raid1",    "RAID1 (mirroring)",               0, 2, 1, 0 /* NONE */},
 
  77	{"raid4",    "RAID4 (dedicated parity disk)",	1, 2, 5, ALGORITHM_PARITY_0},
  78	{"raid5_la", "RAID5 (left asymmetric)",		1, 2, 5, ALGORITHM_LEFT_ASYMMETRIC},
  79	{"raid5_ra", "RAID5 (right asymmetric)",	1, 2, 5, ALGORITHM_RIGHT_ASYMMETRIC},
  80	{"raid5_ls", "RAID5 (left symmetric)",		1, 2, 5, ALGORITHM_LEFT_SYMMETRIC},
  81	{"raid5_rs", "RAID5 (right symmetric)",		1, 2, 5, ALGORITHM_RIGHT_SYMMETRIC},
  82	{"raid6_zr", "RAID6 (zero restart)",		2, 4, 6, ALGORITHM_ROTATING_ZERO_RESTART},
  83	{"raid6_nr", "RAID6 (N restart)",		2, 4, 6, ALGORITHM_ROTATING_N_RESTART},
  84	{"raid6_nc", "RAID6 (N continue)",		2, 4, 6, ALGORITHM_ROTATING_N_CONTINUE}
  85};
  86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  87static struct raid_type *get_raid_type(char *name)
  88{
  89	int i;
  90
  91	for (i = 0; i < ARRAY_SIZE(raid_types); i++)
  92		if (!strcmp(raid_types[i].name, name))
  93			return &raid_types[i];
  94
  95	return NULL;
  96}
  97
  98static struct raid_set *context_alloc(struct dm_target *ti, struct raid_type *raid_type, unsigned raid_devs)
  99{
 100	unsigned i;
 101	struct raid_set *rs;
 102	sector_t sectors_per_dev;
 103
 104	if (raid_devs <= raid_type->parity_devs) {
 105		ti->error = "Insufficient number of devices";
 106		return ERR_PTR(-EINVAL);
 107	}
 108
 109	sectors_per_dev = ti->len;
 110	if ((raid_type->level > 1) &&
 111	    sector_div(sectors_per_dev, (raid_devs - raid_type->parity_devs))) {
 112		ti->error = "Target length not divisible by number of data devices";
 113		return ERR_PTR(-EINVAL);
 114	}
 115
 116	rs = kzalloc(sizeof(*rs) + raid_devs * sizeof(rs->dev[0]), GFP_KERNEL);
 117	if (!rs) {
 118		ti->error = "Cannot allocate raid context";
 119		return ERR_PTR(-ENOMEM);
 120	}
 121
 122	mddev_init(&rs->md);
 123
 124	rs->ti = ti;
 125	rs->raid_type = raid_type;
 126	rs->md.raid_disks = raid_devs;
 127	rs->md.level = raid_type->level;
 128	rs->md.new_level = rs->md.level;
 129	rs->md.dev_sectors = sectors_per_dev;
 130	rs->md.layout = raid_type->algorithm;
 131	rs->md.new_layout = rs->md.layout;
 132	rs->md.delta_disks = 0;
 133	rs->md.recovery_cp = 0;
 134
 135	for (i = 0; i < raid_devs; i++)
 136		md_rdev_init(&rs->dev[i].rdev);
 137
 138	/*
 139	 * Remaining items to be initialized by further RAID params:
 140	 *  rs->md.persistent
 141	 *  rs->md.external
 142	 *  rs->md.chunk_sectors
 143	 *  rs->md.new_chunk_sectors
 
 144	 */
 145
 146	return rs;
 147}
 148
 149static void context_free(struct raid_set *rs)
 150{
 151	int i;
 152
 153	for (i = 0; i < rs->md.raid_disks; i++) {
 154		if (rs->dev[i].meta_dev)
 155			dm_put_device(rs->ti, rs->dev[i].meta_dev);
 156		if (rs->dev[i].rdev.sb_page)
 157			put_page(rs->dev[i].rdev.sb_page);
 158		rs->dev[i].rdev.sb_page = NULL;
 159		rs->dev[i].rdev.sb_loaded = 0;
 160		if (rs->dev[i].data_dev)
 161			dm_put_device(rs->ti, rs->dev[i].data_dev);
 162	}
 163
 164	kfree(rs);
 165}
 166
 167/*
 168 * For every device we have two words
 169 *  <meta_dev>: meta device name or '-' if missing
 170 *  <data_dev>: data device name or '-' if missing
 171 *
 172 * The following are permitted:
 173 *    - -
 174 *    - <data_dev>
 175 *    <meta_dev> <data_dev>
 176 *
 177 * The following is not allowed:
 178 *    <meta_dev> -
 179 *
 180 * This code parses those words.  If there is a failure,
 181 * the caller must use context_free to unwind the operations.
 182 */
 183static int dev_parms(struct raid_set *rs, char **argv)
 184{
 185	int i;
 186	int rebuild = 0;
 187	int metadata_available = 0;
 188	int ret = 0;
 189
 190	for (i = 0; i < rs->md.raid_disks; i++, argv += 2) {
 191		rs->dev[i].rdev.raid_disk = i;
 192
 193		rs->dev[i].meta_dev = NULL;
 194		rs->dev[i].data_dev = NULL;
 195
 196		/*
 197		 * There are no offsets, since there is a separate device
 198		 * for data and metadata.
 199		 */
 200		rs->dev[i].rdev.data_offset = 0;
 201		rs->dev[i].rdev.mddev = &rs->md;
 202
 203		if (strcmp(argv[0], "-")) {
 204			ret = dm_get_device(rs->ti, argv[0],
 205					    dm_table_get_mode(rs->ti->table),
 206					    &rs->dev[i].meta_dev);
 207			rs->ti->error = "RAID metadata device lookup failure";
 208			if (ret)
 209				return ret;
 210
 211			rs->dev[i].rdev.sb_page = alloc_page(GFP_KERNEL);
 212			if (!rs->dev[i].rdev.sb_page)
 213				return -ENOMEM;
 214		}
 215
 216		if (!strcmp(argv[1], "-")) {
 217			if (!test_bit(In_sync, &rs->dev[i].rdev.flags) &&
 218			    (!rs->dev[i].rdev.recovery_offset)) {
 219				rs->ti->error = "Drive designated for rebuild not specified";
 220				return -EINVAL;
 221			}
 222
 223			rs->ti->error = "No data device supplied with metadata device";
 224			if (rs->dev[i].meta_dev)
 225				return -EINVAL;
 226
 227			continue;
 228		}
 229
 230		ret = dm_get_device(rs->ti, argv[1],
 231				    dm_table_get_mode(rs->ti->table),
 232				    &rs->dev[i].data_dev);
 233		if (ret) {
 234			rs->ti->error = "RAID device lookup failure";
 235			return ret;
 236		}
 237
 238		if (rs->dev[i].meta_dev) {
 239			metadata_available = 1;
 240			rs->dev[i].rdev.meta_bdev = rs->dev[i].meta_dev->bdev;
 241		}
 242		rs->dev[i].rdev.bdev = rs->dev[i].data_dev->bdev;
 243		list_add(&rs->dev[i].rdev.same_set, &rs->md.disks);
 244		if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
 245			rebuild++;
 246	}
 247
 248	if (metadata_available) {
 249		rs->md.external = 0;
 250		rs->md.persistent = 1;
 251		rs->md.major_version = 2;
 252	} else if (rebuild && !rs->md.recovery_cp) {
 253		/*
 254		 * Without metadata, we will not be able to tell if the array
 255		 * is in-sync or not - we must assume it is not.  Therefore,
 256		 * it is impossible to rebuild a drive.
 257		 *
 258		 * Even if there is metadata, the on-disk information may
 259		 * indicate that the array is not in-sync and it will then
 260		 * fail at that time.
 261		 *
 262		 * User could specify 'nosync' option if desperate.
 263		 */
 264		DMERR("Unable to rebuild drive while array is not in-sync");
 265		rs->ti->error = "RAID device lookup failure";
 266		return -EINVAL;
 267	}
 268
 269	return 0;
 270}
 271
 272/*
 273 * validate_region_size
 274 * @rs
 275 * @region_size:  region size in sectors.  If 0, pick a size (4MiB default).
 276 *
 277 * Set rs->md.bitmap_info.chunksize (which really refers to 'region size').
 278 * Ensure that (ti->len/region_size < 2^21) - required by MD bitmap.
 279 *
 280 * Returns: 0 on success, -EINVAL on failure.
 281 */
 282static int validate_region_size(struct raid_set *rs, unsigned long region_size)
 283{
 284	unsigned long min_region_size = rs->ti->len / (1 << 21);
 285
 286	if (!region_size) {
 287		/*
 288		 * Choose a reasonable default.  All figures in sectors.
 289		 */
 290		if (min_region_size > (1 << 13)) {
 
 
 291			DMINFO("Choosing default region size of %lu sectors",
 292			       region_size);
 293			region_size = min_region_size;
 294		} else {
 295			DMINFO("Choosing default region size of 4MiB");
 296			region_size = 1 << 13; /* sectors */
 297		}
 298	} else {
 299		/*
 300		 * Validate user-supplied value.
 301		 */
 302		if (region_size > rs->ti->len) {
 303			rs->ti->error = "Supplied region size is too large";
 304			return -EINVAL;
 305		}
 306
 307		if (region_size < min_region_size) {
 308			DMERR("Supplied region_size (%lu sectors) below minimum (%lu)",
 309			      region_size, min_region_size);
 310			rs->ti->error = "Supplied region size is too small";
 311			return -EINVAL;
 312		}
 313
 314		if (!is_power_of_2(region_size)) {
 315			rs->ti->error = "Region size is not a power of 2";
 316			return -EINVAL;
 317		}
 318
 319		if (region_size < rs->md.chunk_sectors) {
 320			rs->ti->error = "Region size is smaller than the chunk size";
 321			return -EINVAL;
 322		}
 323	}
 324
 325	/*
 326	 * Convert sectors to bytes.
 327	 */
 328	rs->md.bitmap_info.chunksize = (region_size << 9);
 329
 330	return 0;
 331}
 332
 333/*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 334 * Possible arguments are...
 335 *	<chunk_size> [optional_args]
 336 *
 337 * Argument definitions
 338 *    <chunk_size>			The number of sectors per disk that
 339 *                                      will form the "stripe"
 340 *    [[no]sync]			Force or prevent recovery of the
 341 *                                      entire array
 342 *    [rebuild <idx>]			Rebuild the drive indicated by the index
 343 *    [daemon_sleep <ms>]		Time between bitmap daemon work to
 344 *                                      clear bits
 345 *    [min_recovery_rate <kB/sec/disk>]	Throttle RAID initialization
 346 *    [max_recovery_rate <kB/sec/disk>]	Throttle RAID initialization
 347 *    [write_mostly <idx>]		Indicate a write mostly drive via index
 348 *    [max_write_behind <sectors>]	See '-write-behind=' (man mdadm)
 349 *    [stripe_cache <sectors>]		Stripe cache size for higher RAIDs
 350 *    [region_size <sectors>]           Defines granularity of bitmap
 
 
 
 
 351 */
 352static int parse_raid_params(struct raid_set *rs, char **argv,
 353			     unsigned num_raid_params)
 354{
 355	unsigned i, rebuild_cnt = 0;
 
 
 356	unsigned long value, region_size = 0;
 
 
 357	char *key;
 358
 359	/*
 360	 * First, parse the in-order required arguments
 361	 * "chunk_size" is the only argument of this type.
 362	 */
 363	if ((strict_strtoul(argv[0], 10, &value) < 0)) {
 364		rs->ti->error = "Bad chunk size";
 365		return -EINVAL;
 366	} else if (rs->raid_type->level == 1) {
 367		if (value)
 368			DMERR("Ignoring chunk size parameter for RAID 1");
 369		value = 0;
 370	} else if (!is_power_of_2(value)) {
 371		rs->ti->error = "Chunk size must be a power of 2";
 372		return -EINVAL;
 373	} else if (value < 8) {
 374		rs->ti->error = "Chunk size value is too small";
 375		return -EINVAL;
 376	}
 377
 378	rs->md.new_chunk_sectors = rs->md.chunk_sectors = value;
 379	argv++;
 380	num_raid_params--;
 381
 382	/*
 383	 * We set each individual device as In_sync with a completed
 384	 * 'recovery_offset'.  If there has been a device failure or
 385	 * replacement then one of the following cases applies:
 386	 *
 387	 *   1) User specifies 'rebuild'.
 388	 *      - Device is reset when param is read.
 389	 *   2) A new device is supplied.
 390	 *      - No matching superblock found, resets device.
 391	 *   3) Device failure was transient and returns on reload.
 392	 *      - Failure noticed, resets device for bitmap replay.
 393	 *   4) Device hadn't completed recovery after previous failure.
 394	 *      - Superblock is read and overrides recovery_offset.
 395	 *
 396	 * What is found in the superblocks of the devices is always
 397	 * authoritative, unless 'rebuild' or '[no]sync' was specified.
 398	 */
 399	for (i = 0; i < rs->md.raid_disks; i++) {
 400		set_bit(In_sync, &rs->dev[i].rdev.flags);
 401		rs->dev[i].rdev.recovery_offset = MaxSector;
 402	}
 403
 404	/*
 405	 * Second, parse the unordered optional arguments
 406	 */
 407	for (i = 0; i < num_raid_params; i++) {
 408		if (!strcasecmp(argv[i], "nosync")) {
 409			rs->md.recovery_cp = MaxSector;
 410			rs->print_flags |= DMPF_NOSYNC;
 411			continue;
 412		}
 413		if (!strcasecmp(argv[i], "sync")) {
 414			rs->md.recovery_cp = 0;
 415			rs->print_flags |= DMPF_SYNC;
 416			continue;
 417		}
 418
 419		/* The rest of the optional arguments come in key/value pairs */
 420		if ((i + 1) >= num_raid_params) {
 421			rs->ti->error = "Wrong number of raid parameters given";
 422			return -EINVAL;
 423		}
 424
 425		key = argv[i++];
 426		if (strict_strtoul(argv[i], 10, &value) < 0) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 427			rs->ti->error = "Bad numerical argument given in raid params";
 428			return -EINVAL;
 429		}
 430
 
 431		if (!strcasecmp(key, "rebuild")) {
 432			rebuild_cnt++;
 433			if (((rs->raid_type->level != 1) &&
 434			     (rebuild_cnt > rs->raid_type->parity_devs)) ||
 435			    ((rs->raid_type->level == 1) &&
 436			     (rebuild_cnt > (rs->md.raid_disks - 1)))) {
 437				rs->ti->error = "Too many rebuild devices specified for given RAID type";
 438				return -EINVAL;
 439			}
 440			if (value > rs->md.raid_disks) {
 441				rs->ti->error = "Invalid rebuild index given";
 442				return -EINVAL;
 443			}
 444			clear_bit(In_sync, &rs->dev[value].rdev.flags);
 445			rs->dev[value].rdev.recovery_offset = 0;
 446			rs->print_flags |= DMPF_REBUILD;
 447		} else if (!strcasecmp(key, "write_mostly")) {
 448			if (rs->raid_type->level != 1) {
 449				rs->ti->error = "write_mostly option is only valid for RAID1";
 450				return -EINVAL;
 451			}
 452			if (value >= rs->md.raid_disks) {
 453				rs->ti->error = "Invalid write_mostly drive index given";
 454				return -EINVAL;
 455			}
 456			set_bit(WriteMostly, &rs->dev[value].rdev.flags);
 457		} else if (!strcasecmp(key, "max_write_behind")) {
 458			if (rs->raid_type->level != 1) {
 459				rs->ti->error = "max_write_behind option is only valid for RAID1";
 460				return -EINVAL;
 461			}
 462			rs->print_flags |= DMPF_MAX_WRITE_BEHIND;
 463
 464			/*
 465			 * In device-mapper, we specify things in sectors, but
 466			 * MD records this value in kB
 467			 */
 468			value /= 2;
 469			if (value > COUNTER_MAX) {
 470				rs->ti->error = "Max write-behind limit out of range";
 471				return -EINVAL;
 472			}
 473			rs->md.bitmap_info.max_write_behind = value;
 474		} else if (!strcasecmp(key, "daemon_sleep")) {
 475			rs->print_flags |= DMPF_DAEMON_SLEEP;
 476			if (!value || (value > MAX_SCHEDULE_TIMEOUT)) {
 477				rs->ti->error = "daemon sleep period out of range";
 478				return -EINVAL;
 479			}
 480			rs->md.bitmap_info.daemon_sleep = value;
 481		} else if (!strcasecmp(key, "stripe_cache")) {
 482			rs->print_flags |= DMPF_STRIPE_CACHE;
 483
 484			/*
 485			 * In device-mapper, we specify things in sectors, but
 486			 * MD records this value in kB
 487			 */
 488			value /= 2;
 489
 490			if (rs->raid_type->level < 5) {
 
 491				rs->ti->error = "Inappropriate argument: stripe_cache";
 492				return -EINVAL;
 493			}
 494			if (raid5_set_cache_size(&rs->md, (int)value)) {
 495				rs->ti->error = "Bad stripe_cache size";
 496				return -EINVAL;
 497			}
 498		} else if (!strcasecmp(key, "min_recovery_rate")) {
 499			rs->print_flags |= DMPF_MIN_RECOVERY_RATE;
 500			if (value > INT_MAX) {
 501				rs->ti->error = "min_recovery_rate out of range";
 502				return -EINVAL;
 503			}
 504			rs->md.sync_speed_min = (int)value;
 505		} else if (!strcasecmp(key, "max_recovery_rate")) {
 506			rs->print_flags |= DMPF_MAX_RECOVERY_RATE;
 507			if (value > INT_MAX) {
 508				rs->ti->error = "max_recovery_rate out of range";
 509				return -EINVAL;
 510			}
 511			rs->md.sync_speed_max = (int)value;
 512		} else if (!strcasecmp(key, "region_size")) {
 513			rs->print_flags |= DMPF_REGION_SIZE;
 514			region_size = value;
 
 
 
 
 
 
 
 
 515		} else {
 516			DMERR("Unable to parse RAID parameter: %s", key);
 517			rs->ti->error = "Unable to parse RAID parameters";
 518			return -EINVAL;
 519		}
 520	}
 521
 522	if (validate_region_size(rs, region_size))
 523		return -EINVAL;
 524
 525	if (rs->md.chunk_sectors)
 526		rs->ti->split_io = rs->md.chunk_sectors;
 527	else
 528		rs->ti->split_io = region_size;
 529
 530	if (rs->md.chunk_sectors)
 531		rs->ti->split_io = rs->md.chunk_sectors;
 532	else
 533		rs->ti->split_io = region_size;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 534
 535	/* Assume there are no metadata devices until the drives are parsed */
 536	rs->md.persistent = 0;
 537	rs->md.external = 1;
 538
 539	return 0;
 540}
 541
 542static void do_table_event(struct work_struct *ws)
 543{
 544	struct raid_set *rs = container_of(ws, struct raid_set, md.event_work);
 545
 546	dm_table_event(rs->ti->table);
 547}
 548
 549static int raid_is_congested(struct dm_target_callbacks *cb, int bits)
 550{
 551	struct raid_set *rs = container_of(cb, struct raid_set, callbacks);
 552
 553	if (rs->raid_type->level == 1)
 554		return md_raid1_congested(&rs->md, bits);
 555
 556	return md_raid5_congested(&rs->md, bits);
 557}
 558
 559/*
 560 * This structure is never routinely used by userspace, unlike md superblocks.
 561 * Devices with this superblock should only ever be accessed via device-mapper.
 562 */
 563#define DM_RAID_MAGIC 0x64526D44
 564struct dm_raid_superblock {
 565	__le32 magic;		/* "DmRd" */
 566	__le32 features;	/* Used to indicate possible future changes */
 567
 568	__le32 num_devices;	/* Number of devices in this array. (Max 64) */
 569	__le32 array_position;	/* The position of this drive in the array */
 570
 571	__le64 events;		/* Incremented by md when superblock updated */
 572	__le64 failed_devices;	/* Bit field of devices to indicate failures */
 573
 574	/*
 575	 * This offset tracks the progress of the repair or replacement of
 576	 * an individual drive.
 577	 */
 578	__le64 disk_recovery_offset;
 579
 580	/*
 581	 * This offset tracks the progress of the initial array
 582	 * synchronisation/parity calculation.
 583	 */
 584	__le64 array_resync_offset;
 585
 586	/*
 587	 * RAID characteristics
 588	 */
 589	__le32 level;
 590	__le32 layout;
 591	__le32 stripe_sectors;
 592
 593	__u8 pad[452];		/* Round struct to 512 bytes. */
 594				/* Always set to 0 when writing. */
 595} __packed;
 596
 597static int read_disk_sb(mdk_rdev_t *rdev, int size)
 598{
 599	BUG_ON(!rdev->sb_page);
 600
 601	if (rdev->sb_loaded)
 602		return 0;
 603
 604	if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, 1)) {
 605		DMERR("Failed to read device superblock");
 
 
 606		return -EINVAL;
 607	}
 608
 609	rdev->sb_loaded = 1;
 610
 611	return 0;
 612}
 613
 614static void super_sync(mddev_t *mddev, mdk_rdev_t *rdev)
 615{
 616	mdk_rdev_t *r, *t;
 617	uint64_t failed_devices;
 618	struct dm_raid_superblock *sb;
 
 619
 620	sb = page_address(rdev->sb_page);
 621	failed_devices = le64_to_cpu(sb->failed_devices);
 622
 623	rdev_for_each(r, t, mddev)
 624		if ((r->raid_disk >= 0) && test_bit(Faulty, &r->flags))
 625			failed_devices |= (1ULL << r->raid_disk);
 
 626
 627	memset(sb, 0, sizeof(*sb));
 628
 629	sb->magic = cpu_to_le32(DM_RAID_MAGIC);
 630	sb->features = cpu_to_le32(0);	/* No features yet */
 631
 632	sb->num_devices = cpu_to_le32(mddev->raid_disks);
 633	sb->array_position = cpu_to_le32(rdev->raid_disk);
 634
 635	sb->events = cpu_to_le64(mddev->events);
 636	sb->failed_devices = cpu_to_le64(failed_devices);
 637
 638	sb->disk_recovery_offset = cpu_to_le64(rdev->recovery_offset);
 639	sb->array_resync_offset = cpu_to_le64(mddev->recovery_cp);
 640
 641	sb->level = cpu_to_le32(mddev->level);
 642	sb->layout = cpu_to_le32(mddev->layout);
 643	sb->stripe_sectors = cpu_to_le32(mddev->chunk_sectors);
 644}
 645
 646/*
 647 * super_load
 648 *
 649 * This function creates a superblock if one is not found on the device
 650 * and will decide which superblock to use if there's a choice.
 651 *
 652 * Return: 1 if use rdev, 0 if use refdev, -Exxx otherwise
 653 */
 654static int super_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev)
 655{
 656	int ret;
 657	struct dm_raid_superblock *sb;
 658	struct dm_raid_superblock *refsb;
 659	uint64_t events_sb, events_refsb;
 660
 661	rdev->sb_start = 0;
 662	rdev->sb_size = sizeof(*sb);
 
 
 
 
 663
 664	ret = read_disk_sb(rdev, rdev->sb_size);
 665	if (ret)
 666		return ret;
 667
 668	sb = page_address(rdev->sb_page);
 669	if (sb->magic != cpu_to_le32(DM_RAID_MAGIC)) {
 
 
 
 
 
 
 
 670		super_sync(rdev->mddev, rdev);
 671
 672		set_bit(FirstUse, &rdev->flags);
 673
 674		/* Force writing of superblocks to disk */
 675		set_bit(MD_CHANGE_DEVS, &rdev->mddev->flags);
 676
 677		/* Any superblock is better than none, choose that if given */
 678		return refdev ? 0 : 1;
 679	}
 680
 681	if (!refdev)
 682		return 1;
 683
 684	events_sb = le64_to_cpu(sb->events);
 685
 686	refsb = page_address(refdev->sb_page);
 687	events_refsb = le64_to_cpu(refsb->events);
 688
 689	return (events_sb > events_refsb) ? 1 : 0;
 690}
 691
 692static int super_init_validation(mddev_t *mddev, mdk_rdev_t *rdev)
 693{
 694	int role;
 695	struct raid_set *rs = container_of(mddev, struct raid_set, md);
 696	uint64_t events_sb;
 697	uint64_t failed_devices;
 698	struct dm_raid_superblock *sb;
 699	uint32_t new_devs = 0;
 700	uint32_t rebuilds = 0;
 701	mdk_rdev_t *r, *t;
 702	struct dm_raid_superblock *sb2;
 703
 704	sb = page_address(rdev->sb_page);
 705	events_sb = le64_to_cpu(sb->events);
 706	failed_devices = le64_to_cpu(sb->failed_devices);
 707
 708	/*
 709	 * Initialise to 1 if this is a new superblock.
 710	 */
 711	mddev->events = events_sb ? : 1;
 712
 713	/*
 714	 * Reshaping is not currently allowed
 715	 */
 716	if ((le32_to_cpu(sb->level) != mddev->level) ||
 717	    (le32_to_cpu(sb->layout) != mddev->layout) ||
 718	    (le32_to_cpu(sb->stripe_sectors) != mddev->chunk_sectors)) {
 719		DMERR("Reshaping arrays not yet supported.");
 
 
 
 
 
 
 
 
 
 
 
 
 
 720		return -EINVAL;
 721	}
 722
 723	/* We can only change the number of devices in RAID1 right now */
 724	if ((rs->raid_type->level != 1) &&
 725	    (le32_to_cpu(sb->num_devices) != mddev->raid_disks)) {
 726		DMERR("Reshaping arrays not yet supported.");
 727		return -EINVAL;
 728	}
 729
 730	if (!(rs->print_flags & (DMPF_SYNC | DMPF_NOSYNC)))
 731		mddev->recovery_cp = le64_to_cpu(sb->array_resync_offset);
 732
 733	/*
 734	 * During load, we set FirstUse if a new superblock was written.
 735	 * There are two reasons we might not have a superblock:
 736	 * 1) The array is brand new - in which case, all of the
 737	 *    devices must have their In_sync bit set.  Also,
 738	 *    recovery_cp must be 0, unless forced.
 739	 * 2) This is a new device being added to an old array
 740	 *    and the new device needs to be rebuilt - in which
 741	 *    case the In_sync bit will /not/ be set and
 742	 *    recovery_cp must be MaxSector.
 743	 */
 744	rdev_for_each(r, t, mddev) {
 745		if (!test_bit(In_sync, &r->flags)) {
 746			if (!test_bit(FirstUse, &r->flags))
 747				DMERR("Superblock area of "
 748				      "rebuild device %d should have been "
 749				      "cleared.", r->raid_disk);
 750			set_bit(FirstUse, &r->flags);
 751			rebuilds++;
 752		} else if (test_bit(FirstUse, &r->flags))
 753			new_devs++;
 754	}
 755
 756	if (!rebuilds) {
 757		if (new_devs == mddev->raid_disks) {
 758			DMINFO("Superblocks created for new array");
 759			set_bit(MD_ARRAY_FIRST_USE, &mddev->flags);
 760		} else if (new_devs) {
 761			DMERR("New device injected "
 762			      "into existing array without 'rebuild' "
 763			      "parameter specified");
 764			return -EINVAL;
 765		}
 766	} else if (new_devs) {
 767		DMERR("'rebuild' devices cannot be "
 768		      "injected into an array with other first-time devices");
 769		return -EINVAL;
 770	} else if (mddev->recovery_cp != MaxSector) {
 771		DMERR("'rebuild' specified while array is not in-sync");
 772		return -EINVAL;
 773	}
 774
 775	/*
 776	 * Now we set the Faulty bit for those devices that are
 777	 * recorded in the superblock as failed.
 778	 */
 779	rdev_for_each(r, t, mddev) {
 780		if (!r->sb_page)
 781			continue;
 782		sb2 = page_address(r->sb_page);
 783		sb2->failed_devices = 0;
 784
 785		/*
 786		 * Check for any device re-ordering.
 787		 */
 788		if (!test_bit(FirstUse, &r->flags) && (r->raid_disk >= 0)) {
 789			role = le32_to_cpu(sb2->array_position);
 790			if (role != r->raid_disk) {
 791				if (rs->raid_type->level != 1) {
 792					rs->ti->error = "Cannot change device "
 793						"positions in RAID array";
 794					return -EINVAL;
 795				}
 796				DMINFO("RAID1 device #%d now at position #%d",
 797				       role, r->raid_disk);
 798			}
 799
 800			/*
 801			 * Partial recovery is performed on
 802			 * returning failed devices.
 803			 */
 804			if (failed_devices & (1 << role))
 805				set_bit(Faulty, &r->flags);
 806		}
 807	}
 808
 809	return 0;
 810}
 811
 812static int super_validate(mddev_t *mddev, mdk_rdev_t *rdev)
 813{
 
 814	struct dm_raid_superblock *sb = page_address(rdev->sb_page);
 815
 816	/*
 817	 * If mddev->events is not set, we know we have not yet initialized
 818	 * the array.
 819	 */
 820	if (!mddev->events && super_init_validation(mddev, rdev))
 821		return -EINVAL;
 822
 823	mddev->bitmap_info.offset = 4096 >> 9; /* Enable bitmap creation */
 824	rdev->mddev->bitmap_info.default_offset = 4096 >> 9;
 
 
 825	if (!test_bit(FirstUse, &rdev->flags)) {
 826		rdev->recovery_offset = le64_to_cpu(sb->disk_recovery_offset);
 827		if (rdev->recovery_offset != MaxSector)
 828			clear_bit(In_sync, &rdev->flags);
 829	}
 830
 831	/*
 832	 * If a device comes back, set it as not In_sync and no longer faulty.
 833	 */
 834	if (test_bit(Faulty, &rdev->flags)) {
 835		clear_bit(Faulty, &rdev->flags);
 836		clear_bit(In_sync, &rdev->flags);
 837		rdev->saved_raid_disk = rdev->raid_disk;
 838		rdev->recovery_offset = 0;
 839	}
 840
 841	clear_bit(FirstUse, &rdev->flags);
 842
 843	return 0;
 844}
 845
 846/*
 847 * Analyse superblocks and select the freshest.
 848 */
 849static int analyse_superblocks(struct dm_target *ti, struct raid_set *rs)
 850{
 851	int ret;
 852	mdk_rdev_t *rdev, *freshest, *tmp;
 853	mddev_t *mddev = &rs->md;
 
 854
 855	freshest = NULL;
 856	rdev_for_each(rdev, tmp, mddev) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 857		if (!rdev->meta_bdev)
 858			continue;
 859
 860		ret = super_load(rdev, freshest);
 861
 862		switch (ret) {
 863		case 1:
 864			freshest = rdev;
 865			break;
 866		case 0:
 867			break;
 868		default:
 869			ti->error = "Failed to load superblock";
 870			return ret;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 871		}
 872	}
 873
 874	if (!freshest)
 875		return 0;
 876
 
 
 
 
 
 877	/*
 878	 * Validation of the freshest device provides the source of
 879	 * validation for the remaining devices.
 880	 */
 881	ti->error = "Unable to assemble array: Invalid superblocks";
 882	if (super_validate(mddev, freshest))
 883		return -EINVAL;
 884
 885	rdev_for_each(rdev, tmp, mddev)
 886		if ((rdev != freshest) && super_validate(mddev, rdev))
 887			return -EINVAL;
 888
 889	return 0;
 890}
 891
 892/*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 893 * Construct a RAID4/5/6 mapping:
 894 * Args:
 895 *	<raid_type> <#raid_params> <raid_params>		\
 896 *	<#raid_devs> { <meta_dev1> <dev1> .. <meta_devN> <devN> }
 897 *
 898 * <raid_params> varies by <raid_type>.  See 'parse_raid_params' for
 899 * details on possible <raid_params>.
 900 */
 901static int raid_ctr(struct dm_target *ti, unsigned argc, char **argv)
 902{
 903	int ret;
 904	struct raid_type *rt;
 905	unsigned long num_raid_params, num_raid_devs;
 906	struct raid_set *rs = NULL;
 907
 908	/* Must have at least <raid_type> <#raid_params> */
 909	if (argc < 2) {
 910		ti->error = "Too few arguments";
 911		return -EINVAL;
 912	}
 913
 914	/* raid type */
 915	rt = get_raid_type(argv[0]);
 916	if (!rt) {
 917		ti->error = "Unrecognised raid_type";
 918		return -EINVAL;
 919	}
 920	argc--;
 921	argv++;
 922
 923	/* number of RAID parameters */
 924	if (strict_strtoul(argv[0], 10, &num_raid_params) < 0) {
 925		ti->error = "Cannot understand number of RAID parameters";
 926		return -EINVAL;
 927	}
 928	argc--;
 929	argv++;
 930
 931	/* Skip over RAID params for now and find out # of devices */
 932	if (num_raid_params + 1 > argc) {
 933		ti->error = "Arguments do not agree with counts given";
 934		return -EINVAL;
 935	}
 936
 937	if ((strict_strtoul(argv[num_raid_params], 10, &num_raid_devs) < 0) ||
 938	    (num_raid_devs >= INT_MAX)) {
 939		ti->error = "Cannot understand number of raid devices";
 940		return -EINVAL;
 941	}
 942
 
 
 
 
 
 
 943	rs = context_alloc(ti, rt, (unsigned)num_raid_devs);
 944	if (IS_ERR(rs))
 945		return PTR_ERR(rs);
 946
 947	ret = parse_raid_params(rs, argv, (unsigned)num_raid_params);
 948	if (ret)
 949		goto bad;
 950
 951	ret = -EINVAL;
 952
 953	argc -= num_raid_params + 1; /* +1: we already have num_raid_devs */
 954	argv += num_raid_params + 1;
 955
 956	if (argc != (num_raid_devs * 2)) {
 957		ti->error = "Supplied RAID devices does not match the count given";
 958		goto bad;
 959	}
 960
 961	ret = dev_parms(rs, argv);
 962	if (ret)
 963		goto bad;
 964
 965	rs->md.sync_super = super_sync;
 966	ret = analyse_superblocks(ti, rs);
 967	if (ret)
 968		goto bad;
 969
 970	INIT_WORK(&rs->md.event_work, do_table_event);
 971	ti->private = rs;
 
 972
 973	mutex_lock(&rs->md.reconfig_mutex);
 
 
 
 
 
 
 974	ret = md_run(&rs->md);
 975	rs->md.in_sync = 0; /* Assume already marked dirty */
 976	mutex_unlock(&rs->md.reconfig_mutex);
 977
 978	if (ret) {
 979		ti->error = "Fail to run raid array";
 980		goto bad;
 981	}
 982
 
 
 
 
 
 983	rs->callbacks.congested_fn = raid_is_congested;
 984	dm_table_add_target_callbacks(ti->table, &rs->callbacks);
 985
 986	mddev_suspend(&rs->md);
 987	return 0;
 988
 
 
 989bad:
 990	context_free(rs);
 991
 992	return ret;
 993}
 994
 995static void raid_dtr(struct dm_target *ti)
 996{
 997	struct raid_set *rs = ti->private;
 998
 999	list_del_init(&rs->callbacks.list);
1000	md_stop(&rs->md);
1001	context_free(rs);
1002}
1003
1004static int raid_map(struct dm_target *ti, struct bio *bio, union map_info *map_context)
1005{
1006	struct raid_set *rs = ti->private;
1007	mddev_t *mddev = &rs->md;
1008
1009	mddev->pers->make_request(mddev, bio);
1010
1011	return DM_MAPIO_SUBMITTED;
1012}
1013
1014static int raid_status(struct dm_target *ti, status_type_t type,
1015		       char *result, unsigned maxlen)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1016{
1017	struct raid_set *rs = ti->private;
1018	unsigned raid_param_cnt = 1; /* at least 1 for chunksize */
1019	unsigned sz = 0;
1020	int i;
1021	sector_t sync;
1022
1023	switch (type) {
1024	case STATUSTYPE_INFO:
1025		DMEMIT("%s %d ", rs->raid_type->name, rs->md.raid_disks);
1026
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1027		for (i = 0; i < rs->md.raid_disks; i++) {
1028			if (test_bit(Faulty, &rs->dev[i].rdev.flags))
1029				DMEMIT("D");
1030			else if (test_bit(In_sync, &rs->dev[i].rdev.flags))
1031				DMEMIT("A");
1032			else
1033				DMEMIT("a");
 
 
1034		}
1035
1036		if (test_bit(MD_RECOVERY_RUNNING, &rs->md.recovery))
1037			sync = rs->md.curr_resync_completed;
1038		else
1039			sync = rs->md.recovery_cp;
1040
1041		if (sync > rs->md.resync_max_sectors)
1042			sync = rs->md.resync_max_sectors;
1043
1044		DMEMIT(" %llu/%llu",
1045		       (unsigned long long) sync,
1046		       (unsigned long long) rs->md.resync_max_sectors);
1047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1048		break;
1049	case STATUSTYPE_TABLE:
1050		/* The string you would use to construct this array */
1051		for (i = 0; i < rs->md.raid_disks; i++) {
1052			if ((rs->print_flags & DMPF_REBUILD) &&
1053			    rs->dev[i].data_dev &&
1054			    !test_bit(In_sync, &rs->dev[i].rdev.flags))
1055				raid_param_cnt += 2; /* for rebuilds */
1056			if (rs->dev[i].data_dev &&
1057			    test_bit(WriteMostly, &rs->dev[i].rdev.flags))
1058				raid_param_cnt += 2;
1059		}
1060
1061		raid_param_cnt += (hweight64(rs->print_flags & ~DMPF_REBUILD) * 2);
1062		if (rs->print_flags & (DMPF_SYNC | DMPF_NOSYNC))
1063			raid_param_cnt--;
1064
1065		DMEMIT("%s %u %u", rs->raid_type->name,
1066		       raid_param_cnt, rs->md.chunk_sectors);
1067
1068		if ((rs->print_flags & DMPF_SYNC) &&
1069		    (rs->md.recovery_cp == MaxSector))
1070			DMEMIT(" sync");
1071		if (rs->print_flags & DMPF_NOSYNC)
1072			DMEMIT(" nosync");
1073
1074		for (i = 0; i < rs->md.raid_disks; i++)
1075			if ((rs->print_flags & DMPF_REBUILD) &&
1076			    rs->dev[i].data_dev &&
1077			    !test_bit(In_sync, &rs->dev[i].rdev.flags))
1078				DMEMIT(" rebuild %u", i);
1079
1080		if (rs->print_flags & DMPF_DAEMON_SLEEP)
1081			DMEMIT(" daemon_sleep %lu",
1082			       rs->md.bitmap_info.daemon_sleep);
1083
1084		if (rs->print_flags & DMPF_MIN_RECOVERY_RATE)
1085			DMEMIT(" min_recovery_rate %d", rs->md.sync_speed_min);
1086
1087		if (rs->print_flags & DMPF_MAX_RECOVERY_RATE)
1088			DMEMIT(" max_recovery_rate %d", rs->md.sync_speed_max);
1089
1090		for (i = 0; i < rs->md.raid_disks; i++)
1091			if (rs->dev[i].data_dev &&
1092			    test_bit(WriteMostly, &rs->dev[i].rdev.flags))
1093				DMEMIT(" write_mostly %u", i);
1094
1095		if (rs->print_flags & DMPF_MAX_WRITE_BEHIND)
1096			DMEMIT(" max_write_behind %lu",
1097			       rs->md.bitmap_info.max_write_behind);
1098
1099		if (rs->print_flags & DMPF_STRIPE_CACHE) {
1100			raid5_conf_t *conf = rs->md.private;
1101
1102			/* convert from kiB to sectors */
1103			DMEMIT(" stripe_cache %d",
1104			       conf ? conf->max_nr_stripes * 2 : 0);
1105		}
1106
1107		if (rs->print_flags & DMPF_REGION_SIZE)
1108			DMEMIT(" region_size %lu",
1109			       rs->md.bitmap_info.chunksize >> 9);
1110
 
 
 
 
 
 
 
 
1111		DMEMIT(" %d", rs->md.raid_disks);
1112		for (i = 0; i < rs->md.raid_disks; i++) {
1113			if (rs->dev[i].meta_dev)
1114				DMEMIT(" %s", rs->dev[i].meta_dev->name);
1115			else
1116				DMEMIT(" -");
1117
1118			if (rs->dev[i].data_dev)
1119				DMEMIT(" %s", rs->dev[i].data_dev->name);
1120			else
1121				DMEMIT(" -");
1122		}
1123	}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1124
1125	return 0;
1126}
1127
1128static int raid_iterate_devices(struct dm_target *ti, iterate_devices_callout_fn fn, void *data)
 
1129{
1130	struct raid_set *rs = ti->private;
1131	unsigned i;
1132	int ret = 0;
1133
1134	for (i = 0; !ret && i < rs->md.raid_disks; i++)
1135		if (rs->dev[i].data_dev)
1136			ret = fn(ti,
1137				 rs->dev[i].data_dev,
1138				 0, /* No offset on data devs */
1139				 rs->md.dev_sectors,
1140				 data);
1141
1142	return ret;
1143}
1144
1145static void raid_io_hints(struct dm_target *ti, struct queue_limits *limits)
1146{
1147	struct raid_set *rs = ti->private;
1148	unsigned chunk_size = rs->md.chunk_sectors << 9;
1149	raid5_conf_t *conf = rs->md.private;
1150
1151	blk_limits_io_min(limits, chunk_size);
1152	blk_limits_io_opt(limits, chunk_size * (conf->raid_disks - conf->max_degraded));
1153}
1154
1155static void raid_presuspend(struct dm_target *ti)
1156{
1157	struct raid_set *rs = ti->private;
1158
1159	md_stop_writes(&rs->md);
1160}
1161
1162static void raid_postsuspend(struct dm_target *ti)
1163{
1164	struct raid_set *rs = ti->private;
1165
1166	mddev_suspend(&rs->md);
1167}
1168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1169static void raid_resume(struct dm_target *ti)
1170{
1171	struct raid_set *rs = ti->private;
1172
1173	bitmap_load(&rs->md);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1174	mddev_resume(&rs->md);
1175}
1176
1177static struct target_type raid_target = {
1178	.name = "raid",
1179	.version = {1, 1, 0},
1180	.module = THIS_MODULE,
1181	.ctr = raid_ctr,
1182	.dtr = raid_dtr,
1183	.map = raid_map,
1184	.status = raid_status,
 
1185	.iterate_devices = raid_iterate_devices,
1186	.io_hints = raid_io_hints,
1187	.presuspend = raid_presuspend,
1188	.postsuspend = raid_postsuspend,
1189	.resume = raid_resume,
1190};
1191
1192static int __init dm_raid_init(void)
1193{
 
 
 
 
1194	return dm_register_target(&raid_target);
1195}
1196
1197static void __exit dm_raid_exit(void)
1198{
1199	dm_unregister_target(&raid_target);
1200}
1201
1202module_init(dm_raid_init);
1203module_exit(dm_raid_exit);
1204
 
 
 
 
1205MODULE_DESCRIPTION(DM_NAME " raid4/5/6 target");
 
 
1206MODULE_ALIAS("dm-raid4");
1207MODULE_ALIAS("dm-raid5");
1208MODULE_ALIAS("dm-raid6");
1209MODULE_AUTHOR("Neil Brown <dm-devel@redhat.com>");
1210MODULE_LICENSE("GPL");
v4.6
   1/*
   2 * Copyright (C) 2010-2011 Neil Brown
   3 * Copyright (C) 2010-2015 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 "raid10.h"
  15#include "bitmap.h"
  16
  17#include <linux/device-mapper.h>
  18
  19#define DM_MSG_PREFIX "raid"
  20#define	MAX_RAID_DEVICES	253 /* raid4/5/6 limit */
  21
  22static bool devices_handle_discard_safely = false;
  23
  24/*
  25 * The following flags are used by dm-raid.c to set up the array state.
  26 * They must be cleared before md_run is called.
  27 */
  28#define FirstUse 10             /* rdev flag */
  29
  30struct raid_dev {
  31	/*
  32	 * Two DM devices, one to hold metadata and one to hold the
  33	 * actual data/parity.  The reason for this is to not confuse
  34	 * ti->len and give more flexibility in altering size and
  35	 * characteristics.
  36	 *
  37	 * While it is possible for this device to be associated
  38	 * with a different physical device than the data_dev, it
  39	 * is intended for it to be the same.
  40	 *    |--------- Physical Device ---------|
  41	 *    |- meta_dev -|------ data_dev ------|
  42	 */
  43	struct dm_dev *meta_dev;
  44	struct dm_dev *data_dev;
  45	struct md_rdev rdev;
  46};
  47
  48/*
  49 * Flags for rs->ctr_flags field.
  50 */
  51#define CTR_FLAG_SYNC              0x1
  52#define CTR_FLAG_NOSYNC            0x2
  53#define CTR_FLAG_REBUILD           0x4
  54#define CTR_FLAG_DAEMON_SLEEP      0x8
  55#define CTR_FLAG_MIN_RECOVERY_RATE 0x10
  56#define CTR_FLAG_MAX_RECOVERY_RATE 0x20
  57#define CTR_FLAG_MAX_WRITE_BEHIND  0x40
  58#define CTR_FLAG_STRIPE_CACHE      0x80
  59#define CTR_FLAG_REGION_SIZE       0x100
  60#define CTR_FLAG_RAID10_COPIES     0x200
  61#define CTR_FLAG_RAID10_FORMAT     0x400
  62
  63struct raid_set {
  64	struct dm_target *ti;
  65
  66	uint32_t bitmap_loaded;
  67	uint32_t ctr_flags;
  68
  69	struct mddev md;
  70	struct raid_type *raid_type;
  71	struct dm_target_callbacks callbacks;
  72
  73	struct raid_dev dev[0];
  74};
  75
  76/* Supported raid types and properties. */
  77static struct raid_type {
  78	const char *name;		/* RAID algorithm. */
  79	const char *descr;		/* Descriptor text for logging. */
  80	const unsigned parity_devs;	/* # of parity devices. */
  81	const unsigned minimal_devs;	/* minimal # of devices in set. */
  82	const unsigned level;		/* RAID level. */
  83	const unsigned algorithm;	/* RAID algorithm. */
  84} raid_types[] = {
  85	{"raid0",    "RAID0 (striping)",                0, 2, 0, 0 /* NONE */},
  86	{"raid1",    "RAID1 (mirroring)",               0, 2, 1, 0 /* NONE */},
  87	{"raid10",   "RAID10 (striped mirrors)",        0, 2, 10, UINT_MAX /* Varies */},
  88	{"raid4",    "RAID4 (dedicated parity disk)",	1, 2, 5, ALGORITHM_PARITY_0},
  89	{"raid5_la", "RAID5 (left asymmetric)",		1, 2, 5, ALGORITHM_LEFT_ASYMMETRIC},
  90	{"raid5_ra", "RAID5 (right asymmetric)",	1, 2, 5, ALGORITHM_RIGHT_ASYMMETRIC},
  91	{"raid5_ls", "RAID5 (left symmetric)",		1, 2, 5, ALGORITHM_LEFT_SYMMETRIC},
  92	{"raid5_rs", "RAID5 (right symmetric)",		1, 2, 5, ALGORITHM_RIGHT_SYMMETRIC},
  93	{"raid6_zr", "RAID6 (zero restart)",		2, 4, 6, ALGORITHM_ROTATING_ZERO_RESTART},
  94	{"raid6_nr", "RAID6 (N restart)",		2, 4, 6, ALGORITHM_ROTATING_N_RESTART},
  95	{"raid6_nc", "RAID6 (N continue)",		2, 4, 6, ALGORITHM_ROTATING_N_CONTINUE}
  96};
  97
  98static char *raid10_md_layout_to_format(int layout)
  99{
 100	/*
 101	 * Bit 16 and 17 stand for "offset" and "use_far_sets"
 102	 * Refer to MD's raid10.c for details
 103	 */
 104	if ((layout & 0x10000) && (layout & 0x20000))
 105		return "offset";
 106
 107	if ((layout & 0xFF) > 1)
 108		return "near";
 109
 110	return "far";
 111}
 112
 113static unsigned raid10_md_layout_to_copies(int layout)
 114{
 115	if ((layout & 0xFF) > 1)
 116		return layout & 0xFF;
 117	return (layout >> 8) & 0xFF;
 118}
 119
 120static int raid10_format_to_md_layout(char *format, unsigned copies)
 121{
 122	unsigned n = 1, f = 1;
 123
 124	if (!strcasecmp("near", format))
 125		n = copies;
 126	else
 127		f = copies;
 128
 129	if (!strcasecmp("offset", format))
 130		return 0x30000 | (f << 8) | n;
 131
 132	if (!strcasecmp("far", format))
 133		return 0x20000 | (f << 8) | n;
 134
 135	return (f << 8) | n;
 136}
 137
 138static struct raid_type *get_raid_type(char *name)
 139{
 140	int i;
 141
 142	for (i = 0; i < ARRAY_SIZE(raid_types); i++)
 143		if (!strcmp(raid_types[i].name, name))
 144			return &raid_types[i];
 145
 146	return NULL;
 147}
 148
 149static struct raid_set *context_alloc(struct dm_target *ti, struct raid_type *raid_type, unsigned raid_devs)
 150{
 151	unsigned i;
 152	struct raid_set *rs;
 
 153
 154	if (raid_devs <= raid_type->parity_devs) {
 155		ti->error = "Insufficient number of devices";
 156		return ERR_PTR(-EINVAL);
 157	}
 158
 
 
 
 
 
 
 
 159	rs = kzalloc(sizeof(*rs) + raid_devs * sizeof(rs->dev[0]), GFP_KERNEL);
 160	if (!rs) {
 161		ti->error = "Cannot allocate raid context";
 162		return ERR_PTR(-ENOMEM);
 163	}
 164
 165	mddev_init(&rs->md);
 166
 167	rs->ti = ti;
 168	rs->raid_type = raid_type;
 169	rs->md.raid_disks = raid_devs;
 170	rs->md.level = raid_type->level;
 171	rs->md.new_level = rs->md.level;
 
 172	rs->md.layout = raid_type->algorithm;
 173	rs->md.new_layout = rs->md.layout;
 174	rs->md.delta_disks = 0;
 175	rs->md.recovery_cp = 0;
 176
 177	for (i = 0; i < raid_devs; i++)
 178		md_rdev_init(&rs->dev[i].rdev);
 179
 180	/*
 181	 * Remaining items to be initialized by further RAID params:
 182	 *  rs->md.persistent
 183	 *  rs->md.external
 184	 *  rs->md.chunk_sectors
 185	 *  rs->md.new_chunk_sectors
 186	 *  rs->md.dev_sectors
 187	 */
 188
 189	return rs;
 190}
 191
 192static void context_free(struct raid_set *rs)
 193{
 194	int i;
 195
 196	for (i = 0; i < rs->md.raid_disks; i++) {
 197		if (rs->dev[i].meta_dev)
 198			dm_put_device(rs->ti, rs->dev[i].meta_dev);
 199		md_rdev_clear(&rs->dev[i].rdev);
 
 
 
 200		if (rs->dev[i].data_dev)
 201			dm_put_device(rs->ti, rs->dev[i].data_dev);
 202	}
 203
 204	kfree(rs);
 205}
 206
 207/*
 208 * For every device we have two words
 209 *  <meta_dev>: meta device name or '-' if missing
 210 *  <data_dev>: data device name or '-' if missing
 211 *
 212 * The following are permitted:
 213 *    - -
 214 *    - <data_dev>
 215 *    <meta_dev> <data_dev>
 216 *
 217 * The following is not allowed:
 218 *    <meta_dev> -
 219 *
 220 * This code parses those words.  If there is a failure,
 221 * the caller must use context_free to unwind the operations.
 222 */
 223static int dev_parms(struct raid_set *rs, char **argv)
 224{
 225	int i;
 226	int rebuild = 0;
 227	int metadata_available = 0;
 228	int ret = 0;
 229
 230	for (i = 0; i < rs->md.raid_disks; i++, argv += 2) {
 231		rs->dev[i].rdev.raid_disk = i;
 232
 233		rs->dev[i].meta_dev = NULL;
 234		rs->dev[i].data_dev = NULL;
 235
 236		/*
 237		 * There are no offsets, since there is a separate device
 238		 * for data and metadata.
 239		 */
 240		rs->dev[i].rdev.data_offset = 0;
 241		rs->dev[i].rdev.mddev = &rs->md;
 242
 243		if (strcmp(argv[0], "-")) {
 244			ret = dm_get_device(rs->ti, argv[0],
 245					    dm_table_get_mode(rs->ti->table),
 246					    &rs->dev[i].meta_dev);
 247			rs->ti->error = "RAID metadata device lookup failure";
 248			if (ret)
 249				return ret;
 250
 251			rs->dev[i].rdev.sb_page = alloc_page(GFP_KERNEL);
 252			if (!rs->dev[i].rdev.sb_page)
 253				return -ENOMEM;
 254		}
 255
 256		if (!strcmp(argv[1], "-")) {
 257			if (!test_bit(In_sync, &rs->dev[i].rdev.flags) &&
 258			    (!rs->dev[i].rdev.recovery_offset)) {
 259				rs->ti->error = "Drive designated for rebuild not specified";
 260				return -EINVAL;
 261			}
 262
 263			rs->ti->error = "No data device supplied with metadata device";
 264			if (rs->dev[i].meta_dev)
 265				return -EINVAL;
 266
 267			continue;
 268		}
 269
 270		ret = dm_get_device(rs->ti, argv[1],
 271				    dm_table_get_mode(rs->ti->table),
 272				    &rs->dev[i].data_dev);
 273		if (ret) {
 274			rs->ti->error = "RAID device lookup failure";
 275			return ret;
 276		}
 277
 278		if (rs->dev[i].meta_dev) {
 279			metadata_available = 1;
 280			rs->dev[i].rdev.meta_bdev = rs->dev[i].meta_dev->bdev;
 281		}
 282		rs->dev[i].rdev.bdev = rs->dev[i].data_dev->bdev;
 283		list_add(&rs->dev[i].rdev.same_set, &rs->md.disks);
 284		if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
 285			rebuild++;
 286	}
 287
 288	if (metadata_available) {
 289		rs->md.external = 0;
 290		rs->md.persistent = 1;
 291		rs->md.major_version = 2;
 292	} else if (rebuild && !rs->md.recovery_cp) {
 293		/*
 294		 * Without metadata, we will not be able to tell if the array
 295		 * is in-sync or not - we must assume it is not.  Therefore,
 296		 * it is impossible to rebuild a drive.
 297		 *
 298		 * Even if there is metadata, the on-disk information may
 299		 * indicate that the array is not in-sync and it will then
 300		 * fail at that time.
 301		 *
 302		 * User could specify 'nosync' option if desperate.
 303		 */
 304		DMERR("Unable to rebuild drive while array is not in-sync");
 305		rs->ti->error = "RAID device lookup failure";
 306		return -EINVAL;
 307	}
 308
 309	return 0;
 310}
 311
 312/*
 313 * validate_region_size
 314 * @rs
 315 * @region_size:  region size in sectors.  If 0, pick a size (4MiB default).
 316 *
 317 * Set rs->md.bitmap_info.chunksize (which really refers to 'region size').
 318 * Ensure that (ti->len/region_size < 2^21) - required by MD bitmap.
 319 *
 320 * Returns: 0 on success, -EINVAL on failure.
 321 */
 322static int validate_region_size(struct raid_set *rs, unsigned long region_size)
 323{
 324	unsigned long min_region_size = rs->ti->len / (1 << 21);
 325
 326	if (!region_size) {
 327		/*
 328		 * Choose a reasonable default.  All figures in sectors.
 329		 */
 330		if (min_region_size > (1 << 13)) {
 331			/* If not a power of 2, make it the next power of 2 */
 332			region_size = roundup_pow_of_two(min_region_size);
 333			DMINFO("Choosing default region size of %lu sectors",
 334			       region_size);
 
 335		} else {
 336			DMINFO("Choosing default region size of 4MiB");
 337			region_size = 1 << 13; /* sectors */
 338		}
 339	} else {
 340		/*
 341		 * Validate user-supplied value.
 342		 */
 343		if (region_size > rs->ti->len) {
 344			rs->ti->error = "Supplied region size is too large";
 345			return -EINVAL;
 346		}
 347
 348		if (region_size < min_region_size) {
 349			DMERR("Supplied region_size (%lu sectors) below minimum (%lu)",
 350			      region_size, min_region_size);
 351			rs->ti->error = "Supplied region size is too small";
 352			return -EINVAL;
 353		}
 354
 355		if (!is_power_of_2(region_size)) {
 356			rs->ti->error = "Region size is not a power of 2";
 357			return -EINVAL;
 358		}
 359
 360		if (region_size < rs->md.chunk_sectors) {
 361			rs->ti->error = "Region size is smaller than the chunk size";
 362			return -EINVAL;
 363		}
 364	}
 365
 366	/*
 367	 * Convert sectors to bytes.
 368	 */
 369	rs->md.bitmap_info.chunksize = (region_size << 9);
 370
 371	return 0;
 372}
 373
 374/*
 375 * validate_raid_redundancy
 376 * @rs
 377 *
 378 * Determine if there are enough devices in the array that haven't
 379 * failed (or are being rebuilt) to form a usable array.
 380 *
 381 * Returns: 0 on success, -EINVAL on failure.
 382 */
 383static int validate_raid_redundancy(struct raid_set *rs)
 384{
 385	unsigned i, rebuild_cnt = 0;
 386	unsigned rebuilds_per_group = 0, copies, d;
 387	unsigned group_size, last_group_start;
 388
 389	for (i = 0; i < rs->md.raid_disks; i++)
 390		if (!test_bit(In_sync, &rs->dev[i].rdev.flags) ||
 391		    !rs->dev[i].rdev.sb_page)
 392			rebuild_cnt++;
 393
 394	switch (rs->raid_type->level) {
 395	case 1:
 396		if (rebuild_cnt >= rs->md.raid_disks)
 397			goto too_many;
 398		break;
 399	case 4:
 400	case 5:
 401	case 6:
 402		if (rebuild_cnt > rs->raid_type->parity_devs)
 403			goto too_many;
 404		break;
 405	case 10:
 406		copies = raid10_md_layout_to_copies(rs->md.layout);
 407		if (rebuild_cnt < copies)
 408			break;
 409
 410		/*
 411		 * It is possible to have a higher rebuild count for RAID10,
 412		 * as long as the failed devices occur in different mirror
 413		 * groups (i.e. different stripes).
 414		 *
 415		 * When checking "near" format, make sure no adjacent devices
 416		 * have failed beyond what can be handled.  In addition to the
 417		 * simple case where the number of devices is a multiple of the
 418		 * number of copies, we must also handle cases where the number
 419		 * of devices is not a multiple of the number of copies.
 420		 * E.g.    dev1 dev2 dev3 dev4 dev5
 421		 *          A    A    B    B    C
 422		 *          C    D    D    E    E
 423		 */
 424		if (!strcmp("near", raid10_md_layout_to_format(rs->md.layout))) {
 425			for (i = 0; i < rs->md.raid_disks * copies; i++) {
 426				if (!(i % copies))
 427					rebuilds_per_group = 0;
 428				d = i % rs->md.raid_disks;
 429				if ((!rs->dev[d].rdev.sb_page ||
 430				     !test_bit(In_sync, &rs->dev[d].rdev.flags)) &&
 431				    (++rebuilds_per_group >= copies))
 432					goto too_many;
 433			}
 434			break;
 435		}
 436
 437		/*
 438		 * When checking "far" and "offset" formats, we need to ensure
 439		 * that the device that holds its copy is not also dead or
 440		 * being rebuilt.  (Note that "far" and "offset" formats only
 441		 * support two copies right now.  These formats also only ever
 442		 * use the 'use_far_sets' variant.)
 443		 *
 444		 * This check is somewhat complicated by the need to account
 445		 * for arrays that are not a multiple of (far) copies.  This
 446		 * results in the need to treat the last (potentially larger)
 447		 * set differently.
 448		 */
 449		group_size = (rs->md.raid_disks / copies);
 450		last_group_start = (rs->md.raid_disks / group_size) - 1;
 451		last_group_start *= group_size;
 452		for (i = 0; i < rs->md.raid_disks; i++) {
 453			if (!(i % copies) && !(i > last_group_start))
 454				rebuilds_per_group = 0;
 455			if ((!rs->dev[i].rdev.sb_page ||
 456			     !test_bit(In_sync, &rs->dev[i].rdev.flags)) &&
 457			    (++rebuilds_per_group >= copies))
 458					goto too_many;
 459		}
 460		break;
 461	default:
 462		if (rebuild_cnt)
 463			return -EINVAL;
 464	}
 465
 466	return 0;
 467
 468too_many:
 469	return -EINVAL;
 470}
 471
 472/*
 473 * Possible arguments are...
 474 *	<chunk_size> [optional_args]
 475 *
 476 * Argument definitions
 477 *    <chunk_size>			The number of sectors per disk that
 478 *                                      will form the "stripe"
 479 *    [[no]sync]			Force or prevent recovery of the
 480 *                                      entire array
 481 *    [rebuild <idx>]			Rebuild the drive indicated by the index
 482 *    [daemon_sleep <ms>]		Time between bitmap daemon work to
 483 *                                      clear bits
 484 *    [min_recovery_rate <kB/sec/disk>]	Throttle RAID initialization
 485 *    [max_recovery_rate <kB/sec/disk>]	Throttle RAID initialization
 486 *    [write_mostly <idx>]		Indicate a write mostly drive via index
 487 *    [max_write_behind <sectors>]	See '-write-behind=' (man mdadm)
 488 *    [stripe_cache <sectors>]		Stripe cache size for higher RAIDs
 489 *    [region_size <sectors>]           Defines granularity of bitmap
 490 *
 491 * RAID10-only options:
 492 *    [raid10_copies <# copies>]        Number of copies.  (Default: 2)
 493 *    [raid10_format <near|far|offset>] Layout algorithm.  (Default: near)
 494 */
 495static int parse_raid_params(struct raid_set *rs, char **argv,
 496			     unsigned num_raid_params)
 497{
 498	char *raid10_format = "near";
 499	unsigned raid10_copies = 2;
 500	unsigned i;
 501	unsigned long value, region_size = 0;
 502	sector_t sectors_per_dev = rs->ti->len;
 503	sector_t max_io_len;
 504	char *key;
 505
 506	/*
 507	 * First, parse the in-order required arguments
 508	 * "chunk_size" is the only argument of this type.
 509	 */
 510	if ((kstrtoul(argv[0], 10, &value) < 0)) {
 511		rs->ti->error = "Bad chunk size";
 512		return -EINVAL;
 513	} else if (rs->raid_type->level == 1) {
 514		if (value)
 515			DMERR("Ignoring chunk size parameter for RAID 1");
 516		value = 0;
 517	} else if (!is_power_of_2(value)) {
 518		rs->ti->error = "Chunk size must be a power of 2";
 519		return -EINVAL;
 520	} else if (value < 8) {
 521		rs->ti->error = "Chunk size value is too small";
 522		return -EINVAL;
 523	}
 524
 525	rs->md.new_chunk_sectors = rs->md.chunk_sectors = value;
 526	argv++;
 527	num_raid_params--;
 528
 529	/*
 530	 * We set each individual device as In_sync with a completed
 531	 * 'recovery_offset'.  If there has been a device failure or
 532	 * replacement then one of the following cases applies:
 533	 *
 534	 *   1) User specifies 'rebuild'.
 535	 *      - Device is reset when param is read.
 536	 *   2) A new device is supplied.
 537	 *      - No matching superblock found, resets device.
 538	 *   3) Device failure was transient and returns on reload.
 539	 *      - Failure noticed, resets device for bitmap replay.
 540	 *   4) Device hadn't completed recovery after previous failure.
 541	 *      - Superblock is read and overrides recovery_offset.
 542	 *
 543	 * What is found in the superblocks of the devices is always
 544	 * authoritative, unless 'rebuild' or '[no]sync' was specified.
 545	 */
 546	for (i = 0; i < rs->md.raid_disks; i++) {
 547		set_bit(In_sync, &rs->dev[i].rdev.flags);
 548		rs->dev[i].rdev.recovery_offset = MaxSector;
 549	}
 550
 551	/*
 552	 * Second, parse the unordered optional arguments
 553	 */
 554	for (i = 0; i < num_raid_params; i++) {
 555		if (!strcasecmp(argv[i], "nosync")) {
 556			rs->md.recovery_cp = MaxSector;
 557			rs->ctr_flags |= CTR_FLAG_NOSYNC;
 558			continue;
 559		}
 560		if (!strcasecmp(argv[i], "sync")) {
 561			rs->md.recovery_cp = 0;
 562			rs->ctr_flags |= CTR_FLAG_SYNC;
 563			continue;
 564		}
 565
 566		/* The rest of the optional arguments come in key/value pairs */
 567		if ((i + 1) >= num_raid_params) {
 568			rs->ti->error = "Wrong number of raid parameters given";
 569			return -EINVAL;
 570		}
 571
 572		key = argv[i++];
 573
 574		/* Parameters that take a string value are checked here. */
 575		if (!strcasecmp(key, "raid10_format")) {
 576			if (rs->raid_type->level != 10) {
 577				rs->ti->error = "'raid10_format' is an invalid parameter for this RAID type";
 578				return -EINVAL;
 579			}
 580			if (strcmp("near", argv[i]) &&
 581			    strcmp("far", argv[i]) &&
 582			    strcmp("offset", argv[i])) {
 583				rs->ti->error = "Invalid 'raid10_format' value given";
 584				return -EINVAL;
 585			}
 586			raid10_format = argv[i];
 587			rs->ctr_flags |= CTR_FLAG_RAID10_FORMAT;
 588			continue;
 589		}
 590
 591		if (kstrtoul(argv[i], 10, &value) < 0) {
 592			rs->ti->error = "Bad numerical argument given in raid params";
 593			return -EINVAL;
 594		}
 595
 596		/* Parameters that take a numeric value are checked here */
 597		if (!strcasecmp(key, "rebuild")) {
 598			if (value >= rs->md.raid_disks) {
 
 
 
 
 
 
 
 
 599				rs->ti->error = "Invalid rebuild index given";
 600				return -EINVAL;
 601			}
 602			clear_bit(In_sync, &rs->dev[value].rdev.flags);
 603			rs->dev[value].rdev.recovery_offset = 0;
 604			rs->ctr_flags |= CTR_FLAG_REBUILD;
 605		} else if (!strcasecmp(key, "write_mostly")) {
 606			if (rs->raid_type->level != 1) {
 607				rs->ti->error = "write_mostly option is only valid for RAID1";
 608				return -EINVAL;
 609			}
 610			if (value >= rs->md.raid_disks) {
 611				rs->ti->error = "Invalid write_mostly drive index given";
 612				return -EINVAL;
 613			}
 614			set_bit(WriteMostly, &rs->dev[value].rdev.flags);
 615		} else if (!strcasecmp(key, "max_write_behind")) {
 616			if (rs->raid_type->level != 1) {
 617				rs->ti->error = "max_write_behind option is only valid for RAID1";
 618				return -EINVAL;
 619			}
 620			rs->ctr_flags |= CTR_FLAG_MAX_WRITE_BEHIND;
 621
 622			/*
 623			 * In device-mapper, we specify things in sectors, but
 624			 * MD records this value in kB
 625			 */
 626			value /= 2;
 627			if (value > COUNTER_MAX) {
 628				rs->ti->error = "Max write-behind limit out of range";
 629				return -EINVAL;
 630			}
 631			rs->md.bitmap_info.max_write_behind = value;
 632		} else if (!strcasecmp(key, "daemon_sleep")) {
 633			rs->ctr_flags |= CTR_FLAG_DAEMON_SLEEP;
 634			if (!value || (value > MAX_SCHEDULE_TIMEOUT)) {
 635				rs->ti->error = "daemon sleep period out of range";
 636				return -EINVAL;
 637			}
 638			rs->md.bitmap_info.daemon_sleep = value;
 639		} else if (!strcasecmp(key, "stripe_cache")) {
 640			rs->ctr_flags |= CTR_FLAG_STRIPE_CACHE;
 641
 642			/*
 643			 * In device-mapper, we specify things in sectors, but
 644			 * MD records this value in kB
 645			 */
 646			value /= 2;
 647
 648			if ((rs->raid_type->level != 5) &&
 649			    (rs->raid_type->level != 6)) {
 650				rs->ti->error = "Inappropriate argument: stripe_cache";
 651				return -EINVAL;
 652			}
 653			if (raid5_set_cache_size(&rs->md, (int)value)) {
 654				rs->ti->error = "Bad stripe_cache size";
 655				return -EINVAL;
 656			}
 657		} else if (!strcasecmp(key, "min_recovery_rate")) {
 658			rs->ctr_flags |= CTR_FLAG_MIN_RECOVERY_RATE;
 659			if (value > INT_MAX) {
 660				rs->ti->error = "min_recovery_rate out of range";
 661				return -EINVAL;
 662			}
 663			rs->md.sync_speed_min = (int)value;
 664		} else if (!strcasecmp(key, "max_recovery_rate")) {
 665			rs->ctr_flags |= CTR_FLAG_MAX_RECOVERY_RATE;
 666			if (value > INT_MAX) {
 667				rs->ti->error = "max_recovery_rate out of range";
 668				return -EINVAL;
 669			}
 670			rs->md.sync_speed_max = (int)value;
 671		} else if (!strcasecmp(key, "region_size")) {
 672			rs->ctr_flags |= CTR_FLAG_REGION_SIZE;
 673			region_size = value;
 674		} else if (!strcasecmp(key, "raid10_copies") &&
 675			   (rs->raid_type->level == 10)) {
 676			if ((value < 2) || (value > 0xFF)) {
 677				rs->ti->error = "Bad value for 'raid10_copies'";
 678				return -EINVAL;
 679			}
 680			rs->ctr_flags |= CTR_FLAG_RAID10_COPIES;
 681			raid10_copies = value;
 682		} else {
 683			DMERR("Unable to parse RAID parameter: %s", key);
 684			rs->ti->error = "Unable to parse RAID parameters";
 685			return -EINVAL;
 686		}
 687	}
 688
 689	if (validate_region_size(rs, region_size))
 690		return -EINVAL;
 691
 692	if (rs->md.chunk_sectors)
 693		max_io_len = rs->md.chunk_sectors;
 694	else
 695		max_io_len = region_size;
 696
 697	if (dm_set_target_max_io_len(rs->ti, max_io_len))
 698		return -EINVAL;
 699
 700	if (rs->raid_type->level == 10) {
 701		if (raid10_copies > rs->md.raid_disks) {
 702			rs->ti->error = "Not enough devices to satisfy specification";
 703			return -EINVAL;
 704		}
 705
 706		/*
 707		 * If the format is not "near", we only support
 708		 * two copies at the moment.
 709		 */
 710		if (strcmp("near", raid10_format) && (raid10_copies > 2)) {
 711			rs->ti->error = "Too many copies for given RAID10 format.";
 712			return -EINVAL;
 713		}
 714
 715		/* (Len * #mirrors) / #devices */
 716		sectors_per_dev = rs->ti->len * raid10_copies;
 717		sector_div(sectors_per_dev, rs->md.raid_disks);
 718
 719		rs->md.layout = raid10_format_to_md_layout(raid10_format,
 720							   raid10_copies);
 721		rs->md.new_layout = rs->md.layout;
 722	} else if ((!rs->raid_type->level || rs->raid_type->level > 1) &&
 723		   sector_div(sectors_per_dev,
 724			      (rs->md.raid_disks - rs->raid_type->parity_devs))) {
 725		rs->ti->error = "Target length not divisible by number of data devices";
 726		return -EINVAL;
 727	}
 728	rs->md.dev_sectors = sectors_per_dev;
 729
 730	/* Assume there are no metadata devices until the drives are parsed */
 731	rs->md.persistent = 0;
 732	rs->md.external = 1;
 733
 734	return 0;
 735}
 736
 737static void do_table_event(struct work_struct *ws)
 738{
 739	struct raid_set *rs = container_of(ws, struct raid_set, md.event_work);
 740
 741	dm_table_event(rs->ti->table);
 742}
 743
 744static int raid_is_congested(struct dm_target_callbacks *cb, int bits)
 745{
 746	struct raid_set *rs = container_of(cb, struct raid_set, callbacks);
 747
 748	return mddev_congested(&rs->md, bits);
 
 
 
 749}
 750
 751/*
 752 * This structure is never routinely used by userspace, unlike md superblocks.
 753 * Devices with this superblock should only ever be accessed via device-mapper.
 754 */
 755#define DM_RAID_MAGIC 0x64526D44
 756struct dm_raid_superblock {
 757	__le32 magic;		/* "DmRd" */
 758	__le32 features;	/* Used to indicate possible future changes */
 759
 760	__le32 num_devices;	/* Number of devices in this array. (Max 64) */
 761	__le32 array_position;	/* The position of this drive in the array */
 762
 763	__le64 events;		/* Incremented by md when superblock updated */
 764	__le64 failed_devices;	/* Bit field of devices to indicate failures */
 765
 766	/*
 767	 * This offset tracks the progress of the repair or replacement of
 768	 * an individual drive.
 769	 */
 770	__le64 disk_recovery_offset;
 771
 772	/*
 773	 * This offset tracks the progress of the initial array
 774	 * synchronisation/parity calculation.
 775	 */
 776	__le64 array_resync_offset;
 777
 778	/*
 779	 * RAID characteristics
 780	 */
 781	__le32 level;
 782	__le32 layout;
 783	__le32 stripe_sectors;
 784
 785	/* Remainder of a logical block is zero-filled when writing (see super_sync()). */
 
 786} __packed;
 787
 788static int read_disk_sb(struct md_rdev *rdev, int size)
 789{
 790	BUG_ON(!rdev->sb_page);
 791
 792	if (rdev->sb_loaded)
 793		return 0;
 794
 795	if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, 1)) {
 796		DMERR("Failed to read superblock of device at position %d",
 797		      rdev->raid_disk);
 798		md_error(rdev->mddev, rdev);
 799		return -EINVAL;
 800	}
 801
 802	rdev->sb_loaded = 1;
 803
 804	return 0;
 805}
 806
 807static void super_sync(struct mddev *mddev, struct md_rdev *rdev)
 808{
 809	int i;
 810	uint64_t failed_devices;
 811	struct dm_raid_superblock *sb;
 812	struct raid_set *rs = container_of(mddev, struct raid_set, md);
 813
 814	sb = page_address(rdev->sb_page);
 815	failed_devices = le64_to_cpu(sb->failed_devices);
 816
 817	for (i = 0; i < mddev->raid_disks; i++)
 818		if (!rs->dev[i].data_dev ||
 819		    test_bit(Faulty, &(rs->dev[i].rdev.flags)))
 820			failed_devices |= (1ULL << i);
 821
 822	memset(sb + 1, 0, rdev->sb_size - sizeof(*sb));
 823
 824	sb->magic = cpu_to_le32(DM_RAID_MAGIC);
 825	sb->features = cpu_to_le32(0);	/* No features yet */
 826
 827	sb->num_devices = cpu_to_le32(mddev->raid_disks);
 828	sb->array_position = cpu_to_le32(rdev->raid_disk);
 829
 830	sb->events = cpu_to_le64(mddev->events);
 831	sb->failed_devices = cpu_to_le64(failed_devices);
 832
 833	sb->disk_recovery_offset = cpu_to_le64(rdev->recovery_offset);
 834	sb->array_resync_offset = cpu_to_le64(mddev->recovery_cp);
 835
 836	sb->level = cpu_to_le32(mddev->level);
 837	sb->layout = cpu_to_le32(mddev->layout);
 838	sb->stripe_sectors = cpu_to_le32(mddev->chunk_sectors);
 839}
 840
 841/*
 842 * super_load
 843 *
 844 * This function creates a superblock if one is not found on the device
 845 * and will decide which superblock to use if there's a choice.
 846 *
 847 * Return: 1 if use rdev, 0 if use refdev, -Exxx otherwise
 848 */
 849static int super_load(struct md_rdev *rdev, struct md_rdev *refdev)
 850{
 851	int ret;
 852	struct dm_raid_superblock *sb;
 853	struct dm_raid_superblock *refsb;
 854	uint64_t events_sb, events_refsb;
 855
 856	rdev->sb_start = 0;
 857	rdev->sb_size = bdev_logical_block_size(rdev->meta_bdev);
 858	if (rdev->sb_size < sizeof(*sb) || rdev->sb_size > PAGE_SIZE) {
 859		DMERR("superblock size of a logical block is no longer valid");
 860		return -EINVAL;
 861	}
 862
 863	ret = read_disk_sb(rdev, rdev->sb_size);
 864	if (ret)
 865		return ret;
 866
 867	sb = page_address(rdev->sb_page);
 868
 869	/*
 870	 * Two cases that we want to write new superblocks and rebuild:
 871	 * 1) New device (no matching magic number)
 872	 * 2) Device specified for rebuild (!In_sync w/ offset == 0)
 873	 */
 874	if ((sb->magic != cpu_to_le32(DM_RAID_MAGIC)) ||
 875	    (!test_bit(In_sync, &rdev->flags) && !rdev->recovery_offset)) {
 876		super_sync(rdev->mddev, rdev);
 877
 878		set_bit(FirstUse, &rdev->flags);
 879
 880		/* Force writing of superblocks to disk */
 881		set_bit(MD_CHANGE_DEVS, &rdev->mddev->flags);
 882
 883		/* Any superblock is better than none, choose that if given */
 884		return refdev ? 0 : 1;
 885	}
 886
 887	if (!refdev)
 888		return 1;
 889
 890	events_sb = le64_to_cpu(sb->events);
 891
 892	refsb = page_address(refdev->sb_page);
 893	events_refsb = le64_to_cpu(refsb->events);
 894
 895	return (events_sb > events_refsb) ? 1 : 0;
 896}
 897
 898static int super_init_validation(struct mddev *mddev, struct md_rdev *rdev)
 899{
 900	int role;
 901	struct raid_set *rs = container_of(mddev, struct raid_set, md);
 902	uint64_t events_sb;
 903	uint64_t failed_devices;
 904	struct dm_raid_superblock *sb;
 905	uint32_t new_devs = 0;
 906	uint32_t rebuilds = 0;
 907	struct md_rdev *r;
 908	struct dm_raid_superblock *sb2;
 909
 910	sb = page_address(rdev->sb_page);
 911	events_sb = le64_to_cpu(sb->events);
 912	failed_devices = le64_to_cpu(sb->failed_devices);
 913
 914	/*
 915	 * Initialise to 1 if this is a new superblock.
 916	 */
 917	mddev->events = events_sb ? : 1;
 918
 919	/*
 920	 * Reshaping is not currently allowed
 921	 */
 922	if (le32_to_cpu(sb->level) != mddev->level) {
 923		DMERR("Reshaping arrays not yet supported. (RAID level change)");
 924		return -EINVAL;
 925	}
 926	if (le32_to_cpu(sb->layout) != mddev->layout) {
 927		DMERR("Reshaping arrays not yet supported. (RAID layout change)");
 928		DMERR("  0x%X vs 0x%X", le32_to_cpu(sb->layout), mddev->layout);
 929		DMERR("  Old layout: %s w/ %d copies",
 930		      raid10_md_layout_to_format(le32_to_cpu(sb->layout)),
 931		      raid10_md_layout_to_copies(le32_to_cpu(sb->layout)));
 932		DMERR("  New layout: %s w/ %d copies",
 933		      raid10_md_layout_to_format(mddev->layout),
 934		      raid10_md_layout_to_copies(mddev->layout));
 935		return -EINVAL;
 936	}
 937	if (le32_to_cpu(sb->stripe_sectors) != mddev->chunk_sectors) {
 938		DMERR("Reshaping arrays not yet supported. (stripe sectors change)");
 939		return -EINVAL;
 940	}
 941
 942	/* We can only change the number of devices in RAID1 right now */
 943	if ((rs->raid_type->level != 1) &&
 944	    (le32_to_cpu(sb->num_devices) != mddev->raid_disks)) {
 945		DMERR("Reshaping arrays not yet supported. (device count change)");
 946		return -EINVAL;
 947	}
 948
 949	if (!(rs->ctr_flags & (CTR_FLAG_SYNC | CTR_FLAG_NOSYNC)))
 950		mddev->recovery_cp = le64_to_cpu(sb->array_resync_offset);
 951
 952	/*
 953	 * During load, we set FirstUse if a new superblock was written.
 954	 * There are two reasons we might not have a superblock:
 955	 * 1) The array is brand new - in which case, all of the
 956	 *    devices must have their In_sync bit set.  Also,
 957	 *    recovery_cp must be 0, unless forced.
 958	 * 2) This is a new device being added to an old array
 959	 *    and the new device needs to be rebuilt - in which
 960	 *    case the In_sync bit will /not/ be set and
 961	 *    recovery_cp must be MaxSector.
 962	 */
 963	rdev_for_each(r, mddev) {
 964		if (!test_bit(In_sync, &r->flags)) {
 965			DMINFO("Device %d specified for rebuild: "
 966			       "Clearing superblock", r->raid_disk);
 
 
 
 967			rebuilds++;
 968		} else if (test_bit(FirstUse, &r->flags))
 969			new_devs++;
 970	}
 971
 972	if (!rebuilds) {
 973		if (new_devs == mddev->raid_disks) {
 974			DMINFO("Superblocks created for new array");
 975			set_bit(MD_ARRAY_FIRST_USE, &mddev->flags);
 976		} else if (new_devs) {
 977			DMERR("New device injected "
 978			      "into existing array without 'rebuild' "
 979			      "parameter specified");
 980			return -EINVAL;
 981		}
 982	} else if (new_devs) {
 983		DMERR("'rebuild' devices cannot be "
 984		      "injected into an array with other first-time devices");
 985		return -EINVAL;
 986	} else if (mddev->recovery_cp != MaxSector) {
 987		DMERR("'rebuild' specified while array is not in-sync");
 988		return -EINVAL;
 989	}
 990
 991	/*
 992	 * Now we set the Faulty bit for those devices that are
 993	 * recorded in the superblock as failed.
 994	 */
 995	rdev_for_each(r, mddev) {
 996		if (!r->sb_page)
 997			continue;
 998		sb2 = page_address(r->sb_page);
 999		sb2->failed_devices = 0;
1000
1001		/*
1002		 * Check for any device re-ordering.
1003		 */
1004		if (!test_bit(FirstUse, &r->flags) && (r->raid_disk >= 0)) {
1005			role = le32_to_cpu(sb2->array_position);
1006			if (role != r->raid_disk) {
1007				if (rs->raid_type->level != 1) {
1008					rs->ti->error = "Cannot change device "
1009						"positions in RAID array";
1010					return -EINVAL;
1011				}
1012				DMINFO("RAID1 device #%d now at position #%d",
1013				       role, r->raid_disk);
1014			}
1015
1016			/*
1017			 * Partial recovery is performed on
1018			 * returning failed devices.
1019			 */
1020			if (failed_devices & (1 << role))
1021				set_bit(Faulty, &r->flags);
1022		}
1023	}
1024
1025	return 0;
1026}
1027
1028static int super_validate(struct raid_set *rs, struct md_rdev *rdev)
1029{
1030	struct mddev *mddev = &rs->md;
1031	struct dm_raid_superblock *sb = page_address(rdev->sb_page);
1032
1033	/*
1034	 * If mddev->events is not set, we know we have not yet initialized
1035	 * the array.
1036	 */
1037	if (!mddev->events && super_init_validation(mddev, rdev))
1038		return -EINVAL;
1039
1040	/* Enable bitmap creation for RAID levels != 0 */
1041	mddev->bitmap_info.offset = (rs->raid_type->level) ? to_sector(4096) : 0;
1042	rdev->mddev->bitmap_info.default_offset = mddev->bitmap_info.offset;
1043
1044	if (!test_bit(FirstUse, &rdev->flags)) {
1045		rdev->recovery_offset = le64_to_cpu(sb->disk_recovery_offset);
1046		if (rdev->recovery_offset != MaxSector)
1047			clear_bit(In_sync, &rdev->flags);
1048	}
1049
1050	/*
1051	 * If a device comes back, set it as not In_sync and no longer faulty.
1052	 */
1053	if (test_bit(Faulty, &rdev->flags)) {
1054		clear_bit(Faulty, &rdev->flags);
1055		clear_bit(In_sync, &rdev->flags);
1056		rdev->saved_raid_disk = rdev->raid_disk;
1057		rdev->recovery_offset = 0;
1058	}
1059
1060	clear_bit(FirstUse, &rdev->flags);
1061
1062	return 0;
1063}
1064
1065/*
1066 * Analyse superblocks and select the freshest.
1067 */
1068static int analyse_superblocks(struct dm_target *ti, struct raid_set *rs)
1069{
1070	int ret;
1071	struct raid_dev *dev;
1072	struct md_rdev *rdev, *tmp, *freshest;
1073	struct mddev *mddev = &rs->md;
1074
1075	freshest = NULL;
1076	rdev_for_each_safe(rdev, tmp, mddev) {
1077		/*
1078		 * Skipping super_load due to CTR_FLAG_SYNC will cause
1079		 * the array to undergo initialization again as
1080		 * though it were new.  This is the intended effect
1081		 * of the "sync" directive.
1082		 *
1083		 * When reshaping capability is added, we must ensure
1084		 * that the "sync" directive is disallowed during the
1085		 * reshape.
1086		 */
1087		rdev->sectors = to_sector(i_size_read(rdev->bdev->bd_inode));
1088
1089		if (rs->ctr_flags & CTR_FLAG_SYNC)
1090			continue;
1091
1092		if (!rdev->meta_bdev)
1093			continue;
1094
1095		ret = super_load(rdev, freshest);
1096
1097		switch (ret) {
1098		case 1:
1099			freshest = rdev;
1100			break;
1101		case 0:
1102			break;
1103		default:
1104			dev = container_of(rdev, struct raid_dev, rdev);
1105			if (dev->meta_dev)
1106				dm_put_device(ti, dev->meta_dev);
1107
1108			dev->meta_dev = NULL;
1109			rdev->meta_bdev = NULL;
1110
1111			if (rdev->sb_page)
1112				put_page(rdev->sb_page);
1113
1114			rdev->sb_page = NULL;
1115
1116			rdev->sb_loaded = 0;
1117
1118			/*
1119			 * We might be able to salvage the data device
1120			 * even though the meta device has failed.  For
1121			 * now, we behave as though '- -' had been
1122			 * set for this device in the table.
1123			 */
1124			if (dev->data_dev)
1125				dm_put_device(ti, dev->data_dev);
1126
1127			dev->data_dev = NULL;
1128			rdev->bdev = NULL;
1129
1130			list_del(&rdev->same_set);
1131		}
1132	}
1133
1134	if (!freshest)
1135		return 0;
1136
1137	if (validate_raid_redundancy(rs)) {
1138		rs->ti->error = "Insufficient redundancy to activate array";
1139		return -EINVAL;
1140	}
1141
1142	/*
1143	 * Validation of the freshest device provides the source of
1144	 * validation for the remaining devices.
1145	 */
1146	ti->error = "Unable to assemble array: Invalid superblocks";
1147	if (super_validate(rs, freshest))
1148		return -EINVAL;
1149
1150	rdev_for_each(rdev, mddev)
1151		if ((rdev != freshest) && super_validate(rs, rdev))
1152			return -EINVAL;
1153
1154	return 0;
1155}
1156
1157/*
1158 * Enable/disable discard support on RAID set depending on
1159 * RAID level and discard properties of underlying RAID members.
1160 */
1161static void configure_discard_support(struct dm_target *ti, struct raid_set *rs)
1162{
1163	int i;
1164	bool raid456;
1165
1166	/* Assume discards not supported until after checks below. */
1167	ti->discards_supported = false;
1168
1169	/* RAID level 4,5,6 require discard_zeroes_data for data integrity! */
1170	raid456 = (rs->md.level == 4 || rs->md.level == 5 || rs->md.level == 6);
1171
1172	for (i = 0; i < rs->md.raid_disks; i++) {
1173		struct request_queue *q;
1174
1175		if (!rs->dev[i].rdev.bdev)
1176			continue;
1177
1178		q = bdev_get_queue(rs->dev[i].rdev.bdev);
1179		if (!q || !blk_queue_discard(q))
1180			return;
1181
1182		if (raid456) {
1183			if (!q->limits.discard_zeroes_data)
1184				return;
1185			if (!devices_handle_discard_safely) {
1186				DMERR("raid456 discard support disabled due to discard_zeroes_data uncertainty.");
1187				DMERR("Set dm-raid.devices_handle_discard_safely=Y to override.");
1188				return;
1189			}
1190		}
1191	}
1192
1193	/* All RAID members properly support discards */
1194	ti->discards_supported = true;
1195
1196	/*
1197	 * RAID1 and RAID10 personalities require bio splitting,
1198	 * RAID0/4/5/6 don't and process large discard bios properly.
1199	 */
1200	ti->split_discard_bios = !!(rs->md.level == 1 || rs->md.level == 10);
1201	ti->num_discard_bios = 1;
1202}
1203
1204/*
1205 * Construct a RAID4/5/6 mapping:
1206 * Args:
1207 *	<raid_type> <#raid_params> <raid_params>		\
1208 *	<#raid_devs> { <meta_dev1> <dev1> .. <meta_devN> <devN> }
1209 *
1210 * <raid_params> varies by <raid_type>.  See 'parse_raid_params' for
1211 * details on possible <raid_params>.
1212 */
1213static int raid_ctr(struct dm_target *ti, unsigned argc, char **argv)
1214{
1215	int ret;
1216	struct raid_type *rt;
1217	unsigned long num_raid_params, num_raid_devs;
1218	struct raid_set *rs = NULL;
1219
1220	/* Must have at least <raid_type> <#raid_params> */
1221	if (argc < 2) {
1222		ti->error = "Too few arguments";
1223		return -EINVAL;
1224	}
1225
1226	/* raid type */
1227	rt = get_raid_type(argv[0]);
1228	if (!rt) {
1229		ti->error = "Unrecognised raid_type";
1230		return -EINVAL;
1231	}
1232	argc--;
1233	argv++;
1234
1235	/* number of RAID parameters */
1236	if (kstrtoul(argv[0], 10, &num_raid_params) < 0) {
1237		ti->error = "Cannot understand number of RAID parameters";
1238		return -EINVAL;
1239	}
1240	argc--;
1241	argv++;
1242
1243	/* Skip over RAID params for now and find out # of devices */
1244	if (num_raid_params >= argc) {
1245		ti->error = "Arguments do not agree with counts given";
1246		return -EINVAL;
1247	}
1248
1249	if ((kstrtoul(argv[num_raid_params], 10, &num_raid_devs) < 0) ||
1250	    (num_raid_devs > MAX_RAID_DEVICES)) {
1251		ti->error = "Cannot understand number of raid devices";
1252		return -EINVAL;
1253	}
1254
1255	argc -= num_raid_params + 1; /* +1: we already have num_raid_devs */
1256	if (argc != (num_raid_devs * 2)) {
1257		ti->error = "Supplied RAID devices does not match the count given";
1258		return -EINVAL;
1259	}
1260
1261	rs = context_alloc(ti, rt, (unsigned)num_raid_devs);
1262	if (IS_ERR(rs))
1263		return PTR_ERR(rs);
1264
1265	ret = parse_raid_params(rs, argv, (unsigned)num_raid_params);
1266	if (ret)
1267		goto bad;
1268
 
 
 
1269	argv += num_raid_params + 1;
1270
 
 
 
 
 
1271	ret = dev_parms(rs, argv);
1272	if (ret)
1273		goto bad;
1274
1275	rs->md.sync_super = super_sync;
1276	ret = analyse_superblocks(ti, rs);
1277	if (ret)
1278		goto bad;
1279
1280	INIT_WORK(&rs->md.event_work, do_table_event);
1281	ti->private = rs;
1282	ti->num_flush_bios = 1;
1283
1284	/*
1285	 * Disable/enable discard support on RAID set.
1286	 */
1287	configure_discard_support(ti, rs);
1288
1289	/* Has to be held on running the array */
1290	mddev_lock_nointr(&rs->md);
1291	ret = md_run(&rs->md);
1292	rs->md.in_sync = 0; /* Assume already marked dirty */
1293	mddev_unlock(&rs->md);
1294
1295	if (ret) {
1296		ti->error = "Fail to run raid array";
1297		goto bad;
1298	}
1299
1300	if (ti->len != rs->md.array_sectors) {
1301		ti->error = "Array size does not match requested target length";
1302		ret = -EINVAL;
1303		goto size_mismatch;
1304	}
1305	rs->callbacks.congested_fn = raid_is_congested;
1306	dm_table_add_target_callbacks(ti->table, &rs->callbacks);
1307
1308	mddev_suspend(&rs->md);
1309	return 0;
1310
1311size_mismatch:
1312	md_stop(&rs->md);
1313bad:
1314	context_free(rs);
1315
1316	return ret;
1317}
1318
1319static void raid_dtr(struct dm_target *ti)
1320{
1321	struct raid_set *rs = ti->private;
1322
1323	list_del_init(&rs->callbacks.list);
1324	md_stop(&rs->md);
1325	context_free(rs);
1326}
1327
1328static int raid_map(struct dm_target *ti, struct bio *bio)
1329{
1330	struct raid_set *rs = ti->private;
1331	struct mddev *mddev = &rs->md;
1332
1333	mddev->pers->make_request(mddev, bio);
1334
1335	return DM_MAPIO_SUBMITTED;
1336}
1337
1338static const char *decipher_sync_action(struct mddev *mddev)
1339{
1340	if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
1341		return "frozen";
1342
1343	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
1344	    (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
1345		if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
1346			return "reshape";
1347
1348		if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
1349			if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
1350				return "resync";
1351			else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
1352				return "check";
1353			return "repair";
1354		}
1355
1356		if (test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
1357			return "recover";
1358	}
1359
1360	return "idle";
1361}
1362
1363static void raid_status(struct dm_target *ti, status_type_t type,
1364			unsigned status_flags, char *result, unsigned maxlen)
1365{
1366	struct raid_set *rs = ti->private;
1367	unsigned raid_param_cnt = 1; /* at least 1 for chunksize */
1368	unsigned sz = 0;
1369	int i, array_in_sync = 0;
1370	sector_t sync;
1371
1372	switch (type) {
1373	case STATUSTYPE_INFO:
1374		DMEMIT("%s %d ", rs->raid_type->name, rs->md.raid_disks);
1375
1376		if (rs->raid_type->level) {
1377			if (test_bit(MD_RECOVERY_RUNNING, &rs->md.recovery))
1378				sync = rs->md.curr_resync_completed;
1379			else
1380				sync = rs->md.recovery_cp;
1381
1382			if (sync >= rs->md.resync_max_sectors) {
1383				/*
1384				 * Sync complete.
1385				 */
1386				array_in_sync = 1;
1387				sync = rs->md.resync_max_sectors;
1388			} else if (test_bit(MD_RECOVERY_REQUESTED, &rs->md.recovery)) {
1389				/*
1390				 * If "check" or "repair" is occurring, the array has
1391				 * undergone and initial sync and the health characters
1392				 * should not be 'a' anymore.
1393				 */
1394				array_in_sync = 1;
1395			} else {
1396				/*
1397				 * The array may be doing an initial sync, or it may
1398				 * be rebuilding individual components.  If all the
1399				 * devices are In_sync, then it is the array that is
1400				 * being initialized.
1401				 */
1402				for (i = 0; i < rs->md.raid_disks; i++)
1403					if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
1404						array_in_sync = 1;
1405			}
1406		} else {
1407			/* RAID0 */
1408			array_in_sync = 1;
1409			sync = rs->md.resync_max_sectors;
1410		}
1411
1412		/*
1413		 * Status characters:
1414		 *  'D' = Dead/Failed device
1415		 *  'a' = Alive but not in-sync
1416		 *  'A' = Alive and in-sync
1417		 */
1418		for (i = 0; i < rs->md.raid_disks; i++) {
1419			if (test_bit(Faulty, &rs->dev[i].rdev.flags))
1420				DMEMIT("D");
1421			else if (!array_in_sync ||
1422				 !test_bit(In_sync, &rs->dev[i].rdev.flags))
 
1423				DMEMIT("a");
1424			else
1425				DMEMIT("A");
1426		}
1427
1428		/*
1429		 * In-sync ratio:
1430		 *  The in-sync ratio shows the progress of:
1431		 *   - Initializing the array
1432		 *   - Rebuilding a subset of devices of the array
1433		 *  The user can distinguish between the two by referring
1434		 *  to the status characters.
1435		 */
1436		DMEMIT(" %llu/%llu",
1437		       (unsigned long long) sync,
1438		       (unsigned long long) rs->md.resync_max_sectors);
1439
1440		/*
1441		 * Sync action:
1442		 *   See Documentation/device-mapper/dm-raid.c for
1443		 *   information on each of these states.
1444		 */
1445		DMEMIT(" %s", decipher_sync_action(&rs->md));
1446
1447		/*
1448		 * resync_mismatches/mismatch_cnt
1449		 *   This field shows the number of discrepancies found when
1450		 *   performing a "check" of the array.
1451		 */
1452		DMEMIT(" %llu",
1453		       (strcmp(rs->md.last_sync_action, "check")) ? 0 :
1454		       (unsigned long long)
1455		       atomic64_read(&rs->md.resync_mismatches));
1456		break;
1457	case STATUSTYPE_TABLE:
1458		/* The string you would use to construct this array */
1459		for (i = 0; i < rs->md.raid_disks; i++) {
1460			if ((rs->ctr_flags & CTR_FLAG_REBUILD) &&
1461			    rs->dev[i].data_dev &&
1462			    !test_bit(In_sync, &rs->dev[i].rdev.flags))
1463				raid_param_cnt += 2; /* for rebuilds */
1464			if (rs->dev[i].data_dev &&
1465			    test_bit(WriteMostly, &rs->dev[i].rdev.flags))
1466				raid_param_cnt += 2;
1467		}
1468
1469		raid_param_cnt += (hweight32(rs->ctr_flags & ~CTR_FLAG_REBUILD) * 2);
1470		if (rs->ctr_flags & (CTR_FLAG_SYNC | CTR_FLAG_NOSYNC))
1471			raid_param_cnt--;
1472
1473		DMEMIT("%s %u %u", rs->raid_type->name,
1474		       raid_param_cnt, rs->md.chunk_sectors);
1475
1476		if ((rs->ctr_flags & CTR_FLAG_SYNC) &&
1477		    (rs->md.recovery_cp == MaxSector))
1478			DMEMIT(" sync");
1479		if (rs->ctr_flags & CTR_FLAG_NOSYNC)
1480			DMEMIT(" nosync");
1481
1482		for (i = 0; i < rs->md.raid_disks; i++)
1483			if ((rs->ctr_flags & CTR_FLAG_REBUILD) &&
1484			    rs->dev[i].data_dev &&
1485			    !test_bit(In_sync, &rs->dev[i].rdev.flags))
1486				DMEMIT(" rebuild %u", i);
1487
1488		if (rs->ctr_flags & CTR_FLAG_DAEMON_SLEEP)
1489			DMEMIT(" daemon_sleep %lu",
1490			       rs->md.bitmap_info.daemon_sleep);
1491
1492		if (rs->ctr_flags & CTR_FLAG_MIN_RECOVERY_RATE)
1493			DMEMIT(" min_recovery_rate %d", rs->md.sync_speed_min);
1494
1495		if (rs->ctr_flags & CTR_FLAG_MAX_RECOVERY_RATE)
1496			DMEMIT(" max_recovery_rate %d", rs->md.sync_speed_max);
1497
1498		for (i = 0; i < rs->md.raid_disks; i++)
1499			if (rs->dev[i].data_dev &&
1500			    test_bit(WriteMostly, &rs->dev[i].rdev.flags))
1501				DMEMIT(" write_mostly %u", i);
1502
1503		if (rs->ctr_flags & CTR_FLAG_MAX_WRITE_BEHIND)
1504			DMEMIT(" max_write_behind %lu",
1505			       rs->md.bitmap_info.max_write_behind);
1506
1507		if (rs->ctr_flags & CTR_FLAG_STRIPE_CACHE) {
1508			struct r5conf *conf = rs->md.private;
1509
1510			/* convert from kiB to sectors */
1511			DMEMIT(" stripe_cache %d",
1512			       conf ? conf->max_nr_stripes * 2 : 0);
1513		}
1514
1515		if (rs->ctr_flags & CTR_FLAG_REGION_SIZE)
1516			DMEMIT(" region_size %lu",
1517			       rs->md.bitmap_info.chunksize >> 9);
1518
1519		if (rs->ctr_flags & CTR_FLAG_RAID10_COPIES)
1520			DMEMIT(" raid10_copies %u",
1521			       raid10_md_layout_to_copies(rs->md.layout));
1522
1523		if (rs->ctr_flags & CTR_FLAG_RAID10_FORMAT)
1524			DMEMIT(" raid10_format %s",
1525			       raid10_md_layout_to_format(rs->md.layout));
1526
1527		DMEMIT(" %d", rs->md.raid_disks);
1528		for (i = 0; i < rs->md.raid_disks; i++) {
1529			if (rs->dev[i].meta_dev)
1530				DMEMIT(" %s", rs->dev[i].meta_dev->name);
1531			else
1532				DMEMIT(" -");
1533
1534			if (rs->dev[i].data_dev)
1535				DMEMIT(" %s", rs->dev[i].data_dev->name);
1536			else
1537				DMEMIT(" -");
1538		}
1539	}
1540}
1541
1542static int raid_message(struct dm_target *ti, unsigned argc, char **argv)
1543{
1544	struct raid_set *rs = ti->private;
1545	struct mddev *mddev = &rs->md;
1546
1547	if (!strcasecmp(argv[0], "reshape")) {
1548		DMERR("Reshape not supported.");
1549		return -EINVAL;
1550	}
1551
1552	if (!mddev->pers || !mddev->pers->sync_request)
1553		return -EINVAL;
1554
1555	if (!strcasecmp(argv[0], "frozen"))
1556		set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
1557	else
1558		clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
1559
1560	if (!strcasecmp(argv[0], "idle") || !strcasecmp(argv[0], "frozen")) {
1561		if (mddev->sync_thread) {
1562			set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1563			md_reap_sync_thread(mddev);
1564		}
1565	} else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
1566		   test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
1567		return -EBUSY;
1568	else if (!strcasecmp(argv[0], "resync"))
1569		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
1570	else if (!strcasecmp(argv[0], "recover")) {
1571		set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
1572		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
1573	} else {
1574		if (!strcasecmp(argv[0], "check"))
1575			set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
1576		else if (!!strcasecmp(argv[0], "repair"))
1577			return -EINVAL;
1578		set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
1579		set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
1580	}
1581	if (mddev->ro == 2) {
1582		/* A write to sync_action is enough to justify
1583		 * canceling read-auto mode
1584		 */
1585		mddev->ro = 0;
1586		if (!mddev->suspended)
1587			md_wakeup_thread(mddev->sync_thread);
1588	}
1589	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
1590	if (!mddev->suspended)
1591		md_wakeup_thread(mddev->thread);
1592
1593	return 0;
1594}
1595
1596static int raid_iterate_devices(struct dm_target *ti,
1597				iterate_devices_callout_fn fn, void *data)
1598{
1599	struct raid_set *rs = ti->private;
1600	unsigned i;
1601	int ret = 0;
1602
1603	for (i = 0; !ret && i < rs->md.raid_disks; i++)
1604		if (rs->dev[i].data_dev)
1605			ret = fn(ti,
1606				 rs->dev[i].data_dev,
1607				 0, /* No offset on data devs */
1608				 rs->md.dev_sectors,
1609				 data);
1610
1611	return ret;
1612}
1613
1614static void raid_io_hints(struct dm_target *ti, struct queue_limits *limits)
1615{
1616	struct raid_set *rs = ti->private;
1617	unsigned chunk_size = rs->md.chunk_sectors << 9;
1618	struct r5conf *conf = rs->md.private;
1619
1620	blk_limits_io_min(limits, chunk_size);
1621	blk_limits_io_opt(limits, chunk_size * (conf->raid_disks - conf->max_degraded));
1622}
1623
1624static void raid_presuspend(struct dm_target *ti)
1625{
1626	struct raid_set *rs = ti->private;
1627
1628	md_stop_writes(&rs->md);
1629}
1630
1631static void raid_postsuspend(struct dm_target *ti)
1632{
1633	struct raid_set *rs = ti->private;
1634
1635	mddev_suspend(&rs->md);
1636}
1637
1638static void attempt_restore_of_faulty_devices(struct raid_set *rs)
1639{
1640	int i;
1641	uint64_t failed_devices, cleared_failed_devices = 0;
1642	unsigned long flags;
1643	struct dm_raid_superblock *sb;
1644	struct md_rdev *r;
1645
1646	for (i = 0; i < rs->md.raid_disks; i++) {
1647		r = &rs->dev[i].rdev;
1648		if (test_bit(Faulty, &r->flags) && r->sb_page &&
1649		    sync_page_io(r, 0, r->sb_size, r->sb_page, READ, 1)) {
1650			DMINFO("Faulty %s device #%d has readable super block."
1651			       "  Attempting to revive it.",
1652			       rs->raid_type->name, i);
1653
1654			/*
1655			 * Faulty bit may be set, but sometimes the array can
1656			 * be suspended before the personalities can respond
1657			 * by removing the device from the array (i.e. calling
1658			 * 'hot_remove_disk').  If they haven't yet removed
1659			 * the failed device, its 'raid_disk' number will be
1660			 * '>= 0' - meaning we must call this function
1661			 * ourselves.
1662			 */
1663			if ((r->raid_disk >= 0) &&
1664			    (r->mddev->pers->hot_remove_disk(r->mddev, r) != 0))
1665				/* Failed to revive this device, try next */
1666				continue;
1667
1668			r->raid_disk = i;
1669			r->saved_raid_disk = i;
1670			flags = r->flags;
1671			clear_bit(Faulty, &r->flags);
1672			clear_bit(WriteErrorSeen, &r->flags);
1673			clear_bit(In_sync, &r->flags);
1674			if (r->mddev->pers->hot_add_disk(r->mddev, r)) {
1675				r->raid_disk = -1;
1676				r->saved_raid_disk = -1;
1677				r->flags = flags;
1678			} else {
1679				r->recovery_offset = 0;
1680				cleared_failed_devices |= 1 << i;
1681			}
1682		}
1683	}
1684	if (cleared_failed_devices) {
1685		rdev_for_each(r, &rs->md) {
1686			sb = page_address(r->sb_page);
1687			failed_devices = le64_to_cpu(sb->failed_devices);
1688			failed_devices &= ~cleared_failed_devices;
1689			sb->failed_devices = cpu_to_le64(failed_devices);
1690		}
1691	}
1692}
1693
1694static void raid_resume(struct dm_target *ti)
1695{
1696	struct raid_set *rs = ti->private;
1697
1698	if (rs->raid_type->level) {
1699		set_bit(MD_CHANGE_DEVS, &rs->md.flags);
1700
1701		if (!rs->bitmap_loaded) {
1702			bitmap_load(&rs->md);
1703			rs->bitmap_loaded = 1;
1704		} else {
1705			/*
1706			 * A secondary resume while the device is active.
1707			 * Take this opportunity to check whether any failed
1708			 * devices are reachable again.
1709			 */
1710			attempt_restore_of_faulty_devices(rs);
1711		}
1712
1713		clear_bit(MD_RECOVERY_FROZEN, &rs->md.recovery);
1714	}
1715
1716	mddev_resume(&rs->md);
1717}
1718
1719static struct target_type raid_target = {
1720	.name = "raid",
1721	.version = {1, 7, 0},
1722	.module = THIS_MODULE,
1723	.ctr = raid_ctr,
1724	.dtr = raid_dtr,
1725	.map = raid_map,
1726	.status = raid_status,
1727	.message = raid_message,
1728	.iterate_devices = raid_iterate_devices,
1729	.io_hints = raid_io_hints,
1730	.presuspend = raid_presuspend,
1731	.postsuspend = raid_postsuspend,
1732	.resume = raid_resume,
1733};
1734
1735static int __init dm_raid_init(void)
1736{
1737	DMINFO("Loading target version %u.%u.%u",
1738	       raid_target.version[0],
1739	       raid_target.version[1],
1740	       raid_target.version[2]);
1741	return dm_register_target(&raid_target);
1742}
1743
1744static void __exit dm_raid_exit(void)
1745{
1746	dm_unregister_target(&raid_target);
1747}
1748
1749module_init(dm_raid_init);
1750module_exit(dm_raid_exit);
1751
1752module_param(devices_handle_discard_safely, bool, 0644);
1753MODULE_PARM_DESC(devices_handle_discard_safely,
1754		 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
1755
1756MODULE_DESCRIPTION(DM_NAME " raid4/5/6 target");
1757MODULE_ALIAS("dm-raid1");
1758MODULE_ALIAS("dm-raid10");
1759MODULE_ALIAS("dm-raid4");
1760MODULE_ALIAS("dm-raid5");
1761MODULE_ALIAS("dm-raid6");
1762MODULE_AUTHOR("Neil Brown <dm-devel@redhat.com>");
1763MODULE_LICENSE("GPL");