dm raid: add new reshaping/raid10 format table line options to parameter parser
[cascardo/linux.git] / drivers / md / dm-raid.c
1 /*
2  * Copyright (C) 2010-2011 Neil Brown
3  * Copyright (C) 2010-2016 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 /* md-raid kernel limit */
21
22 static 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
30 struct 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  * 1 = no flag value
52  * 2 = flag with value
53  */
54 #define CTR_FLAG_SYNC              0x1   /* 1 */ /* Not with raid0! */
55 #define CTR_FLAG_NOSYNC            0x2   /* 1 */ /* Not with raid0! */
56 #define CTR_FLAG_REBUILD           0x4   /* 2 */ /* Not with raid0! */
57 #define CTR_FLAG_DAEMON_SLEEP      0x8   /* 2 */ /* Not with raid0! */
58 #define CTR_FLAG_MIN_RECOVERY_RATE 0x10  /* 2 */ /* Not with raid0! */
59 #define CTR_FLAG_MAX_RECOVERY_RATE 0x20  /* 2 */ /* Not with raid0! */
60 #define CTR_FLAG_MAX_WRITE_BEHIND  0x40  /* 2 */ /* Only with raid1! */
61 #define CTR_FLAG_WRITE_MOSTLY      0x80  /* 2 */ /* Only with raid1! */
62 #define CTR_FLAG_STRIPE_CACHE      0x100 /* 2 */ /* Only with raid4/5/6! */
63 #define CTR_FLAG_REGION_SIZE       0x200 /* 2 */ /* Not with raid0! */
64 #define CTR_FLAG_RAID10_COPIES     0x400 /* 2 */ /* Only with raid10 */
65 #define CTR_FLAG_RAID10_FORMAT     0x800 /* 2 */ /* Only with raid10 */
66 /* New for v1.8.0 */
67 #define CTR_FLAG_DELTA_DISKS          0x1000 /* 2 */ /* Only with reshapable raid4/5/6/10! */
68 #define CTR_FLAG_DATA_OFFSET          0x2000 /* 2 */ /* Only with reshapable raid4/5/6/10! */
69 #define CTR_FLAG_RAID10_USE_NEAR_SETS 0x4000 /* 2 */ /* Only with raid10! */
70
71 /*
72  * Definitions of various constructor flags to
73  * be used in checks of valid / invalid flags
74  * per raid level.
75  */
76 /* Define all any sync flags */
77 #define CTR_FLAGS_ANY_SYNC              (CTR_FLAG_SYNC | CTR_FLAG_NOSYNC)
78
79 /* Define flags for options without argument (e.g. 'nosync') */
80 #define CTR_FLAG_OPTIONS_NO_ARGS        (CTR_FLAGS_ANY_SYNC | \
81                                          CTR_FLAG_RAID10_USE_NEAR_SETS)
82
83 /* Define flags for options with one argument (e.g. 'delta_disks +2') */
84 #define CTR_FLAG_OPTIONS_ONE_ARG (CTR_FLAG_REBUILD | \
85                                   CTR_FLAG_WRITE_MOSTLY | \
86                                   CTR_FLAG_DAEMON_SLEEP | \
87                                   CTR_FLAG_MIN_RECOVERY_RATE | \
88                                   CTR_FLAG_MAX_RECOVERY_RATE | \
89                                   CTR_FLAG_MAX_WRITE_BEHIND | \
90                                   CTR_FLAG_STRIPE_CACHE | \
91                                   CTR_FLAG_REGION_SIZE | \
92                                   CTR_FLAG_RAID10_COPIES | \
93                                   CTR_FLAG_RAID10_FORMAT | \
94                                   CTR_FLAG_DELTA_DISKS | \
95                                   CTR_FLAG_DATA_OFFSET)
96
97 /* All ctr optional arguments */
98 #define ALL_CTR_FLAGS           (CTR_FLAG_OPTIONS_NO_ARGS | \
99                                  CTR_FLAG_OPTIONS_ONE_ARG)
100
101 /* Invalid options definitions per raid level... */
102
103 /* "raid0" does not accept any options */
104 #define RAID0_INVALID_FLAGS ALL_CTR_FLAGS
105
106 /* "raid1" does not accept stripe cache or any raid10 options */
107 #define RAID1_INVALID_FLAGS     (CTR_FLAG_STRIPE_CACHE | \
108                                  CTR_FLAG_RAID10_COPIES | \
109                                  CTR_FLAG_RAID10_FORMAT | \
110                                  CTR_FLAG_DELTA_DISKS | \
111                                  CTR_FLAG_DATA_OFFSET)
112
113 /* "raid10" does not accept any raid1 or stripe cache options */
114 #define RAID10_INVALID_FLAGS    (CTR_FLAG_WRITE_MOSTLY | \
115                                  CTR_FLAG_MAX_WRITE_BEHIND | \
116                                  CTR_FLAG_STRIPE_CACHE)
117 /*
118  * "raid4/5/6" do not accept any raid1 or raid10 specific options
119  *
120  * "raid6" does not accept "nosync", because it is not guaranteed
121  * that both parity and q-syndrome are being written properly with
122  * any writes
123  */
124 #define RAID45_INVALID_FLAGS    (CTR_FLAG_WRITE_MOSTLY | \
125                                  CTR_FLAG_MAX_WRITE_BEHIND | \
126                                  CTR_FLAG_RAID10_FORMAT | \
127                                  CTR_FLAG_RAID10_COPIES | \
128                                  CTR_FLAG_RAID10_USE_NEAR_SETS)
129 #define RAID6_INVALID_FLAGS     (CTR_FLAG_NOSYNC | RAID45_INVALID_FLAGS)
130 /* ...invalid options definitions per raid level */
131
132 /* Array elements of 64 bit needed for rebuild/write_mostly bits */
133 #define DISKS_ARRAY_ELEMS ((MAX_RAID_DEVICES + (sizeof(uint64_t) * 8 - 1)) / sizeof(uint64_t) / 8)
134
135 struct raid_set {
136         struct dm_target *ti;
137
138         uint32_t bitmap_loaded;
139         uint32_t ctr_flags;
140
141         int raid_disks;
142         int delta_disks;
143         int data_offset;
144         int raid10_copies;
145
146         struct mddev md;
147         struct raid_type *raid_type;
148         struct dm_target_callbacks callbacks;
149
150         struct raid_dev dev[0];
151 };
152
153 /* raid10 algorithms (i.e. formats) */
154 #define ALGORITHM_RAID10_DEFAULT        0
155 #define ALGORITHM_RAID10_NEAR           1
156 #define ALGORITHM_RAID10_OFFSET         2
157 #define ALGORITHM_RAID10_FAR            3
158
159 /* Supported raid types and properties. */
160 static struct raid_type {
161         const char *name;               /* RAID algorithm. */
162         const char *descr;              /* Descriptor text for logging. */
163         const unsigned parity_devs;     /* # of parity devices. */
164         const unsigned minimal_devs;    /* minimal # of devices in set. */
165         const unsigned level;           /* RAID level. */
166         const unsigned algorithm;       /* RAID algorithm. */
167 } raid_types[] = {
168         {"raid0",         "raid0 (striping)",                       0, 2, 0,  0 /* NONE */},
169         {"raid1",         "raid1 (mirroring)",                      0, 2, 1,  0 /* NONE */},
170         {"raid10_far",    "raid10 far (striped mirrors)",           0, 2, 10, ALGORITHM_RAID10_FAR},
171         {"raid10_offset", "raid10 offset (striped mirrors)",        0, 2, 10, ALGORITHM_RAID10_OFFSET},
172         {"raid10_near",   "raid10 near (striped mirrors)",          0, 2, 10, ALGORITHM_RAID10_NEAR},
173         {"raid10",        "raid10 (striped mirrors)",               0, 2, 10, ALGORITHM_RAID10_DEFAULT},
174         {"raid4",         "raid4 (dedicated last parity disk)",     1, 2, 4,  ALGORITHM_PARITY_N}, /* raid4 layout = raid5_n */
175         {"raid5_n",       "raid5 (dedicated last parity disk)",     1, 2, 5,  ALGORITHM_PARITY_N},
176         {"raid5_ls",      "raid5 (left symmetric)",                 1, 2, 5,  ALGORITHM_LEFT_SYMMETRIC},
177         {"raid5_rs",      "raid5 (right symmetric)",                1, 2, 5,  ALGORITHM_RIGHT_SYMMETRIC},
178         {"raid5_la",      "raid5 (left asymmetric)",                1, 2, 5,  ALGORITHM_LEFT_ASYMMETRIC},
179         {"raid5_ra",      "raid5 (right asymmetric)",               1, 2, 5,  ALGORITHM_RIGHT_ASYMMETRIC},
180         {"raid6_zr",      "raid6 (zero restart)",                   2, 4, 6,  ALGORITHM_ROTATING_ZERO_RESTART},
181         {"raid6_nr",      "raid6 (N restart)",                      2, 4, 6,  ALGORITHM_ROTATING_N_RESTART},
182         {"raid6_nc",      "raid6 (N continue)",                     2, 4, 6,  ALGORITHM_ROTATING_N_CONTINUE},
183         {"raid6_n_6",     "raid6 (dedicated parity/Q n/6)",         2, 4, 6,  ALGORITHM_PARITY_N_6},
184         {"raid6_ls_6",    "raid6 (left symmetric dedicated Q 6)",   2, 4, 6,  ALGORITHM_LEFT_SYMMETRIC_6},
185         {"raid6_rs_6",    "raid6 (right symmetric dedicated Q 6)",  2, 4, 6,  ALGORITHM_RIGHT_SYMMETRIC_6},
186         {"raid6_la_6",    "raid6 (left asymmetric dedicated Q 6)",  2, 4, 6,  ALGORITHM_LEFT_ASYMMETRIC_6},
187         {"raid6_ra_6",    "raid6 (right asymmetric dedicated Q 6)", 2, 4, 6,  ALGORITHM_RIGHT_ASYMMETRIC_6}
188 };
189
190 /* True, if @v is in inclusive range [@min, @max] */
191 static bool _in_range(long v, long min, long max)
192 {
193         return v >= min && v <= max;
194 }
195
196 /* ctr flag bit manipulation... */
197 /* Set single @flag in @flags */
198 static void _set_flag(uint32_t flag, uint32_t *flags)
199 {
200         WARN_ON_ONCE(hweight32(flag) != 1);
201         *flags |= flag;
202 }
203
204 /* Test single @flag in @flags */
205 static bool _test_flag(uint32_t flag, uint32_t flags)
206 {
207         WARN_ON_ONCE(hweight32(flag) != 1);
208         return (flag & flags) ? true : false;
209 }
210
211 /* Test multiple @flags in @all_flags */
212 static bool _test_flags(uint32_t flags, uint32_t all_flags)
213 {
214         return (flags & all_flags) ? true : false;
215 }
216
217 /* Return true if single @flag is set in @*flags, else set it and return false */
218 static bool _test_and_set_flag(uint32_t flag, uint32_t *flags)
219 {
220         if (_test_flag(flag, *flags))
221                 return true;
222
223         _set_flag(flag, flags);
224         return false;
225 }
226 /* ...ctr and runtime flag bit manipulation */
227
228 /* All table line arguments are defined here */
229 static struct arg_name_flag {
230         const uint32_t flag;
231         const char *name;
232 } _arg_name_flags[] = {
233         { CTR_FLAG_SYNC, "sync"},
234         { CTR_FLAG_NOSYNC, "nosync"},
235         { CTR_FLAG_REBUILD, "rebuild"},
236         { CTR_FLAG_DAEMON_SLEEP, "daemon_sleep"},
237         { CTR_FLAG_MIN_RECOVERY_RATE, "min_recovery_rate"},
238         { CTR_FLAG_MAX_RECOVERY_RATE, "max_recovery_rate"},
239         { CTR_FLAG_MAX_WRITE_BEHIND, "max_write_behind"},
240         { CTR_FLAG_WRITE_MOSTLY, "writemostly"},
241         { CTR_FLAG_STRIPE_CACHE, "stripe_cache"},
242         { CTR_FLAG_REGION_SIZE, "region_size"},
243         { CTR_FLAG_RAID10_COPIES, "raid10_copies"},
244         { CTR_FLAG_RAID10_FORMAT, "raid10_format"},
245         { CTR_FLAG_DATA_OFFSET, "data_offset"},
246         { CTR_FLAG_DELTA_DISKS, "delta_disks"},
247         { CTR_FLAG_RAID10_USE_NEAR_SETS, "raid10_use_near_sets"},
248 };
249
250 /* Return argument name string for given @flag */
251 static const char *_argname_by_flag(const uint32_t flag)
252 {
253         if (hweight32(flag) == 1) {
254                 struct arg_name_flag *anf = _arg_name_flags + ARRAY_SIZE(_arg_name_flags);
255
256                 while (anf-- > _arg_name_flags)
257                         if (_test_flag(flag, anf->flag))
258                                 return anf->name;
259
260         } else
261                 DMERR("%s called with more than one flag!", __func__);
262
263         return NULL;
264 }
265
266 /*
267  * bool helpers to test for various raid levels of a raid set,
268  * is. it's level as reported by the superblock rather than
269  * the requested raid_type passed to the constructor.
270  */
271 /* Return true, if raid set in @rs is raid0 */
272 static bool rs_is_raid0(struct raid_set *rs)
273 {
274         return !rs->md.level;
275 }
276
277 /* Return true, if raid set in @rs is raid10 */
278 static bool rs_is_raid10(struct raid_set *rs)
279 {
280         return rs->md.level == 10;
281 }
282
283 /*
284  * bool helpers to test for various raid levels of a raid type
285  */
286
287 /* Return true, if raid type in @rt is raid0 */
288 static bool rt_is_raid0(struct raid_type *rt)
289 {
290         return !rt->level;
291 }
292
293 /* Return true, if raid type in @rt is raid1 */
294 static bool rt_is_raid1(struct raid_type *rt)
295 {
296         return rt->level == 1;
297 }
298
299 /* Return true, if raid type in @rt is raid10 */
300 static bool rt_is_raid10(struct raid_type *rt)
301 {
302         return rt->level == 10;
303 }
304
305 /* Return true, if raid type in @rt is raid4/5 */
306 static bool rt_is_raid45(struct raid_type *rt)
307 {
308         return _in_range(rt->level, 4, 5);
309 }
310
311 /* Return true, if raid type in @rt is raid6 */
312 static bool rt_is_raid6(struct raid_type *rt)
313 {
314         return rt->level == 6;
315 }
316
317 /* Return true, if raid type in @rt is raid4/5/6 */
318 static bool rt_is_raid456(struct raid_type *rt)
319 {
320         return _in_range(rt->level, 4, 6);
321 }
322 /* END: raid level bools */
323
324 /*
325  * Convenience functions to set ti->error to @errmsg and
326  * return @r in order to shorten code in a lot of places
327  */
328 static int ti_error_ret(struct dm_target *ti, const char *errmsg, int r)
329 {
330         ti->error = (char *) errmsg;
331         return r;
332 }
333
334 static int ti_error_einval(struct dm_target *ti, const char *errmsg)
335 {
336         return ti_error_ret(ti, errmsg, -EINVAL);
337 }
338 /* END: convenience functions to set ti->error to @errmsg... */
339
340 /* Return invalid ctr flags for the raid level of @rs */
341 static uint32_t _invalid_flags(struct raid_set *rs)
342 {
343         if (rt_is_raid0(rs->raid_type))
344                 return RAID0_INVALID_FLAGS;
345         else if (rt_is_raid1(rs->raid_type))
346                 return RAID1_INVALID_FLAGS;
347         else if (rt_is_raid10(rs->raid_type))
348                 return RAID10_INVALID_FLAGS;
349         else if (rt_is_raid45(rs->raid_type))
350                 return RAID45_INVALID_FLAGS;
351         else if (rt_is_raid6(rs->raid_type))
352                 return RAID6_INVALID_FLAGS;
353
354         return ~0;
355 }
356
357 /*
358  * Check for any invalid flags set on @rs defined by bitset @invalid_flags
359  *
360  * Has to be called after parsing of the ctr flags!
361  */
362 static int rs_check_for_invalid_flags(struct raid_set *rs)
363 {
364         if (_test_flags(rs->ctr_flags, _invalid_flags(rs)))
365                 return ti_error_einval(rs->ti, "Invalid flag combined");
366
367         return 0;
368 }
369
370
371 /* MD raid10 bit definitions and helpers */
372 #define RAID10_OFFSET                   (1 << 16) /* stripes with data copies area adjacent on devices */
373 #define RAID10_BROCKEN_USE_FAR_SETS     (1 << 17) /* Broken in raid10.c: use sets instead of whole stripe rotation */
374 #define RAID10_USE_FAR_SETS             (1 << 18) /* Use sets instead of whole stripe rotation */
375 #define RAID10_FAR_COPIES_SHIFT         8         /* raid10 # far copies shift (2nd byte of layout) */
376
377 /* Return md raid10 near copies for @layout */
378 static unsigned int _raid10_near_copies(int layout)
379 {
380         return layout & 0xFF;
381 }
382
383 /* Return md raid10 far copies for @layout */
384 static unsigned int _raid10_far_copies(int layout)
385 {
386         return _raid10_near_copies(layout >> RAID10_FAR_COPIES_SHIFT);
387 }
388
389 /* Return true if md raid10 offset for @layout */
390 static unsigned int _is_raid10_offset(int layout)
391 {
392         return layout & RAID10_OFFSET;
393 }
394
395 /* Return true if md raid10 near for @layout */
396 static unsigned int _is_raid10_near(int layout)
397 {
398         return !_is_raid10_offset(layout) && _raid10_near_copies(layout) > 1;
399 }
400
401 /* Return true if md raid10 far for @layout */
402 static unsigned int _is_raid10_far(int layout)
403 {
404         return !_is_raid10_offset(layout) && _raid10_far_copies(layout) > 1;
405 }
406
407 /* Return md raid10 layout string for @layout */
408 static const char *raid10_md_layout_to_format(int layout)
409 {
410         /*
411          * Bit 16 stands for "offset"
412          * (i.e. adjacent stripes hold copies)
413          *
414          * Refer to MD's raid10.c for details
415          */
416         if (_is_raid10_offset(layout))
417                 return "offset";
418
419         if (_raid10_near_copies(layout) > 1)
420                 return "near";
421
422         WARN_ON(_raid10_far_copies(layout) < 2);
423
424         return "far";
425 }
426
427 /* Return md raid10 algorithm for @name */
428 static const int raid10_name_to_format(const char *name)
429 {
430         if (!strcasecmp(name, "near"))
431                 return ALGORITHM_RAID10_NEAR;
432         else if (!strcasecmp(name, "offset"))
433                 return ALGORITHM_RAID10_OFFSET;
434         else if (!strcasecmp(name, "far"))
435                 return ALGORITHM_RAID10_FAR;
436
437         return -EINVAL;
438 }
439
440
441 /* Return md raid10 copies for @layout */
442 static unsigned int raid10_md_layout_to_copies(int layout)
443 {
444         return _raid10_near_copies(layout) > 1 ?
445                _raid10_near_copies(layout) : _raid10_far_copies(layout);
446 }
447
448 /* Return md raid10 format id for @format string */
449 static int raid10_format_to_md_layout(struct raid_set *rs,
450                                       unsigned int algorithm,
451                                       unsigned int copies)
452 {
453         unsigned int n = 1, f = 1, r = 0;
454
455         /*
456          * MD resilienece flaw:
457          *
458          * enabling use_far_sets for far/offset formats causes copies
459          * to be colocated on the same devs together with their origins!
460          *
461          * -> disable it for now in the definition above
462          */
463         if (algorithm == ALGORITHM_RAID10_DEFAULT ||
464             algorithm == ALGORITHM_RAID10_NEAR)
465                 n = copies;
466
467         else if (algorithm == ALGORITHM_RAID10_OFFSET) {
468                 f = copies;
469                 r = RAID10_OFFSET;
470                 if (!_test_flag(CTR_FLAG_RAID10_USE_NEAR_SETS, rs->ctr_flags))
471                         r |= RAID10_USE_FAR_SETS;
472
473         } else if (algorithm == ALGORITHM_RAID10_FAR) {
474                 f = copies;
475                 r = !RAID10_OFFSET;
476                 if (!_test_flag(CTR_FLAG_RAID10_USE_NEAR_SETS, rs->ctr_flags))
477                         r |= RAID10_USE_FAR_SETS;
478
479         } else
480                 return -EINVAL;
481
482         return r | (f << RAID10_FAR_COPIES_SHIFT) | n;
483 }
484 /* END: MD raid10 bit definitions and helpers */
485
486 /* Check for any of the raid10 algorithms */
487 static int _got_raid10(struct raid_type *rtp, const int layout)
488 {
489         if (rtp->level == 10) {
490                 switch (rtp->algorithm) {
491                 case ALGORITHM_RAID10_DEFAULT:
492                 case ALGORITHM_RAID10_NEAR:
493                         return _is_raid10_near(layout);
494                 case ALGORITHM_RAID10_OFFSET:
495                         return _is_raid10_offset(layout);
496                 case ALGORITHM_RAID10_FAR:
497                         return _is_raid10_far(layout);
498                 default:
499                         break;
500                 }
501         }
502
503         return 0;
504 }
505
506 /* Return raid_type for @name */
507 static struct raid_type *get_raid_type(const char *name)
508 {
509         struct raid_type *rtp = raid_types + ARRAY_SIZE(raid_types);
510
511         while (rtp-- > raid_types)
512                 if (!strcasecmp(rtp->name, name))
513                         return rtp;
514
515         return NULL;
516 }
517
518 /* Return raid_type for @name based derived from @level and @layout */
519 static struct raid_type *get_raid_type_by_ll(const int level, const int layout)
520 {
521         struct raid_type *rtp = raid_types + ARRAY_SIZE(raid_types);
522
523         while (rtp-- > raid_types) {
524                 /* RAID10 special checks based on @layout flags/properties */
525                 if (rtp->level == level &&
526                     (_got_raid10(rtp, layout) || rtp->algorithm == layout))
527                         return rtp;
528         }
529
530         return NULL;
531 }
532
533 /*
534  * Set the mddev properties in @rs to the new
535  * ones requested by the ctr
536  */
537 static void rs_set_new(struct raid_set *rs)
538 {
539         struct mddev *mddev = &rs->md;
540
541         mddev->level = mddev->new_level;
542         mddev->layout = mddev->new_layout;
543         mddev->chunk_sectors = mddev->new_chunk_sectors;
544         mddev->delta_disks = 0;
545 }
546
547
548 static struct raid_set *context_alloc(struct dm_target *ti, struct raid_type *raid_type, unsigned raid_devs)
549 {
550         unsigned i;
551         struct raid_set *rs;
552
553         if (raid_devs <= raid_type->parity_devs)
554                 return ERR_PTR(ti_error_einval(ti, "Insufficient number of devices"));
555
556         rs = kzalloc(sizeof(*rs) + raid_devs * sizeof(rs->dev[0]), GFP_KERNEL);
557         if (!rs)
558                 return ERR_PTR(ti_error_ret(ti, "Cannot allocate raid context", -ENOMEM));
559
560         mddev_init(&rs->md);
561
562         rs->raid_disks = raid_devs;
563         rs->delta_disks = 0;
564
565         rs->ti = ti;
566         rs->raid_type = raid_type;
567         rs->md.raid_disks = raid_devs;
568         rs->md.level = raid_type->level;
569         rs->md.new_level = rs->md.level;
570         rs->md.layout = raid_type->algorithm;
571         rs->md.new_layout = rs->md.layout;
572         rs->md.delta_disks = 0;
573         rs->md.recovery_cp = 0;
574
575         for (i = 0; i < raid_devs; i++)
576                 md_rdev_init(&rs->dev[i].rdev);
577
578         /*
579          * Remaining items to be initialized by further RAID params:
580          *  rs->md.persistent
581          *  rs->md.external
582          *  rs->md.chunk_sectors
583          *  rs->md.new_chunk_sectors
584          *  rs->md.dev_sectors
585          */
586
587         return rs;
588 }
589
590 static void context_free(struct raid_set *rs)
591 {
592         int i;
593
594         for (i = 0; i < rs->md.raid_disks; i++) {
595                 if (rs->dev[i].meta_dev)
596                         dm_put_device(rs->ti, rs->dev[i].meta_dev);
597                 md_rdev_clear(&rs->dev[i].rdev);
598                 if (rs->dev[i].data_dev)
599                         dm_put_device(rs->ti, rs->dev[i].data_dev);
600         }
601
602         kfree(rs);
603 }
604
605 /*
606  * For every device we have two words
607  *  <meta_dev>: meta device name or '-' if missing
608  *  <data_dev>: data device name or '-' if missing
609  *
610  * The following are permitted:
611  *    - -
612  *    - <data_dev>
613  *    <meta_dev> <data_dev>
614  *
615  * The following is not allowed:
616  *    <meta_dev> -
617  *
618  * This code parses those words.  If there is a failure,
619  * the caller must use context_free to unwind the operations.
620  */
621 static int parse_dev_params(struct raid_set *rs, struct dm_arg_set *as)
622 {
623         int i;
624         int rebuild = 0;
625         int metadata_available = 0;
626         int r = 0;
627         const char *arg;
628
629         /* Put off the number of raid devices argument to get to dev pairs */
630         arg = dm_shift_arg(as);
631         if (!arg)
632                 return -EINVAL;
633
634         for (i = 0; i < rs->md.raid_disks; i++) {
635                 rs->dev[i].rdev.raid_disk = i;
636
637                 rs->dev[i].meta_dev = NULL;
638                 rs->dev[i].data_dev = NULL;
639
640                 /*
641                  * There are no offsets, since there is a separate device
642                  * for data and metadata.
643                  */
644                 rs->dev[i].rdev.data_offset = 0;
645                 rs->dev[i].rdev.mddev = &rs->md;
646
647                 arg = dm_shift_arg(as);
648                 if (!arg)
649                         return -EINVAL;
650
651                 if (strcmp(arg, "-")) {
652                         r = dm_get_device(rs->ti, arg,
653                                             dm_table_get_mode(rs->ti->table),
654                                             &rs->dev[i].meta_dev);
655                         if (r)
656                                 return ti_error_ret(rs->ti, "RAID metadata device lookup failure", r);
657
658                         rs->dev[i].rdev.sb_page = alloc_page(GFP_KERNEL);
659                         if (!rs->dev[i].rdev.sb_page)
660                                 return ti_error_ret(rs->ti, "Failed to allocate superblock page", -ENOMEM);
661                 }
662
663                 arg = dm_shift_arg(as);
664                 if (!arg)
665                         return -EINVAL;
666
667                 if (!strcmp(arg, "-")) {
668                         if (!test_bit(In_sync, &rs->dev[i].rdev.flags) &&
669                             (!rs->dev[i].rdev.recovery_offset))
670                                 return ti_error_einval(rs->ti, "Drive designated for rebuild not specified");
671
672                         if (rs->dev[i].meta_dev)
673                                 return ti_error_einval(rs->ti, "No data device supplied with metadata device");
674
675                         continue;
676                 }
677
678                 r = dm_get_device(rs->ti, arg,
679                                     dm_table_get_mode(rs->ti->table),
680                                     &rs->dev[i].data_dev);
681                 if (r)
682                         return ti_error_ret(rs->ti, "RAID device lookup failure", r);
683
684                 if (rs->dev[i].meta_dev) {
685                         metadata_available = 1;
686                         rs->dev[i].rdev.meta_bdev = rs->dev[i].meta_dev->bdev;
687                 }
688                 rs->dev[i].rdev.bdev = rs->dev[i].data_dev->bdev;
689                 list_add(&rs->dev[i].rdev.same_set, &rs->md.disks);
690                 if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
691                         rebuild++;
692         }
693
694         if (metadata_available) {
695                 rs->md.external = 0;
696                 rs->md.persistent = 1;
697                 rs->md.major_version = 2;
698         } else if (rebuild && !rs->md.recovery_cp) {
699                 /*
700                  * Without metadata, we will not be able to tell if the array
701                  * is in-sync or not - we must assume it is not.  Therefore,
702                  * it is impossible to rebuild a drive.
703                  *
704                  * Even if there is metadata, the on-disk information may
705                  * indicate that the array is not in-sync and it will then
706                  * fail at that time.
707                  *
708                  * User could specify 'nosync' option if desperate.
709                  */
710                 DMERR("Unable to rebuild drive while array is not in-sync");
711                 return ti_error_einval(rs->ti, "Unable to rebuild drive while array is not in-sync");
712         }
713
714         return 0;
715 }
716
717 /*
718  * validate_region_size
719  * @rs
720  * @region_size:  region size in sectors.  If 0, pick a size (4MiB default).
721  *
722  * Set rs->md.bitmap_info.chunksize (which really refers to 'region size').
723  * Ensure that (ti->len/region_size < 2^21) - required by MD bitmap.
724  *
725  * Returns: 0 on success, -EINVAL on failure.
726  */
727 static int validate_region_size(struct raid_set *rs, unsigned long region_size)
728 {
729         unsigned long min_region_size = rs->ti->len / (1 << 21);
730
731         if (!region_size) {
732                 /*
733                  * Choose a reasonable default.  All figures in sectors.
734                  */
735                 if (min_region_size > (1 << 13)) {
736                         /* If not a power of 2, make it the next power of 2 */
737                         region_size = roundup_pow_of_two(min_region_size);
738                         DMINFO("Choosing default region size of %lu sectors",
739                                region_size);
740                 } else {
741                         DMINFO("Choosing default region size of 4MiB");
742                         region_size = 1 << 13; /* sectors */
743                 }
744         } else {
745                 /*
746                  * Validate user-supplied value.
747                  */
748                 if (region_size > rs->ti->len)
749                         return ti_error_einval(rs->ti, "Supplied region size is too large");
750
751                 if (region_size < min_region_size) {
752                         DMERR("Supplied region_size (%lu sectors) below minimum (%lu)",
753                               region_size, min_region_size);
754                         return ti_error_einval(rs->ti, "Supplied region size is too small");
755                 }
756
757                 if (!is_power_of_2(region_size))
758                         return ti_error_einval(rs->ti, "Region size is not a power of 2");
759
760                 if (region_size < rs->md.chunk_sectors)
761                         return ti_error_einval(rs->ti, "Region size is smaller than the chunk size");
762         }
763
764         /*
765          * Convert sectors to bytes.
766          */
767         rs->md.bitmap_info.chunksize = (region_size << 9);
768
769         return 0;
770 }
771
772 /*
773  * validate_raid_redundancy
774  * @rs
775  *
776  * Determine if there are enough devices in the array that haven't
777  * failed (or are being rebuilt) to form a usable array.
778  *
779  * Returns: 0 on success, -EINVAL on failure.
780  */
781 static int validate_raid_redundancy(struct raid_set *rs)
782 {
783         unsigned i, rebuild_cnt = 0;
784         unsigned rebuilds_per_group = 0, copies, d;
785         unsigned group_size, last_group_start;
786
787         for (i = 0; i < rs->md.raid_disks; i++)
788                 if (!test_bit(In_sync, &rs->dev[i].rdev.flags) ||
789                     !rs->dev[i].rdev.sb_page)
790                         rebuild_cnt++;
791
792         switch (rs->raid_type->level) {
793         case 1:
794                 if (rebuild_cnt >= rs->md.raid_disks)
795                         goto too_many;
796                 break;
797         case 4:
798         case 5:
799         case 6:
800                 if (rebuild_cnt > rs->raid_type->parity_devs)
801                         goto too_many;
802                 break;
803         case 10:
804                 copies = raid10_md_layout_to_copies(rs->md.layout);
805                 if (rebuild_cnt < copies)
806                         break;
807
808                 /*
809                  * It is possible to have a higher rebuild count for RAID10,
810                  * as long as the failed devices occur in different mirror
811                  * groups (i.e. different stripes).
812                  *
813                  * When checking "near" format, make sure no adjacent devices
814                  * have failed beyond what can be handled.  In addition to the
815                  * simple case where the number of devices is a multiple of the
816                  * number of copies, we must also handle cases where the number
817                  * of devices is not a multiple of the number of copies.
818                  * E.g.    dev1 dev2 dev3 dev4 dev5
819                  *          A    A    B    B    C
820                  *          C    D    D    E    E
821                  */
822                 if (!strcmp("near", raid10_md_layout_to_format(rs->md.layout))) {
823                         for (i = 0; i < rs->md.raid_disks * copies; i++) {
824                                 if (!(i % copies))
825                                         rebuilds_per_group = 0;
826                                 d = i % rs->md.raid_disks;
827                                 if ((!rs->dev[d].rdev.sb_page ||
828                                      !test_bit(In_sync, &rs->dev[d].rdev.flags)) &&
829                                     (++rebuilds_per_group >= copies))
830                                         goto too_many;
831                         }
832                         break;
833                 }
834
835                 /*
836                  * When checking "far" and "offset" formats, we need to ensure
837                  * that the device that holds its copy is not also dead or
838                  * being rebuilt.  (Note that "far" and "offset" formats only
839                  * support two copies right now.  These formats also only ever
840                  * use the 'use_far_sets' variant.)
841                  *
842                  * This check is somewhat complicated by the need to account
843                  * for arrays that are not a multiple of (far) copies.  This
844                  * results in the need to treat the last (potentially larger)
845                  * set differently.
846                  */
847                 group_size = (rs->md.raid_disks / copies);
848                 last_group_start = (rs->md.raid_disks / group_size) - 1;
849                 last_group_start *= group_size;
850                 for (i = 0; i < rs->md.raid_disks; i++) {
851                         if (!(i % copies) && !(i > last_group_start))
852                                 rebuilds_per_group = 0;
853                         if ((!rs->dev[i].rdev.sb_page ||
854                              !test_bit(In_sync, &rs->dev[i].rdev.flags)) &&
855                             (++rebuilds_per_group >= copies))
856                                         goto too_many;
857                 }
858                 break;
859         default:
860                 if (rebuild_cnt)
861                         return -EINVAL;
862         }
863
864         return 0;
865
866 too_many:
867         return -EINVAL;
868 }
869
870 /*
871  * Possible arguments are...
872  *      <chunk_size> [optional_args]
873  *
874  * Argument definitions
875  *    <chunk_size>                      The number of sectors per disk that
876  *                                      will form the "stripe"
877  *    [[no]sync]                        Force or prevent recovery of the
878  *                                      entire array
879  *    [rebuild <idx>]                   Rebuild the drive indicated by the index
880  *    [daemon_sleep <ms>]               Time between bitmap daemon work to
881  *                                      clear bits
882  *    [min_recovery_rate <kB/sec/disk>] Throttle RAID initialization
883  *    [max_recovery_rate <kB/sec/disk>] Throttle RAID initialization
884  *    [write_mostly <idx>]              Indicate a write mostly drive via index
885  *    [max_write_behind <sectors>]      See '-write-behind=' (man mdadm)
886  *    [stripe_cache <sectors>]          Stripe cache size for higher RAIDs
887  *    [region_size <sectors>]           Defines granularity of bitmap
888  *
889  * RAID10-only options:
890  *    [raid10_copies <# copies>]        Number of copies.  (Default: 2)
891  *    [raid10_format <near|far|offset>] Layout algorithm.  (Default: near)
892  */
893 static int parse_raid_params(struct raid_set *rs, struct dm_arg_set *as,
894                              unsigned num_raid_params)
895 {
896         int raid10_format = ALGORITHM_RAID10_DEFAULT;
897         unsigned raid10_copies = 2;
898         unsigned i;
899         unsigned value, region_size = 0;
900         sector_t sectors_per_dev = rs->ti->len;
901         sector_t max_io_len;
902         const char *arg, *key;
903         struct raid_dev *rd;
904         struct raid_type *rt = rs->raid_type;
905
906         arg = dm_shift_arg(as);
907         num_raid_params--; /* Account for chunk_size argument */
908
909         if (kstrtouint(arg, 10, &value) < 0)
910                 return ti_error_einval(rs->ti, "Bad numerical argument given for chunk_size");
911
912         /*
913          * First, parse the in-order required arguments
914          * "chunk_size" is the only argument of this type.
915          */
916         if (rt_is_raid1(rt)) {
917                 if (value)
918                         DMERR("Ignoring chunk size parameter for RAID 1");
919                 value = 0;
920         } else if (!is_power_of_2(value))
921                 return ti_error_einval(rs->ti, "Chunk size must be a power of 2");
922         else if (value < 8)
923                 return ti_error_einval(rs->ti, "Chunk size value is too small");
924
925         rs->md.new_chunk_sectors = rs->md.chunk_sectors = value;
926
927         /*
928          * We set each individual device as In_sync with a completed
929          * 'recovery_offset'.  If there has been a device failure or
930          * replacement then one of the following cases applies:
931          *
932          *   1) User specifies 'rebuild'.
933          *      - Device is reset when param is read.
934          *   2) A new device is supplied.
935          *      - No matching superblock found, resets device.
936          *   3) Device failure was transient and returns on reload.
937          *      - Failure noticed, resets device for bitmap replay.
938          *   4) Device hadn't completed recovery after previous failure.
939          *      - Superblock is read and overrides recovery_offset.
940          *
941          * What is found in the superblocks of the devices is always
942          * authoritative, unless 'rebuild' or '[no]sync' was specified.
943          */
944         for (i = 0; i < rs->md.raid_disks; i++) {
945                 set_bit(In_sync, &rs->dev[i].rdev.flags);
946                 rs->dev[i].rdev.recovery_offset = MaxSector;
947         }
948
949         /*
950          * Second, parse the unordered optional arguments
951          */
952         for (i = 0; i < num_raid_params; i++) {
953                 key = dm_shift_arg(as);
954                 if (!key)
955                         return ti_error_einval(rs->ti, "Not enough raid parameters given");
956
957                 if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_NOSYNC))) {
958                         if (_test_and_set_flag(CTR_FLAG_NOSYNC, &rs->ctr_flags))
959                                 return ti_error_einval(rs->ti, "Only one 'nosync' argument allowed");
960                         rs->md.recovery_cp = MaxSector;
961                         continue;
962                 }
963                 if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_SYNC))) {
964                         if (_test_and_set_flag(CTR_FLAG_SYNC, &rs->ctr_flags))
965                                 return ti_error_einval(rs->ti, "Only one 'sync' argument allowed");
966                         rs->md.recovery_cp = 0;
967                         continue;
968                 }
969                 if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_RAID10_USE_NEAR_SETS))) {
970                         if (_test_and_set_flag(CTR_FLAG_RAID10_USE_NEAR_SETS, &rs->ctr_flags))
971                                 return ti_error_einval(rs->ti, "Only one 'raid10_use_new_sets' argument allowed");
972                         continue;
973                 }
974
975                 arg = dm_shift_arg(as);
976                 i++; /* Account for the argument pairs */
977                 if (!arg)
978                         return ti_error_einval(rs->ti, "Wrong number of raid parameters given");
979
980                 /*
981                  * Parameters that take a string value are checked here.
982                  */
983
984                 if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_RAID10_FORMAT))) {
985                         if (_test_and_set_flag(CTR_FLAG_RAID10_FORMAT, &rs->ctr_flags))
986                                 return ti_error_einval(rs->ti, "Only one 'raid10_format' argument pair allowed");
987                         if (!rt_is_raid10(rt))
988                                 return ti_error_einval(rs->ti, "'raid10_format' is an invalid parameter for this RAID type");
989                         raid10_format = raid10_name_to_format(arg);
990                         if (raid10_format < 0)
991                                 return ti_error_ret(rs->ti, "Invalid 'raid10_format' value given", raid10_format);
992                         continue;
993                 }
994
995                 if (kstrtouint(arg, 10, &value) < 0)
996                         return ti_error_einval(rs->ti, "Bad numerical argument given in raid params");
997
998                 if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_REBUILD))) {
999                         /*
1000                          * "rebuild" is being passed in by userspace to provide
1001                          * indexes of replaced devices and to set up additional
1002                          * devices on raid level takeover.
1003                          */
1004                         if (!_in_range(value, 0, rs->md.raid_disks - 1))
1005                                 return ti_error_einval(rs->ti, "Invalid rebuild index given");
1006
1007                         rd = rs->dev + value;
1008                         clear_bit(In_sync, &rd->rdev.flags);
1009                         clear_bit(Faulty, &rd->rdev.flags);
1010                         rd->rdev.recovery_offset = 0;
1011                         _set_flag(CTR_FLAG_REBUILD, &rs->ctr_flags);
1012                 } else if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_WRITE_MOSTLY))) {
1013                         if (!rt_is_raid1(rt))
1014                                 return ti_error_einval(rs->ti, "write_mostly option is only valid for RAID1");
1015
1016                         if (!_in_range(value, 0, rs->md.raid_disks - 1))
1017                                 return ti_error_einval(rs->ti, "Invalid write_mostly index given");
1018
1019                         set_bit(WriteMostly, &rs->dev[value].rdev.flags);
1020                         _set_flag(CTR_FLAG_WRITE_MOSTLY, &rs->ctr_flags);
1021                 } else if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_MAX_WRITE_BEHIND))) {
1022                         if (!rt_is_raid1(rt))
1023                                 return ti_error_einval(rs->ti, "max_write_behind option is only valid for RAID1");
1024
1025                         if (_test_and_set_flag(CTR_FLAG_MAX_WRITE_BEHIND, &rs->ctr_flags))
1026                                 return ti_error_einval(rs->ti, "Only one max_write_behind argument pair allowed");
1027
1028                         /*
1029                          * In device-mapper, we specify things in sectors, but
1030                          * MD records this value in kB
1031                          */
1032                         value /= 2;
1033                         if (value > COUNTER_MAX)
1034                                 return ti_error_einval(rs->ti, "Max write-behind limit out of range");
1035
1036                         rs->md.bitmap_info.max_write_behind = value;
1037                 } else if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_DAEMON_SLEEP))) {
1038                         if (_test_and_set_flag(CTR_FLAG_DAEMON_SLEEP, &rs->ctr_flags))
1039                                 return ti_error_einval(rs->ti, "Only one daemon_sleep argument pair allowed");
1040                         if (!value || (value > MAX_SCHEDULE_TIMEOUT))
1041                                 return ti_error_einval(rs->ti, "daemon sleep period out of range");
1042                         rs->md.bitmap_info.daemon_sleep = value;
1043                 } else if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_DATA_OFFSET))) {
1044                         /* Userspace passes new data_offset after having extended the the data image LV */
1045                         if (_test_and_set_flag(CTR_FLAG_DATA_OFFSET, &rs->ctr_flags))
1046                                 return ti_error_einval(rs->ti, "Only one data_offset argument pair allowed");
1047
1048                         /* Ensure sensible data offset */
1049                         if (value < 0)
1050                                 return ti_error_einval(rs->ti, "Bogus data_offset value");
1051
1052                         rs->data_offset = value;
1053                 } else if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_DELTA_DISKS))) {
1054                         /* Define the +/-# of disks to add to/remove from the given raid set */
1055                         if (_test_and_set_flag(CTR_FLAG_DELTA_DISKS, &rs->ctr_flags))
1056                                 return ti_error_einval(rs->ti, "Only one delta_disks argument pair allowed");
1057
1058                         /* Ensure MAX_RAID_DEVICES and raid type minimal_devs! */
1059                         if (!_in_range(abs(value), 1, MAX_RAID_DEVICES - rt->minimal_devs))
1060                                 return ti_error_einval(rs->ti, "Too many delta_disk requested");
1061
1062                         rs->delta_disks = value;
1063                 } else if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_STRIPE_CACHE))) {
1064                         if (_test_and_set_flag(CTR_FLAG_STRIPE_CACHE, &rs->ctr_flags))
1065                                 return ti_error_einval(rs->ti, "Only one stripe_cache argument pair allowed");
1066                         /*
1067                          * In device-mapper, we specify things in sectors, but
1068                          * MD records this value in kB
1069                          */
1070                         value /= 2;
1071
1072                         if (!rt_is_raid456(rt))
1073                                 return ti_error_einval(rs->ti, "Inappropriate argument: stripe_cache");
1074                         if (raid5_set_cache_size(&rs->md, (int)value))
1075                                 return ti_error_einval(rs->ti, "Bad stripe_cache size");
1076
1077                 } else if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_MIN_RECOVERY_RATE))) {
1078                         if (_test_and_set_flag(CTR_FLAG_MIN_RECOVERY_RATE, &rs->ctr_flags))
1079                                 return ti_error_einval(rs->ti, "Only one min_recovery_rate argument pair allowed");
1080                         if (value > INT_MAX)
1081                                 return ti_error_einval(rs->ti, "min_recovery_rate out of range");
1082                         rs->md.sync_speed_min = (int)value;
1083                 } else if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_MAX_RECOVERY_RATE))) {
1084                         if (_test_and_set_flag(CTR_FLAG_MIN_RECOVERY_RATE, &rs->ctr_flags))
1085                                 return ti_error_einval(rs->ti, "Only one max_recovery_rate argument pair allowed");
1086                         if (value > INT_MAX)
1087                                 return ti_error_einval(rs->ti, "max_recovery_rate out of range");
1088                         rs->md.sync_speed_max = (int)value;
1089                 } else if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_REGION_SIZE))) {
1090                         if (_test_and_set_flag(CTR_FLAG_REGION_SIZE, &rs->ctr_flags))
1091                                 return ti_error_einval(rs->ti, "Only one region_size argument pair allowed");
1092
1093                         region_size = value;
1094                 } else if (!strcasecmp(key, _argname_by_flag(CTR_FLAG_RAID10_COPIES))) {
1095                         if (_test_and_set_flag(CTR_FLAG_RAID10_COPIES, &rs->ctr_flags))
1096                                 return ti_error_einval(rs->ti, "Only one raid10_copies argument pair allowed");
1097
1098                         if (!_in_range(value, 2, rs->md.raid_disks))
1099                                 return ti_error_einval(rs->ti, "Bad value for 'raid10_copies'");
1100
1101                         raid10_copies = value;
1102                 } else {
1103                         DMERR("Unable to parse RAID parameter: %s", key);
1104                         return ti_error_einval(rs->ti, "Unable to parse RAID parameters");
1105                 }
1106         }
1107
1108         if (validate_region_size(rs, region_size))
1109                 return -EINVAL;
1110
1111         if (rs->md.chunk_sectors)
1112                 max_io_len = rs->md.chunk_sectors;
1113         else
1114                 max_io_len = region_size;
1115
1116         if (dm_set_target_max_io_len(rs->ti, max_io_len))
1117                 return -EINVAL;
1118
1119         if (rt_is_raid10(rt)) {
1120                 if (raid10_copies > rs->md.raid_disks)
1121                         return ti_error_einval(rs->ti, "Not enough devices to satisfy specification");
1122
1123                 rs->md.new_layout = raid10_format_to_md_layout(rs, raid10_format, raid10_copies);
1124                 if (rs->md.new_layout < 0)
1125                         return ti_error_ret(rs->ti, "Error getting raid10 format", rs->md.new_layout);
1126
1127                 rt = get_raid_type_by_ll(10, rs->md.new_layout);
1128                 if (!rt)
1129                         return ti_error_einval(rs->ti, "Failed to recognize new raid10 layout");
1130
1131                 if ((rt->algorithm == ALGORITHM_RAID10_DEFAULT ||
1132                      rt->algorithm == ALGORITHM_RAID10_NEAR) &&
1133                     _test_flag(CTR_FLAG_RAID10_USE_NEAR_SETS, rs->ctr_flags))
1134                         return ti_error_einval(rs->ti, "RAID10 format 'near' and 'raid10_use_near_sets' are incompatible");
1135
1136                 /* (Len * #mirrors) / #devices */
1137                 sectors_per_dev = rs->ti->len * raid10_copies;
1138                 sector_div(sectors_per_dev, rs->md.raid_disks);
1139
1140                 rs->md.layout = raid10_format_to_md_layout(rs, raid10_format, raid10_copies);
1141                 rs->md.new_layout = rs->md.layout;
1142         } else if (!rt_is_raid1(rt) &&
1143                    sector_div(sectors_per_dev,
1144                               (rs->md.raid_disks - rt->parity_devs)))
1145                 return ti_error_einval(rs->ti, "Target length not divisible by number of data devices");
1146
1147         rs->raid10_copies = raid10_copies;
1148         rs->md.dev_sectors = sectors_per_dev;
1149
1150         /* Assume there are no metadata devices until the drives are parsed */
1151         rs->md.persistent = 0;
1152         rs->md.external = 1;
1153
1154         /* Check, if any invalid ctr arguments have been passed in for the raid level */
1155         return rs_check_for_invalid_flags(rs);
1156 }
1157
1158 static void do_table_event(struct work_struct *ws)
1159 {
1160         struct raid_set *rs = container_of(ws, struct raid_set, md.event_work);
1161
1162         dm_table_event(rs->ti->table);
1163 }
1164
1165 static int raid_is_congested(struct dm_target_callbacks *cb, int bits)
1166 {
1167         struct raid_set *rs = container_of(cb, struct raid_set, callbacks);
1168
1169         return mddev_congested(&rs->md, bits);
1170 }
1171
1172 /*  Features */
1173 #define FEATURE_FLAG_SUPPORTS_RESHAPE   0x1
1174
1175 /* State flags for sb->flags */
1176 #define SB_FLAG_RESHAPE_ACTIVE          0x1
1177 #define SB_FLAG_RESHAPE_BACKWARDS       0x2
1178
1179 /*
1180  * This structure is never routinely used by userspace, unlike md superblocks.
1181  * Devices with this superblock should only ever be accessed via device-mapper.
1182  */
1183 #define DM_RAID_MAGIC 0x64526D44
1184 struct dm_raid_superblock {
1185         __le32 magic;           /* "DmRd" */
1186         __le32 compat_features; /* Used to indicate compatible features (like 1.8.0 ondisk metadata extension) */
1187
1188         __le32 num_devices;     /* Number of devices in this raid set. (Max 64) */
1189         __le32 array_position;  /* The position of this drive in the raid set */
1190
1191         __le64 events;          /* Incremented by md when superblock updated */
1192         __le64 failed_devices;  /* Pre 1.8.0 part of bit field of devices to */
1193                                 /* indicate failures (see extension below) */
1194
1195         /*
1196          * This offset tracks the progress of the repair or replacement of
1197          * an individual drive.
1198          */
1199         __le64 disk_recovery_offset;
1200
1201         /*
1202          * This offset tracks the progress of the initial raid set
1203          * synchronisation/parity calculation.
1204          */
1205         __le64 array_resync_offset;
1206
1207         /*
1208          * raid characteristics
1209          */
1210         __le32 level;
1211         __le32 layout;
1212         __le32 stripe_sectors;
1213
1214         /********************************************************************
1215          * BELOW FOLLOW V1.8.0 EXTENSIONS TO THE PRISTINE SUPERBLOCK FORMAT!!!
1216          *
1217          * FEATURE_FLAG_SUPPORTS_RESHAPE in the features member indicates that those exist
1218          */
1219
1220         __le32 flags; /* Flags defining array states for reshaping */
1221
1222         /*
1223          * This offset tracks the progress of a raid
1224          * set reshape in order to be able to restart it
1225          */
1226         __le64 reshape_position;
1227
1228         /*
1229          * These define the properties of the array in case of an interrupted reshape
1230          */
1231         __le32 new_level;
1232         __le32 new_layout;
1233         __le32 new_stripe_sectors;
1234         __le32 delta_disks;
1235
1236         __le64 array_sectors; /* Array size in sectors */
1237
1238         /*
1239          * Sector offsets to data on devices (reshaping).
1240          * Needed to support out of place reshaping, thus
1241          * not writing over any stripes whilst converting
1242          * them from old to new layout
1243          */
1244         __le64 data_offset;
1245         __le64 new_data_offset;
1246
1247         __le64 sectors; /* Used device size in sectors */
1248
1249         /*
1250          * Additonal Bit field of devices indicating failures to support
1251          * up to 256 devices with the 1.8.0 on-disk metadata format
1252          */
1253         __le64 extended_failed_devices[DISKS_ARRAY_ELEMS - 1];
1254
1255         __le32 incompat_features;       /* Used to indicate any incompatible features */
1256
1257         /* Always set rest up to logical block size to 0 when writing (see get_metadata_device() below). */
1258 } __packed;
1259
1260 static int read_disk_sb(struct md_rdev *rdev, int size)
1261 {
1262         BUG_ON(!rdev->sb_page);
1263
1264         if (rdev->sb_loaded)
1265                 return 0;
1266
1267         if (!sync_page_io(rdev, 0, size, rdev->sb_page, REQ_OP_READ, 0, 1)) {
1268                 DMERR("Failed to read superblock of device at position %d",
1269                       rdev->raid_disk);
1270                 md_error(rdev->mddev, rdev);
1271                 return -EINVAL;
1272         }
1273
1274         rdev->sb_loaded = 1;
1275
1276         return 0;
1277 }
1278
1279 static void sb_retrieve_failed_devices(struct dm_raid_superblock *sb, uint64_t *failed_devices)
1280 {
1281         failed_devices[0] = le64_to_cpu(sb->failed_devices);
1282         memset(failed_devices + 1, 0, sizeof(sb->extended_failed_devices));
1283
1284         if (_test_flag(FEATURE_FLAG_SUPPORTS_RESHAPE, le32_to_cpu(sb->compat_features))) {
1285                 int i = ARRAY_SIZE(sb->extended_failed_devices);
1286
1287                 while (i--)
1288                         failed_devices[i+1] = le64_to_cpu(sb->extended_failed_devices[i]);
1289         }
1290 }
1291
1292 static void super_sync(struct mddev *mddev, struct md_rdev *rdev)
1293 {
1294         int i;
1295         uint64_t failed_devices;
1296         struct dm_raid_superblock *sb;
1297         struct raid_set *rs = container_of(mddev, struct raid_set, md);
1298
1299         sb = page_address(rdev->sb_page);
1300         failed_devices = le64_to_cpu(sb->failed_devices);
1301
1302         for (i = 0; i < mddev->raid_disks; i++)
1303                 if (!rs->dev[i].data_dev ||
1304                     test_bit(Faulty, &(rs->dev[i].rdev.flags)))
1305                         failed_devices |= (1ULL << i);
1306
1307         memset(sb + 1, 0, rdev->sb_size - sizeof(*sb));
1308
1309         sb->magic = cpu_to_le32(DM_RAID_MAGIC);
1310         sb->compat_features = cpu_to_le32(0);   /* No features yet */
1311
1312         sb->num_devices = cpu_to_le32(mddev->raid_disks);
1313         sb->array_position = cpu_to_le32(rdev->raid_disk);
1314
1315         sb->events = cpu_to_le64(mddev->events);
1316         sb->failed_devices = cpu_to_le64(failed_devices);
1317
1318         sb->disk_recovery_offset = cpu_to_le64(rdev->recovery_offset);
1319         sb->array_resync_offset = cpu_to_le64(mddev->recovery_cp);
1320
1321         sb->level = cpu_to_le32(mddev->level);
1322         sb->layout = cpu_to_le32(mddev->layout);
1323         sb->stripe_sectors = cpu_to_le32(mddev->chunk_sectors);
1324 }
1325
1326 /*
1327  * super_load
1328  *
1329  * This function creates a superblock if one is not found on the device
1330  * and will decide which superblock to use if there's a choice.
1331  *
1332  * Return: 1 if use rdev, 0 if use refdev, -Exxx otherwise
1333  */
1334 static int super_load(struct md_rdev *rdev, struct md_rdev *refdev)
1335 {
1336         int r;
1337         struct dm_raid_superblock *sb;
1338         struct dm_raid_superblock *refsb;
1339         uint64_t events_sb, events_refsb;
1340
1341         rdev->sb_start = 0;
1342         rdev->sb_size = bdev_logical_block_size(rdev->meta_bdev);
1343         if (rdev->sb_size < sizeof(*sb) || rdev->sb_size > PAGE_SIZE) {
1344                 DMERR("superblock size of a logical block is no longer valid");
1345                 return -EINVAL;
1346         }
1347
1348         r = read_disk_sb(rdev, rdev->sb_size);
1349         if (r)
1350                 return r;
1351
1352         sb = page_address(rdev->sb_page);
1353
1354         /*
1355          * Two cases that we want to write new superblocks and rebuild:
1356          * 1) New device (no matching magic number)
1357          * 2) Device specified for rebuild (!In_sync w/ offset == 0)
1358          */
1359         if ((sb->magic != cpu_to_le32(DM_RAID_MAGIC)) ||
1360             (!test_bit(In_sync, &rdev->flags) && !rdev->recovery_offset)) {
1361                 super_sync(rdev->mddev, rdev);
1362
1363                 set_bit(FirstUse, &rdev->flags);
1364
1365                 /* Force writing of superblocks to disk */
1366                 set_bit(MD_CHANGE_DEVS, &rdev->mddev->flags);
1367
1368                 /* Any superblock is better than none, choose that if given */
1369                 return refdev ? 0 : 1;
1370         }
1371
1372         if (!refdev)
1373                 return 1;
1374
1375         events_sb = le64_to_cpu(sb->events);
1376
1377         refsb = page_address(refdev->sb_page);
1378         events_refsb = le64_to_cpu(refsb->events);
1379
1380         return (events_sb > events_refsb) ? 1 : 0;
1381 }
1382
1383 static int super_init_validation(struct raid_set *rs, struct md_rdev *rdev)
1384 {
1385         int role;
1386         unsigned int d;
1387         struct mddev *mddev = &rs->md;
1388         uint64_t events_sb;
1389         uint64_t failed_devices[DISKS_ARRAY_ELEMS];
1390         struct dm_raid_superblock *sb;
1391         uint32_t new_devs = 0, rebuild_and_new = 0, rebuilds = 0;
1392         struct md_rdev *r;
1393         struct dm_raid_superblock *sb2;
1394
1395         sb = page_address(rdev->sb_page);
1396         events_sb = le64_to_cpu(sb->events);
1397
1398         /*
1399          * Initialise to 1 if this is a new superblock.
1400          */
1401         mddev->events = events_sb ? : 1;
1402
1403         mddev->reshape_position = MaxSector;
1404
1405         /*
1406          * Reshaping is supported, e.g. reshape_position is valid
1407          * in superblock and superblock content is authoritative.
1408          */
1409         if (_test_flag(FEATURE_FLAG_SUPPORTS_RESHAPE, le32_to_cpu(sb->compat_features))) {
1410                 /* Superblock is authoritative wrt given raid set layout! */
1411                 mddev->raid_disks = le32_to_cpu(sb->num_devices);
1412                 mddev->level = le32_to_cpu(sb->level);
1413                 mddev->layout = le32_to_cpu(sb->layout);
1414                 mddev->chunk_sectors = le32_to_cpu(sb->stripe_sectors);
1415                 mddev->new_level = le32_to_cpu(sb->new_level);
1416                 mddev->new_layout = le32_to_cpu(sb->new_layout);
1417                 mddev->new_chunk_sectors = le32_to_cpu(sb->new_stripe_sectors);
1418                 mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1419                 mddev->array_sectors = le64_to_cpu(sb->array_sectors);
1420
1421                 /* raid was reshaping and got interrupted */
1422                 if (_test_flag(SB_FLAG_RESHAPE_ACTIVE, le32_to_cpu(sb->flags))) {
1423                         if (_test_flag(CTR_FLAG_DELTA_DISKS, rs->ctr_flags)) {
1424                                 DMERR("Reshape requested but raid set is still reshaping");
1425                                 return -EINVAL;
1426                         }
1427
1428                         if (mddev->delta_disks < 0 ||
1429                             (!mddev->delta_disks && _test_flag(SB_FLAG_RESHAPE_BACKWARDS, le32_to_cpu(sb->flags))))
1430                                 mddev->reshape_backwards = 1;
1431                         else
1432                                 mddev->reshape_backwards = 0;
1433
1434                         mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1435                         rs->raid_type = get_raid_type_by_ll(mddev->level, mddev->layout);
1436                 }
1437
1438         } else {
1439                 /*
1440                  * Reshaping is not allowed, because we don't have the appropriate metadata
1441                  */
1442                 if (le32_to_cpu(sb->level) != mddev->level) {
1443                         DMERR("Reshaping/takeover raid sets not yet supported. (raid level/stripes/size change)");
1444                         return -EINVAL;
1445                 }
1446                 if (le32_to_cpu(sb->layout) != mddev->layout) {
1447                         DMERR("Reshaping raid sets not yet supported. (raid layout change)");
1448                         DMERR("  0x%X vs 0x%X", le32_to_cpu(sb->layout), mddev->layout);
1449                         DMERR("  Old layout: %s w/ %d copies",
1450                               raid10_md_layout_to_format(le32_to_cpu(sb->layout)),
1451                               raid10_md_layout_to_copies(le32_to_cpu(sb->layout)));
1452                         DMERR("  New layout: %s w/ %d copies",
1453                               raid10_md_layout_to_format(mddev->layout),
1454                               raid10_md_layout_to_copies(mddev->layout));
1455                         return -EINVAL;
1456                 }
1457                 if (le32_to_cpu(sb->stripe_sectors) != mddev->chunk_sectors) {
1458                         DMERR("Reshaping raid sets not yet supported. (stripe sectors change)");
1459                         return -EINVAL;
1460                 }
1461
1462                 /* We can only change the number of devices in raid1 with old (i.e. pre 1.0.7) metadata */
1463                 if (!rt_is_raid1(rs->raid_type) &&
1464                     (le32_to_cpu(sb->num_devices) != mddev->raid_disks)) {
1465                         DMERR("Reshaping raid sets not yet supported. (device count change from %u to %u)",
1466                               sb->num_devices, mddev->raid_disks);
1467                         return -EINVAL;
1468                 }
1469
1470                 /* Table line is checked vs. authoritative superblock */
1471                 rs_set_new(rs);
1472         }
1473
1474         if (!_test_flag(CTR_FLAG_NOSYNC, rs->ctr_flags))
1475                 mddev->recovery_cp = le64_to_cpu(sb->array_resync_offset);
1476
1477         /*
1478          * During load, we set FirstUse if a new superblock was written.
1479          * There are two reasons we might not have a superblock:
1480          * 1) The raid set is brand new - in which case, all of the
1481          *    devices must have their In_sync bit set.  Also,
1482          *    recovery_cp must be 0, unless forced.
1483          * 2) This is a new device being added to an old raid set
1484          *    and the new device needs to be rebuilt - in which
1485          *    case the In_sync bit will /not/ be set and
1486          *    recovery_cp must be MaxSector.
1487          */
1488         d = 0;
1489         rdev_for_each(r, mddev) {
1490                 if (test_bit(FirstUse, &r->flags))
1491                         new_devs++;
1492
1493                 if (!test_bit(In_sync, &r->flags)) {
1494                         DMINFO("Device %d specified for rebuild; clearing superblock",
1495                                 r->raid_disk);
1496                         rebuilds++;
1497
1498                         if (test_bit(FirstUse, &r->flags))
1499                                 rebuild_and_new++;
1500                 }
1501
1502                 d++;
1503         }
1504
1505         if (new_devs == rs->raid_disks || !rebuilds) {
1506                 /* Replace a broken device */
1507                 if (new_devs == 1 && !rs->delta_disks)
1508                         ;
1509                 if (new_devs == rs->raid_disks) {
1510                         DMINFO("Superblocks created for new raid set");
1511                         set_bit(MD_ARRAY_FIRST_USE, &mddev->flags);
1512                         mddev->recovery_cp = 0;
1513                 } else if (new_devs && new_devs != rs->raid_disks && !rebuilds) {
1514                         DMERR("New device injected into existing raid set without "
1515                               "'delta_disks' or 'rebuild' parameter specified");
1516                         return -EINVAL;
1517                 }
1518         } else if (new_devs && new_devs != rebuilds) {
1519                 DMERR("%u 'rebuild' devices cannot be injected into"
1520                       " a raid set with %u other first-time devices",
1521                       rebuilds, new_devs);
1522                 return -EINVAL;
1523         } else if (rebuilds) {
1524                 if (rebuild_and_new && rebuilds != rebuild_and_new) {
1525                         DMERR("new device%s provided without 'rebuild'",
1526                               new_devs > 1 ? "s" : "");
1527                         return -EINVAL;
1528                 } else if (mddev->recovery_cp != MaxSector) {
1529                         DMERR("'rebuild' specified while raid set is not in-sync (recovery_cp=%llu)",
1530                               (unsigned long long) mddev->recovery_cp);
1531                         return -EINVAL;
1532                 } else if (mddev->reshape_position != MaxSector) {
1533                         DMERR("'rebuild' specified while raid set is being reshaped");
1534                         return -EINVAL;
1535                 }
1536         }
1537
1538         /*
1539          * Now we set the Faulty bit for those devices that are
1540          * recorded in the superblock as failed.
1541          */
1542         sb_retrieve_failed_devices(sb, failed_devices);
1543         rdev_for_each(r, mddev) {
1544                 if (!r->sb_page)
1545                         continue;
1546                 sb2 = page_address(r->sb_page);
1547                 sb2->failed_devices = 0;
1548                 memset(sb2->extended_failed_devices, 0, sizeof(sb2->extended_failed_devices));
1549
1550                 /*
1551                  * Check for any device re-ordering.
1552                  */
1553                 if (!test_bit(FirstUse, &r->flags) && (r->raid_disk >= 0)) {
1554                         role = le32_to_cpu(sb2->array_position);
1555                         if (role < 0)
1556                                 continue;
1557
1558                         if (role != r->raid_disk) {
1559                                 if (_is_raid10_near(mddev->layout)) {
1560                                         if (mddev->raid_disks % _raid10_near_copies(mddev->layout) ||
1561                                             rs->raid_disks % rs->raid10_copies)
1562                                                 return ti_error_einval(rs->ti, "Cannot change raid10 near "
1563                                                                                "set to odd # of devices!");
1564
1565                                         sb2->array_position = cpu_to_le32(r->raid_disk);
1566
1567                                 } else if (!(rs_is_raid10(rs) && rt_is_raid0(rs->raid_type)) &&
1568                                     !(rs_is_raid0(rs) && rt_is_raid10(rs->raid_type)) &&
1569                                     !rt_is_raid1(rs->raid_type))
1570                                         return ti_error_einval(rs->ti, "Cannot change device positions in raid set");
1571
1572                                 DMINFO("raid device #%d now at position #%d",
1573                                        role, r->raid_disk);
1574                         }
1575
1576                         /*
1577                          * Partial recovery is performed on
1578                          * returning failed devices.
1579                          */
1580                         if (test_bit(role, (void *) failed_devices))
1581                                 set_bit(Faulty, &r->flags);
1582                 }
1583         }
1584
1585         return 0;
1586 }
1587
1588 static int super_validate(struct raid_set *rs, struct md_rdev *rdev)
1589 {
1590         struct mddev *mddev = &rs->md;
1591         struct dm_raid_superblock *sb;
1592
1593         if (!rdev->sb_page)
1594                 return 0;
1595
1596         sb = page_address(rdev->sb_page);
1597
1598         /*
1599          * If mddev->events is not set, we know we have not yet initialized
1600          * the array.
1601          */
1602         if (!mddev->events && super_init_validation(rs, rdev))
1603                 return -EINVAL;
1604
1605         if (sb->compat_features || sb->incompat_features) {
1606                 rs->ti->error = "Unable to assemble array: No feature flags supported yet";
1607                 return -EINVAL;
1608         }
1609
1610         /* Enable bitmap creation for RAID levels != 0 */
1611         mddev->bitmap_info.offset = rt_is_raid0(rs->raid_type) ? 0 : to_sector(4096);
1612         rdev->mddev->bitmap_info.default_offset = mddev->bitmap_info.offset;
1613
1614         if (!test_and_clear_bit(FirstUse, &rdev->flags)) {
1615                 /* Retrieve device size stored in superblock to be prepared for shrink */
1616                 rdev->sectors = le64_to_cpu(sb->sectors);
1617                 rdev->recovery_offset = le64_to_cpu(sb->disk_recovery_offset);
1618                 if (rdev->recovery_offset == MaxSector)
1619                         set_bit(In_sync, &rdev->flags);
1620                 /*
1621                  * If no reshape in progress -> we're recovering single
1622                  * disk(s) and have to set the device(s) to out-of-sync
1623                  */
1624                 else if (rs->md.reshape_position == MaxSector)
1625                         clear_bit(In_sync, &rdev->flags); /* Mandatory for recovery */
1626         }
1627
1628         /*
1629          * If a device comes back, set it as not In_sync and no longer faulty.
1630          */
1631         if (test_and_clear_bit(Faulty, &rdev->flags)) {
1632                 rdev->recovery_offset = 0;
1633                 clear_bit(In_sync, &rdev->flags);
1634                 rdev->saved_raid_disk = rdev->raid_disk;
1635         }
1636
1637         /* Reshape support -> restore repective data offsets */
1638         rdev->data_offset = le64_to_cpu(sb->data_offset);
1639         rdev->new_data_offset = le64_to_cpu(sb->new_data_offset);
1640
1641         return 0;
1642 }
1643
1644 /*
1645  * Analyse superblocks and select the freshest.
1646  */
1647 static int analyse_superblocks(struct dm_target *ti, struct raid_set *rs)
1648 {
1649         int r;
1650         struct raid_dev *dev;
1651         struct md_rdev *rdev, *tmp, *freshest;
1652         struct mddev *mddev = &rs->md;
1653
1654         freshest = NULL;
1655         rdev_for_each_safe(rdev, tmp, mddev) {
1656                 /*
1657                  * Skipping super_load due to CTR_FLAG_SYNC will cause
1658                  * the array to undergo initialization again as
1659                  * though it were new.  This is the intended effect
1660                  * of the "sync" directive.
1661                  *
1662                  * When reshaping capability is added, we must ensure
1663                  * that the "sync" directive is disallowed during the
1664                  * reshape.
1665                  */
1666                 rdev->sectors = to_sector(i_size_read(rdev->bdev->bd_inode));
1667
1668                 if (_test_flag(CTR_FLAG_SYNC, rs->ctr_flags))
1669                         continue;
1670
1671                 if (!rdev->meta_bdev)
1672                         continue;
1673
1674                 r = super_load(rdev, freshest);
1675
1676                 switch (r) {
1677                 case 1:
1678                         freshest = rdev;
1679                         break;
1680                 case 0:
1681                         break;
1682                 default:
1683                         dev = container_of(rdev, struct raid_dev, rdev);
1684                         if (dev->meta_dev)
1685                                 dm_put_device(ti, dev->meta_dev);
1686
1687                         dev->meta_dev = NULL;
1688                         rdev->meta_bdev = NULL;
1689
1690                         if (rdev->sb_page)
1691                                 put_page(rdev->sb_page);
1692
1693                         rdev->sb_page = NULL;
1694
1695                         rdev->sb_loaded = 0;
1696
1697                         /*
1698                          * We might be able to salvage the data device
1699                          * even though the meta device has failed.  For
1700                          * now, we behave as though '- -' had been
1701                          * set for this device in the table.
1702                          */
1703                         if (dev->data_dev)
1704                                 dm_put_device(ti, dev->data_dev);
1705
1706                         dev->data_dev = NULL;
1707                         rdev->bdev = NULL;
1708
1709                         list_del(&rdev->same_set);
1710                 }
1711         }
1712
1713         if (!freshest)
1714                 return 0;
1715
1716         if (validate_raid_redundancy(rs))
1717                 return ti_error_einval(rs->ti, "Insufficient redundancy to activate array");
1718
1719         /*
1720          * Validation of the freshest device provides the source of
1721          * validation for the remaining devices.
1722          */
1723         if (super_validate(rs, freshest))
1724                 return ti_error_einval(rs->ti, "Unable to assemble array: Invalid superblocks");
1725
1726         rdev_for_each(rdev, mddev)
1727                 if ((rdev != freshest) && super_validate(rs, rdev))
1728                         return -EINVAL;
1729
1730         return 0;
1731 }
1732
1733 /*
1734  * Enable/disable discard support on RAID set depending on
1735  * RAID level and discard properties of underlying RAID members.
1736  */
1737 static void configure_discard_support(struct dm_target *ti, struct raid_set *rs)
1738 {
1739         int i;
1740         bool raid456;
1741
1742         /* Assume discards not supported until after checks below. */
1743         ti->discards_supported = false;
1744
1745         /* RAID level 4,5,6 require discard_zeroes_data for data integrity! */
1746         raid456 = (rs->md.level == 4 || rs->md.level == 5 || rs->md.level == 6);
1747
1748         for (i = 0; i < rs->md.raid_disks; i++) {
1749                 struct request_queue *q;
1750
1751                 if (!rs->dev[i].rdev.bdev)
1752                         continue;
1753
1754                 q = bdev_get_queue(rs->dev[i].rdev.bdev);
1755                 if (!q || !blk_queue_discard(q))
1756                         return;
1757
1758                 if (raid456) {
1759                         if (!q->limits.discard_zeroes_data)
1760                                 return;
1761                         if (!devices_handle_discard_safely) {
1762                                 DMERR("raid456 discard support disabled due to discard_zeroes_data uncertainty.");
1763                                 DMERR("Set dm-raid.devices_handle_discard_safely=Y to override.");
1764                                 return;
1765                         }
1766                 }
1767         }
1768
1769         /* All RAID members properly support discards */
1770         ti->discards_supported = true;
1771
1772         /*
1773          * RAID1 and RAID10 personalities require bio splitting,
1774          * RAID0/4/5/6 don't and process large discard bios properly.
1775          */
1776         ti->split_discard_bios = !!(rs->md.level == 1 || rs->md.level == 10);
1777         ti->num_discard_bios = 1;
1778 }
1779
1780 /*
1781  * Construct a RAID0/1/10/4/5/6 mapping:
1782  * Args:
1783  *      <raid_type> <#raid_params> <raid_params>{0,}    \
1784  *      <#raid_devs> [<meta_dev1> <dev1>]{1,}
1785  *
1786  * <raid_params> varies by <raid_type>.  See 'parse_raid_params' for
1787  * details on possible <raid_params>.
1788  *
1789  * Userspace is free to initialize the metadata devices, hence the superblocks to
1790  * enforce recreation based on the passed in table parameters.
1791  *
1792  */
1793 static int raid_ctr(struct dm_target *ti, unsigned argc, char **argv)
1794 {
1795         int r;
1796         struct raid_type *rt;
1797         unsigned num_raid_params, num_raid_devs;
1798         struct raid_set *rs = NULL;
1799         const char *arg;
1800         struct dm_arg_set as = { argc, argv }, as_nrd;
1801         struct dm_arg _args[] = {
1802                 { 0, as.argc, "Cannot understand number of raid parameters" },
1803                 { 1, 254, "Cannot understand number of raid devices parameters" }
1804         };
1805
1806         /* Must have <raid_type> */
1807         arg = dm_shift_arg(&as);
1808         if (!arg)
1809                 return ti_error_einval(rs->ti, "No arguments");
1810
1811         rt = get_raid_type(arg);
1812         if (!rt)
1813                 return ti_error_einval(rs->ti, "Unrecognised raid_type");
1814
1815         /* Must have <#raid_params> */
1816         if (dm_read_arg_group(_args, &as, &num_raid_params, &ti->error))
1817                 return -EINVAL;
1818
1819         /* number of raid device tupples <meta_dev data_dev> */
1820         as_nrd = as;
1821         dm_consume_args(&as_nrd, num_raid_params);
1822         _args[1].max = (as_nrd.argc - 1) / 2;
1823         if (dm_read_arg(_args + 1, &as_nrd, &num_raid_devs, &ti->error))
1824                 return -EINVAL;
1825
1826         if (!_in_range(num_raid_devs, 1, MAX_RAID_DEVICES))
1827                 return ti_error_einval(rs->ti, "Invalid number of supplied raid devices");
1828
1829         rs = context_alloc(ti, rt, num_raid_devs);
1830         if (IS_ERR(rs))
1831                 return PTR_ERR(rs);
1832
1833         r = parse_raid_params(rs, &as, num_raid_params);
1834         if (r)
1835                 goto bad;
1836
1837         r = parse_dev_params(rs, &as);
1838         if (r)
1839                 goto bad;
1840
1841         rs->md.sync_super = super_sync;
1842         r = analyse_superblocks(ti, rs);
1843         if (r)
1844                 goto bad;
1845
1846         INIT_WORK(&rs->md.event_work, do_table_event);
1847         ti->private = rs;
1848         ti->num_flush_bios = 1;
1849
1850         /*
1851          * Disable/enable discard support on RAID set.
1852          */
1853         configure_discard_support(ti, rs);
1854
1855         /* Has to be held on running the array */
1856         mddev_lock_nointr(&rs->md);
1857         r = md_run(&rs->md);
1858         rs->md.in_sync = 0; /* Assume already marked dirty */
1859         mddev_unlock(&rs->md);
1860
1861         if (r) {
1862                 ti->error = "Fail to run raid array";
1863                 goto bad;
1864         }
1865
1866         if (ti->len != rs->md.array_sectors) {
1867                 r = ti_error_einval(ti, "Array size does not match requested target length");
1868                 goto size_mismatch;
1869         }
1870         rs->callbacks.congested_fn = raid_is_congested;
1871         dm_table_add_target_callbacks(ti->table, &rs->callbacks);
1872
1873         mddev_suspend(&rs->md);
1874         return 0;
1875
1876 size_mismatch:
1877         md_stop(&rs->md);
1878 bad:
1879         context_free(rs);
1880
1881         return r;
1882 }
1883
1884 static void raid_dtr(struct dm_target *ti)
1885 {
1886         struct raid_set *rs = ti->private;
1887
1888         list_del_init(&rs->callbacks.list);
1889         md_stop(&rs->md);
1890         context_free(rs);
1891 }
1892
1893 static int raid_map(struct dm_target *ti, struct bio *bio)
1894 {
1895         struct raid_set *rs = ti->private;
1896         struct mddev *mddev = &rs->md;
1897
1898         mddev->pers->make_request(mddev, bio);
1899
1900         return DM_MAPIO_SUBMITTED;
1901 }
1902
1903 static const char *decipher_sync_action(struct mddev *mddev)
1904 {
1905         if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
1906                 return "frozen";
1907
1908         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
1909             (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
1910                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
1911                         return "reshape";
1912
1913                 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
1914                         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
1915                                 return "resync";
1916                         else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
1917                                 return "check";
1918                         return "repair";
1919                 }
1920
1921                 if (test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
1922                         return "recover";
1923         }
1924
1925         return "idle";
1926 }
1927
1928 static void raid_status(struct dm_target *ti, status_type_t type,
1929                         unsigned status_flags, char *result, unsigned maxlen)
1930 {
1931         struct raid_set *rs = ti->private;
1932         unsigned raid_param_cnt = 1; /* at least 1 for chunksize */
1933         unsigned sz = 0;
1934         int i, array_in_sync = 0;
1935         sector_t sync;
1936
1937         switch (type) {
1938         case STATUSTYPE_INFO:
1939                 DMEMIT("%s %d ", rs->raid_type->name, rs->md.raid_disks);
1940
1941                 if (!rt_is_raid0(rs->raid_type)) {
1942                         if (test_bit(MD_RECOVERY_RUNNING, &rs->md.recovery))
1943                                 sync = rs->md.curr_resync_completed;
1944                         else
1945                                 sync = rs->md.recovery_cp;
1946
1947                         if (sync >= rs->md.resync_max_sectors) {
1948                                 /*
1949                                  * Sync complete.
1950                                  */
1951                                 array_in_sync = 1;
1952                                 sync = rs->md.resync_max_sectors;
1953                         } else if (test_bit(MD_RECOVERY_REQUESTED, &rs->md.recovery)) {
1954                                 /*
1955                                  * If "check" or "repair" is occurring, the array has
1956                                  * undergone and initial sync and the health characters
1957                                  * should not be 'a' anymore.
1958                                  */
1959                                 array_in_sync = 1;
1960                         } else {
1961                                 /*
1962                                  * The array may be doing an initial sync, or it may
1963                                  * be rebuilding individual components.  If all the
1964                                  * devices are In_sync, then it is the array that is
1965                                  * being initialized.
1966                                  */
1967                                 for (i = 0; i < rs->md.raid_disks; i++)
1968                                         if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
1969                                                 array_in_sync = 1;
1970                         }
1971                 } else {
1972                         /* RAID0 */
1973                         array_in_sync = 1;
1974                         sync = rs->md.resync_max_sectors;
1975                 }
1976
1977                 /*
1978                  * Status characters:
1979                  *  'D' = Dead/Failed device
1980                  *  'a' = Alive but not in-sync
1981                  *  'A' = Alive and in-sync
1982                  */
1983                 for (i = 0; i < rs->md.raid_disks; i++) {
1984                         if (test_bit(Faulty, &rs->dev[i].rdev.flags))
1985                                 DMEMIT("D");
1986                         else if (!array_in_sync ||
1987                                  !test_bit(In_sync, &rs->dev[i].rdev.flags))
1988                                 DMEMIT("a");
1989                         else
1990                                 DMEMIT("A");
1991                 }
1992
1993                 /*
1994                  * In-sync ratio:
1995                  *  The in-sync ratio shows the progress of:
1996                  *   - Initializing the array
1997                  *   - Rebuilding a subset of devices of the array
1998                  *  The user can distinguish between the two by referring
1999                  *  to the status characters.
2000                  */
2001                 DMEMIT(" %llu/%llu",
2002                        (unsigned long long) sync,
2003                        (unsigned long long) rs->md.resync_max_sectors);
2004
2005                 /*
2006                  * Sync action:
2007                  *   See Documentation/device-mapper/dm-raid.c for
2008                  *   information on each of these states.
2009                  */
2010                 DMEMIT(" %s", decipher_sync_action(&rs->md));
2011
2012                 /*
2013                  * resync_mismatches/mismatch_cnt
2014                  *   This field shows the number of discrepancies found when
2015                  *   performing a "check" of the array.
2016                  */
2017                 DMEMIT(" %llu",
2018                        (strcmp(rs->md.last_sync_action, "check")) ? 0 :
2019                        (unsigned long long)
2020                        atomic64_read(&rs->md.resync_mismatches));
2021                 break;
2022         case STATUSTYPE_TABLE:
2023                 /* The string you would use to construct this array */
2024                 for (i = 0; i < rs->md.raid_disks; i++) {
2025                         if (_test_flag(CTR_FLAG_REBUILD, rs->ctr_flags) &&
2026                             rs->dev[i].data_dev &&
2027                             !test_bit(In_sync, &rs->dev[i].rdev.flags))
2028                                 raid_param_cnt += 2; /* for rebuilds */
2029                         if (rs->dev[i].data_dev &&
2030                             test_bit(WriteMostly, &rs->dev[i].rdev.flags))
2031                                 raid_param_cnt += 2;
2032                 }
2033
2034                 raid_param_cnt += (hweight32(rs->ctr_flags & ~CTR_FLAG_REBUILD) * 2);
2035                 if (rs->ctr_flags & (CTR_FLAG_SYNC | CTR_FLAG_NOSYNC))
2036                         raid_param_cnt--;
2037
2038                 DMEMIT("%s %u %u", rs->raid_type->name,
2039                        raid_param_cnt, rs->md.chunk_sectors);
2040
2041                 if (_test_flag(CTR_FLAG_SYNC, rs->ctr_flags) &&
2042                     rs->md.recovery_cp == MaxSector)
2043                         DMEMIT(" sync");
2044                 if (_test_flag(CTR_FLAG_NOSYNC, rs->ctr_flags))
2045                         DMEMIT(" nosync");
2046
2047                 for (i = 0; i < rs->md.raid_disks; i++)
2048                         if (_test_flag(CTR_FLAG_REBUILD, rs->ctr_flags) &&
2049                             rs->dev[i].data_dev &&
2050                             !test_bit(In_sync, &rs->dev[i].rdev.flags))
2051                                 DMEMIT(" rebuild %u", i);
2052
2053                 if (_test_flag(CTR_FLAG_DAEMON_SLEEP, rs->ctr_flags))
2054                         DMEMIT(" daemon_sleep %lu",
2055                                rs->md.bitmap_info.daemon_sleep);
2056
2057                 if (_test_flag(CTR_FLAG_MIN_RECOVERY_RATE, rs->ctr_flags))
2058                         DMEMIT(" min_recovery_rate %d", rs->md.sync_speed_min);
2059
2060                 if (_test_flag(CTR_FLAG_MAX_RECOVERY_RATE, rs->ctr_flags))
2061                         DMEMIT(" max_recovery_rate %d", rs->md.sync_speed_max);
2062
2063                 for (i = 0; i < rs->md.raid_disks; i++)
2064                         if (rs->dev[i].data_dev &&
2065                             test_bit(WriteMostly, &rs->dev[i].rdev.flags))
2066                                 DMEMIT(" write_mostly %u", i);
2067
2068                 if (_test_flag(CTR_FLAG_MAX_WRITE_BEHIND, rs->ctr_flags))
2069                         DMEMIT(" max_write_behind %lu",
2070                                rs->md.bitmap_info.max_write_behind);
2071
2072                 if (_test_flag(CTR_FLAG_STRIPE_CACHE, rs->ctr_flags)) {
2073                         struct r5conf *conf = rs->md.private;
2074
2075                         /* convert from kiB to sectors */
2076                         DMEMIT(" stripe_cache %d",
2077                                conf ? conf->max_nr_stripes * 2 : 0);
2078                 }
2079
2080                 if (_test_flag(CTR_FLAG_REGION_SIZE, rs->ctr_flags))
2081                         DMEMIT(" region_size %lu",
2082                                rs->md.bitmap_info.chunksize >> 9);
2083
2084                 if (_test_flag(CTR_FLAG_RAID10_COPIES, rs->ctr_flags))
2085                         DMEMIT(" raid10_copies %u",
2086                                raid10_md_layout_to_copies(rs->md.layout));
2087
2088                 if (_test_flag(CTR_FLAG_RAID10_FORMAT, rs->ctr_flags))
2089                         DMEMIT(" raid10_format %s",
2090                                raid10_md_layout_to_format(rs->md.layout));
2091
2092                 DMEMIT(" %d", rs->md.raid_disks);
2093                 for (i = 0; i < rs->md.raid_disks; i++) {
2094                         if (rs->dev[i].meta_dev)
2095                                 DMEMIT(" %s", rs->dev[i].meta_dev->name);
2096                         else
2097                                 DMEMIT(" -");
2098
2099                         if (rs->dev[i].data_dev)
2100                                 DMEMIT(" %s", rs->dev[i].data_dev->name);
2101                         else
2102                                 DMEMIT(" -");
2103                 }
2104         }
2105 }
2106
2107 static int raid_message(struct dm_target *ti, unsigned argc, char **argv)
2108 {
2109         struct raid_set *rs = ti->private;
2110         struct mddev *mddev = &rs->md;
2111
2112         if (!strcasecmp(argv[0], "reshape")) {
2113                 DMERR("Reshape not supported.");
2114                 return -EINVAL;
2115         }
2116
2117         if (!mddev->pers || !mddev->pers->sync_request)
2118                 return -EINVAL;
2119
2120         if (!strcasecmp(argv[0], "frozen"))
2121                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
2122         else
2123                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
2124
2125         if (!strcasecmp(argv[0], "idle") || !strcasecmp(argv[0], "frozen")) {
2126                 if (mddev->sync_thread) {
2127                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2128                         md_reap_sync_thread(mddev);
2129                 }
2130         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
2131                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
2132                 return -EBUSY;
2133         else if (!strcasecmp(argv[0], "resync"))
2134                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2135         else if (!strcasecmp(argv[0], "recover")) {
2136                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
2137                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2138         } else {
2139                 if (!strcasecmp(argv[0], "check"))
2140                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
2141                 else if (!!strcasecmp(argv[0], "repair"))
2142                         return -EINVAL;
2143                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
2144                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
2145         }
2146         if (mddev->ro == 2) {
2147                 /* A write to sync_action is enough to justify
2148                  * canceling read-auto mode
2149                  */
2150                 mddev->ro = 0;
2151                 if (!mddev->suspended)
2152                         md_wakeup_thread(mddev->sync_thread);
2153         }
2154         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2155         if (!mddev->suspended)
2156                 md_wakeup_thread(mddev->thread);
2157
2158         return 0;
2159 }
2160
2161 static int raid_iterate_devices(struct dm_target *ti,
2162                                 iterate_devices_callout_fn fn, void *data)
2163 {
2164         struct raid_set *rs = ti->private;
2165         unsigned i;
2166         int r = 0;
2167
2168         for (i = 0; !r && i < rs->md.raid_disks; i++)
2169                 if (rs->dev[i].data_dev)
2170                         r = fn(ti,
2171                                  rs->dev[i].data_dev,
2172                                  0, /* No offset on data devs */
2173                                  rs->md.dev_sectors,
2174                                  data);
2175
2176         return r;
2177 }
2178
2179 static void raid_io_hints(struct dm_target *ti, struct queue_limits *limits)
2180 {
2181         struct raid_set *rs = ti->private;
2182         unsigned chunk_size = rs->md.chunk_sectors << 9;
2183         struct r5conf *conf = rs->md.private;
2184
2185         blk_limits_io_min(limits, chunk_size);
2186         blk_limits_io_opt(limits, chunk_size * (conf->raid_disks - conf->max_degraded));
2187 }
2188
2189 static void raid_presuspend(struct dm_target *ti)
2190 {
2191         struct raid_set *rs = ti->private;
2192
2193         md_stop_writes(&rs->md);
2194 }
2195
2196 static void raid_postsuspend(struct dm_target *ti)
2197 {
2198         struct raid_set *rs = ti->private;
2199
2200         mddev_suspend(&rs->md);
2201 }
2202
2203 static void attempt_restore_of_faulty_devices(struct raid_set *rs)
2204 {
2205         int i;
2206         uint64_t failed_devices, cleared_failed_devices = 0;
2207         unsigned long flags;
2208         struct dm_raid_superblock *sb;
2209         struct md_rdev *r;
2210
2211         for (i = 0; i < rs->md.raid_disks; i++) {
2212                 r = &rs->dev[i].rdev;
2213                 if (test_bit(Faulty, &r->flags) && r->sb_page &&
2214                     sync_page_io(r, 0, r->sb_size, r->sb_page, REQ_OP_READ, 0,
2215                                  1)) {
2216                         DMINFO("Faulty %s device #%d has readable super block."
2217                                "  Attempting to revive it.",
2218                                rs->raid_type->name, i);
2219
2220                         /*
2221                          * Faulty bit may be set, but sometimes the array can
2222                          * be suspended before the personalities can respond
2223                          * by removing the device from the array (i.e. calling
2224                          * 'hot_remove_disk').  If they haven't yet removed
2225                          * the failed device, its 'raid_disk' number will be
2226                          * '>= 0' - meaning we must call this function
2227                          * ourselves.
2228                          */
2229                         if ((r->raid_disk >= 0) &&
2230                             (r->mddev->pers->hot_remove_disk(r->mddev, r) != 0))
2231                                 /* Failed to revive this device, try next */
2232                                 continue;
2233
2234                         r->raid_disk = i;
2235                         r->saved_raid_disk = i;
2236                         flags = r->flags;
2237                         clear_bit(Faulty, &r->flags);
2238                         clear_bit(WriteErrorSeen, &r->flags);
2239                         clear_bit(In_sync, &r->flags);
2240                         if (r->mddev->pers->hot_add_disk(r->mddev, r)) {
2241                                 r->raid_disk = -1;
2242                                 r->saved_raid_disk = -1;
2243                                 r->flags = flags;
2244                         } else {
2245                                 r->recovery_offset = 0;
2246                                 cleared_failed_devices |= 1 << i;
2247                         }
2248                 }
2249         }
2250         if (cleared_failed_devices) {
2251                 rdev_for_each(r, &rs->md) {
2252                         sb = page_address(r->sb_page);
2253                         failed_devices = le64_to_cpu(sb->failed_devices);
2254                         failed_devices &= ~cleared_failed_devices;
2255                         sb->failed_devices = cpu_to_le64(failed_devices);
2256                 }
2257         }
2258 }
2259
2260 static void raid_resume(struct dm_target *ti)
2261 {
2262         struct raid_set *rs = ti->private;
2263
2264         if (!rt_is_raid0(rs->raid_type)) {
2265                 set_bit(MD_CHANGE_DEVS, &rs->md.flags);
2266
2267                 if (!rs->bitmap_loaded) {
2268                         bitmap_load(&rs->md);
2269                         rs->bitmap_loaded = 1;
2270                 } else {
2271                         /*
2272                          * A secondary resume while the device is active.
2273                          * Take this opportunity to check whether any failed
2274                          * devices are reachable again.
2275                          */
2276                         attempt_restore_of_faulty_devices(rs);
2277                 }
2278
2279                 clear_bit(MD_RECOVERY_FROZEN, &rs->md.recovery);
2280         }
2281
2282         mddev_resume(&rs->md);
2283 }
2284
2285 static struct target_type raid_target = {
2286         .name = "raid",
2287         .version = {1, 8, 1},
2288         .module = THIS_MODULE,
2289         .ctr = raid_ctr,
2290         .dtr = raid_dtr,
2291         .map = raid_map,
2292         .status = raid_status,
2293         .message = raid_message,
2294         .iterate_devices = raid_iterate_devices,
2295         .io_hints = raid_io_hints,
2296         .presuspend = raid_presuspend,
2297         .postsuspend = raid_postsuspend,
2298         .resume = raid_resume,
2299 };
2300
2301 static int __init dm_raid_init(void)
2302 {
2303         DMINFO("Loading target version %u.%u.%u",
2304                raid_target.version[0],
2305                raid_target.version[1],
2306                raid_target.version[2]);
2307         return dm_register_target(&raid_target);
2308 }
2309
2310 static void __exit dm_raid_exit(void)
2311 {
2312         dm_unregister_target(&raid_target);
2313 }
2314
2315 module_init(dm_raid_init);
2316 module_exit(dm_raid_exit);
2317
2318 module_param(devices_handle_discard_safely, bool, 0644);
2319 MODULE_PARM_DESC(devices_handle_discard_safely,
2320                  "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
2321
2322 MODULE_DESCRIPTION(DM_NAME " raid4/5/6 target");
2323 MODULE_ALIAS("dm-raid1");
2324 MODULE_ALIAS("dm-raid10");
2325 MODULE_ALIAS("dm-raid4");
2326 MODULE_ALIAS("dm-raid5");
2327 MODULE_ALIAS("dm-raid6");
2328 MODULE_AUTHOR("Neil Brown <dm-devel@redhat.com>");
2329 MODULE_LICENSE("GPL");