Merge branch 'for-linus' into for-next
[platform/kernel/linux-rpi.git] / drivers / md / dm-raid.c
1 /*
2  * Copyright (C) 2010-2011 Neil Brown
3  * Copyright (C) 2010-2018 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 "md-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 /*
23  * Minimum sectors of free reshape space per raid device
24  */
25 #define MIN_FREE_RESHAPE_SPACE to_sector(4*4096)
26
27 /*
28  * Minimum journal space 4 MiB in sectors.
29  */
30 #define MIN_RAID456_JOURNAL_SPACE (4*2048)
31
32 static bool devices_handle_discard_safely = false;
33
34 /*
35  * The following flags are used by dm-raid.c to set up the array state.
36  * They must be cleared before md_run is called.
37  */
38 #define FirstUse 10             /* rdev flag */
39
40 struct raid_dev {
41         /*
42          * Two DM devices, one to hold metadata and one to hold the
43          * actual data/parity.  The reason for this is to not confuse
44          * ti->len and give more flexibility in altering size and
45          * characteristics.
46          *
47          * While it is possible for this device to be associated
48          * with a different physical device than the data_dev, it
49          * is intended for it to be the same.
50          *    |--------- Physical Device ---------|
51          *    |- meta_dev -|------ data_dev ------|
52          */
53         struct dm_dev *meta_dev;
54         struct dm_dev *data_dev;
55         struct md_rdev rdev;
56 };
57
58 /*
59  * Bits for establishing rs->ctr_flags
60  *
61  * 1 = no flag value
62  * 2 = flag with value
63  */
64 #define __CTR_FLAG_SYNC                 0  /* 1 */ /* Not with raid0! */
65 #define __CTR_FLAG_NOSYNC               1  /* 1 */ /* Not with raid0! */
66 #define __CTR_FLAG_REBUILD              2  /* 2 */ /* Not with raid0! */
67 #define __CTR_FLAG_DAEMON_SLEEP         3  /* 2 */ /* Not with raid0! */
68 #define __CTR_FLAG_MIN_RECOVERY_RATE    4  /* 2 */ /* Not with raid0! */
69 #define __CTR_FLAG_MAX_RECOVERY_RATE    5  /* 2 */ /* Not with raid0! */
70 #define __CTR_FLAG_MAX_WRITE_BEHIND     6  /* 2 */ /* Only with raid1! */
71 #define __CTR_FLAG_WRITE_MOSTLY         7  /* 2 */ /* Only with raid1! */
72 #define __CTR_FLAG_STRIPE_CACHE         8  /* 2 */ /* Only with raid4/5/6! */
73 #define __CTR_FLAG_REGION_SIZE          9  /* 2 */ /* Not with raid0! */
74 #define __CTR_FLAG_RAID10_COPIES        10 /* 2 */ /* Only with raid10 */
75 #define __CTR_FLAG_RAID10_FORMAT        11 /* 2 */ /* Only with raid10 */
76 /* New for v1.9.0 */
77 #define __CTR_FLAG_DELTA_DISKS          12 /* 2 */ /* Only with reshapable raid1/4/5/6/10! */
78 #define __CTR_FLAG_DATA_OFFSET          13 /* 2 */ /* Only with reshapable raid4/5/6/10! */
79 #define __CTR_FLAG_RAID10_USE_NEAR_SETS 14 /* 2 */ /* Only with raid10! */
80
81 /* New for v1.10.0 */
82 #define __CTR_FLAG_JOURNAL_DEV          15 /* 2 */ /* Only with raid4/5/6 (journal device)! */
83
84 /* New for v1.11.1 */
85 #define __CTR_FLAG_JOURNAL_MODE         16 /* 2 */ /* Only with raid4/5/6 (journal mode)! */
86
87 /*
88  * Flags for rs->ctr_flags field.
89  */
90 #define CTR_FLAG_SYNC                   (1 << __CTR_FLAG_SYNC)
91 #define CTR_FLAG_NOSYNC                 (1 << __CTR_FLAG_NOSYNC)
92 #define CTR_FLAG_REBUILD                (1 << __CTR_FLAG_REBUILD)
93 #define CTR_FLAG_DAEMON_SLEEP           (1 << __CTR_FLAG_DAEMON_SLEEP)
94 #define CTR_FLAG_MIN_RECOVERY_RATE      (1 << __CTR_FLAG_MIN_RECOVERY_RATE)
95 #define CTR_FLAG_MAX_RECOVERY_RATE      (1 << __CTR_FLAG_MAX_RECOVERY_RATE)
96 #define CTR_FLAG_MAX_WRITE_BEHIND       (1 << __CTR_FLAG_MAX_WRITE_BEHIND)
97 #define CTR_FLAG_WRITE_MOSTLY           (1 << __CTR_FLAG_WRITE_MOSTLY)
98 #define CTR_FLAG_STRIPE_CACHE           (1 << __CTR_FLAG_STRIPE_CACHE)
99 #define CTR_FLAG_REGION_SIZE            (1 << __CTR_FLAG_REGION_SIZE)
100 #define CTR_FLAG_RAID10_COPIES          (1 << __CTR_FLAG_RAID10_COPIES)
101 #define CTR_FLAG_RAID10_FORMAT          (1 << __CTR_FLAG_RAID10_FORMAT)
102 #define CTR_FLAG_DELTA_DISKS            (1 << __CTR_FLAG_DELTA_DISKS)
103 #define CTR_FLAG_DATA_OFFSET            (1 << __CTR_FLAG_DATA_OFFSET)
104 #define CTR_FLAG_RAID10_USE_NEAR_SETS   (1 << __CTR_FLAG_RAID10_USE_NEAR_SETS)
105 #define CTR_FLAG_JOURNAL_DEV            (1 << __CTR_FLAG_JOURNAL_DEV)
106 #define CTR_FLAG_JOURNAL_MODE           (1 << __CTR_FLAG_JOURNAL_MODE)
107
108 /*
109  * Definitions of various constructor flags to
110  * be used in checks of valid / invalid flags
111  * per raid level.
112  */
113 /* Define all any sync flags */
114 #define CTR_FLAGS_ANY_SYNC              (CTR_FLAG_SYNC | CTR_FLAG_NOSYNC)
115
116 /* Define flags for options without argument (e.g. 'nosync') */
117 #define CTR_FLAG_OPTIONS_NO_ARGS        (CTR_FLAGS_ANY_SYNC | \
118                                          CTR_FLAG_RAID10_USE_NEAR_SETS)
119
120 /* Define flags for options with one argument (e.g. 'delta_disks +2') */
121 #define CTR_FLAG_OPTIONS_ONE_ARG (CTR_FLAG_REBUILD | \
122                                   CTR_FLAG_WRITE_MOSTLY | \
123                                   CTR_FLAG_DAEMON_SLEEP | \
124                                   CTR_FLAG_MIN_RECOVERY_RATE | \
125                                   CTR_FLAG_MAX_RECOVERY_RATE | \
126                                   CTR_FLAG_MAX_WRITE_BEHIND | \
127                                   CTR_FLAG_STRIPE_CACHE | \
128                                   CTR_FLAG_REGION_SIZE | \
129                                   CTR_FLAG_RAID10_COPIES | \
130                                   CTR_FLAG_RAID10_FORMAT | \
131                                   CTR_FLAG_DELTA_DISKS | \
132                                   CTR_FLAG_DATA_OFFSET)
133
134 /* Valid options definitions per raid level... */
135
136 /* "raid0" does only accept data offset */
137 #define RAID0_VALID_FLAGS       (CTR_FLAG_DATA_OFFSET)
138
139 /* "raid1" does not accept stripe cache, data offset, delta_disks or any raid10 options */
140 #define RAID1_VALID_FLAGS       (CTR_FLAGS_ANY_SYNC | \
141                                  CTR_FLAG_REBUILD | \
142                                  CTR_FLAG_WRITE_MOSTLY | \
143                                  CTR_FLAG_DAEMON_SLEEP | \
144                                  CTR_FLAG_MIN_RECOVERY_RATE | \
145                                  CTR_FLAG_MAX_RECOVERY_RATE | \
146                                  CTR_FLAG_MAX_WRITE_BEHIND | \
147                                  CTR_FLAG_REGION_SIZE | \
148                                  CTR_FLAG_DELTA_DISKS | \
149                                  CTR_FLAG_DATA_OFFSET)
150
151 /* "raid10" does not accept any raid1 or stripe cache options */
152 #define RAID10_VALID_FLAGS      (CTR_FLAGS_ANY_SYNC | \
153                                  CTR_FLAG_REBUILD | \
154                                  CTR_FLAG_DAEMON_SLEEP | \
155                                  CTR_FLAG_MIN_RECOVERY_RATE | \
156                                  CTR_FLAG_MAX_RECOVERY_RATE | \
157                                  CTR_FLAG_REGION_SIZE | \
158                                  CTR_FLAG_RAID10_COPIES | \
159                                  CTR_FLAG_RAID10_FORMAT | \
160                                  CTR_FLAG_DELTA_DISKS | \
161                                  CTR_FLAG_DATA_OFFSET | \
162                                  CTR_FLAG_RAID10_USE_NEAR_SETS)
163
164 /*
165  * "raid4/5/6" do not accept any raid1 or raid10 specific options
166  *
167  * "raid6" does not accept "nosync", because it is not guaranteed
168  * that both parity and q-syndrome are being written properly with
169  * any writes
170  */
171 #define RAID45_VALID_FLAGS      (CTR_FLAGS_ANY_SYNC | \
172                                  CTR_FLAG_REBUILD | \
173                                  CTR_FLAG_DAEMON_SLEEP | \
174                                  CTR_FLAG_MIN_RECOVERY_RATE | \
175                                  CTR_FLAG_MAX_RECOVERY_RATE | \
176                                  CTR_FLAG_STRIPE_CACHE | \
177                                  CTR_FLAG_REGION_SIZE | \
178                                  CTR_FLAG_DELTA_DISKS | \
179                                  CTR_FLAG_DATA_OFFSET | \
180                                  CTR_FLAG_JOURNAL_DEV | \
181                                  CTR_FLAG_JOURNAL_MODE)
182
183 #define RAID6_VALID_FLAGS       (CTR_FLAG_SYNC | \
184                                  CTR_FLAG_REBUILD | \
185                                  CTR_FLAG_DAEMON_SLEEP | \
186                                  CTR_FLAG_MIN_RECOVERY_RATE | \
187                                  CTR_FLAG_MAX_RECOVERY_RATE | \
188                                  CTR_FLAG_STRIPE_CACHE | \
189                                  CTR_FLAG_REGION_SIZE | \
190                                  CTR_FLAG_DELTA_DISKS | \
191                                  CTR_FLAG_DATA_OFFSET | \
192                                  CTR_FLAG_JOURNAL_DEV | \
193                                  CTR_FLAG_JOURNAL_MODE)
194 /* ...valid options definitions per raid level */
195
196 /*
197  * Flags for rs->runtime_flags field
198  * (RT_FLAG prefix meaning "runtime flag")
199  *
200  * These are all internal and used to define runtime state,
201  * e.g. to prevent another resume from preresume processing
202  * the raid set all over again.
203  */
204 #define RT_FLAG_RS_PRERESUMED           0
205 #define RT_FLAG_RS_RESUMED              1
206 #define RT_FLAG_RS_BITMAP_LOADED        2
207 #define RT_FLAG_UPDATE_SBS              3
208 #define RT_FLAG_RESHAPE_RS              4
209 #define RT_FLAG_RS_SUSPENDED            5
210 #define RT_FLAG_RS_IN_SYNC              6
211 #define RT_FLAG_RS_RESYNCING            7
212 #define RT_FLAG_RS_GROW                 8
213
214 /* Array elements of 64 bit needed for rebuild/failed disk bits */
215 #define DISKS_ARRAY_ELEMS ((MAX_RAID_DEVICES + (sizeof(uint64_t) * 8 - 1)) / sizeof(uint64_t) / 8)
216
217 /*
218  * raid set level, layout and chunk sectors backup/restore
219  */
220 struct rs_layout {
221         int new_level;
222         int new_layout;
223         int new_chunk_sectors;
224 };
225
226 struct raid_set {
227         struct dm_target *ti;
228
229         uint32_t stripe_cache_entries;
230         unsigned long ctr_flags;
231         unsigned long runtime_flags;
232
233         uint64_t rebuild_disks[DISKS_ARRAY_ELEMS];
234
235         int raid_disks;
236         int delta_disks;
237         int data_offset;
238         int raid10_copies;
239         int requested_bitmap_chunk_sectors;
240
241         struct mddev md;
242         struct raid_type *raid_type;
243         struct dm_target_callbacks callbacks;
244
245         sector_t array_sectors;
246         sector_t dev_sectors;
247
248         /* Optional raid4/5/6 journal device */
249         struct journal_dev {
250                 struct dm_dev *dev;
251                 struct md_rdev rdev;
252                 int mode;
253         } journal_dev;
254
255         struct raid_dev dev[0];
256 };
257
258 static void rs_config_backup(struct raid_set *rs, struct rs_layout *l)
259 {
260         struct mddev *mddev = &rs->md;
261
262         l->new_level = mddev->new_level;
263         l->new_layout = mddev->new_layout;
264         l->new_chunk_sectors = mddev->new_chunk_sectors;
265 }
266
267 static void rs_config_restore(struct raid_set *rs, struct rs_layout *l)
268 {
269         struct mddev *mddev = &rs->md;
270
271         mddev->new_level = l->new_level;
272         mddev->new_layout = l->new_layout;
273         mddev->new_chunk_sectors = l->new_chunk_sectors;
274 }
275
276 /* raid10 algorithms (i.e. formats) */
277 #define ALGORITHM_RAID10_DEFAULT        0
278 #define ALGORITHM_RAID10_NEAR           1
279 #define ALGORITHM_RAID10_OFFSET         2
280 #define ALGORITHM_RAID10_FAR            3
281
282 /* Supported raid types and properties. */
283 static struct raid_type {
284         const char *name;               /* RAID algorithm. */
285         const char *descr;              /* Descriptor text for logging. */
286         const unsigned int parity_devs; /* # of parity devices. */
287         const unsigned int minimal_devs;/* minimal # of devices in set. */
288         const unsigned int level;       /* RAID level. */
289         const unsigned int algorithm;   /* RAID algorithm. */
290 } raid_types[] = {
291         {"raid0",         "raid0 (striping)",                       0, 2, 0,  0 /* NONE */},
292         {"raid1",         "raid1 (mirroring)",                      0, 2, 1,  0 /* NONE */},
293         {"raid10_far",    "raid10 far (striped mirrors)",           0, 2, 10, ALGORITHM_RAID10_FAR},
294         {"raid10_offset", "raid10 offset (striped mirrors)",        0, 2, 10, ALGORITHM_RAID10_OFFSET},
295         {"raid10_near",   "raid10 near (striped mirrors)",          0, 2, 10, ALGORITHM_RAID10_NEAR},
296         {"raid10",        "raid10 (striped mirrors)",               0, 2, 10, ALGORITHM_RAID10_DEFAULT},
297         {"raid4",         "raid4 (dedicated first parity disk)",    1, 2, 5,  ALGORITHM_PARITY_0}, /* raid4 layout = raid5_0 */
298         {"raid5_n",       "raid5 (dedicated last parity disk)",     1, 2, 5,  ALGORITHM_PARITY_N},
299         {"raid5_ls",      "raid5 (left symmetric)",                 1, 2, 5,  ALGORITHM_LEFT_SYMMETRIC},
300         {"raid5_rs",      "raid5 (right symmetric)",                1, 2, 5,  ALGORITHM_RIGHT_SYMMETRIC},
301         {"raid5_la",      "raid5 (left asymmetric)",                1, 2, 5,  ALGORITHM_LEFT_ASYMMETRIC},
302         {"raid5_ra",      "raid5 (right asymmetric)",               1, 2, 5,  ALGORITHM_RIGHT_ASYMMETRIC},
303         {"raid6_zr",      "raid6 (zero restart)",                   2, 4, 6,  ALGORITHM_ROTATING_ZERO_RESTART},
304         {"raid6_nr",      "raid6 (N restart)",                      2, 4, 6,  ALGORITHM_ROTATING_N_RESTART},
305         {"raid6_nc",      "raid6 (N continue)",                     2, 4, 6,  ALGORITHM_ROTATING_N_CONTINUE},
306         {"raid6_n_6",     "raid6 (dedicated parity/Q n/6)",         2, 4, 6,  ALGORITHM_PARITY_N_6},
307         {"raid6_ls_6",    "raid6 (left symmetric dedicated Q 6)",   2, 4, 6,  ALGORITHM_LEFT_SYMMETRIC_6},
308         {"raid6_rs_6",    "raid6 (right symmetric dedicated Q 6)",  2, 4, 6,  ALGORITHM_RIGHT_SYMMETRIC_6},
309         {"raid6_la_6",    "raid6 (left asymmetric dedicated Q 6)",  2, 4, 6,  ALGORITHM_LEFT_ASYMMETRIC_6},
310         {"raid6_ra_6",    "raid6 (right asymmetric dedicated Q 6)", 2, 4, 6,  ALGORITHM_RIGHT_ASYMMETRIC_6}
311 };
312
313 /* True, if @v is in inclusive range [@min, @max] */
314 static bool __within_range(long v, long min, long max)
315 {
316         return v >= min && v <= max;
317 }
318
319 /* All table line arguments are defined here */
320 static struct arg_name_flag {
321         const unsigned long flag;
322         const char *name;
323 } __arg_name_flags[] = {
324         { CTR_FLAG_SYNC, "sync"},
325         { CTR_FLAG_NOSYNC, "nosync"},
326         { CTR_FLAG_REBUILD, "rebuild"},
327         { CTR_FLAG_DAEMON_SLEEP, "daemon_sleep"},
328         { CTR_FLAG_MIN_RECOVERY_RATE, "min_recovery_rate"},
329         { CTR_FLAG_MAX_RECOVERY_RATE, "max_recovery_rate"},
330         { CTR_FLAG_MAX_WRITE_BEHIND, "max_write_behind"},
331         { CTR_FLAG_WRITE_MOSTLY, "write_mostly"},
332         { CTR_FLAG_STRIPE_CACHE, "stripe_cache"},
333         { CTR_FLAG_REGION_SIZE, "region_size"},
334         { CTR_FLAG_RAID10_COPIES, "raid10_copies"},
335         { CTR_FLAG_RAID10_FORMAT, "raid10_format"},
336         { CTR_FLAG_DATA_OFFSET, "data_offset"},
337         { CTR_FLAG_DELTA_DISKS, "delta_disks"},
338         { CTR_FLAG_RAID10_USE_NEAR_SETS, "raid10_use_near_sets"},
339         { CTR_FLAG_JOURNAL_DEV, "journal_dev" },
340         { CTR_FLAG_JOURNAL_MODE, "journal_mode" },
341 };
342
343 /* Return argument name string for given @flag */
344 static const char *dm_raid_arg_name_by_flag(const uint32_t flag)
345 {
346         if (hweight32(flag) == 1) {
347                 struct arg_name_flag *anf = __arg_name_flags + ARRAY_SIZE(__arg_name_flags);
348
349                 while (anf-- > __arg_name_flags)
350                         if (flag & anf->flag)
351                                 return anf->name;
352
353         } else
354                 DMERR("%s called with more than one flag!", __func__);
355
356         return NULL;
357 }
358
359 /* Define correlation of raid456 journal cache modes and dm-raid target line parameters */
360 static struct {
361         const int mode;
362         const char *param;
363 } _raid456_journal_mode[] = {
364         { R5C_JOURNAL_MODE_WRITE_THROUGH , "writethrough" },
365         { R5C_JOURNAL_MODE_WRITE_BACK    , "writeback" }
366 };
367
368 /* Return MD raid4/5/6 journal mode for dm @journal_mode one */
369 static int dm_raid_journal_mode_to_md(const char *mode)
370 {
371         int m = ARRAY_SIZE(_raid456_journal_mode);
372
373         while (m--)
374                 if (!strcasecmp(mode, _raid456_journal_mode[m].param))
375                         return _raid456_journal_mode[m].mode;
376
377         return -EINVAL;
378 }
379
380 /* Return dm-raid raid4/5/6 journal mode string for @mode */
381 static const char *md_journal_mode_to_dm_raid(const int mode)
382 {
383         int m = ARRAY_SIZE(_raid456_journal_mode);
384
385         while (m--)
386                 if (mode == _raid456_journal_mode[m].mode)
387                         return _raid456_journal_mode[m].param;
388
389         return "unknown";
390 }
391
392 /*
393  * Bool helpers to test for various raid levels of a raid set.
394  * It's level as reported by the superblock rather than
395  * the requested raid_type passed to the constructor.
396  */
397 /* Return true, if raid set in @rs is raid0 */
398 static bool rs_is_raid0(struct raid_set *rs)
399 {
400         return !rs->md.level;
401 }
402
403 /* Return true, if raid set in @rs is raid1 */
404 static bool rs_is_raid1(struct raid_set *rs)
405 {
406         return rs->md.level == 1;
407 }
408
409 /* Return true, if raid set in @rs is raid10 */
410 static bool rs_is_raid10(struct raid_set *rs)
411 {
412         return rs->md.level == 10;
413 }
414
415 /* Return true, if raid set in @rs is level 6 */
416 static bool rs_is_raid6(struct raid_set *rs)
417 {
418         return rs->md.level == 6;
419 }
420
421 /* Return true, if raid set in @rs is level 4, 5 or 6 */
422 static bool rs_is_raid456(struct raid_set *rs)
423 {
424         return __within_range(rs->md.level, 4, 6);
425 }
426
427 /* Return true, if raid set in @rs is reshapable */
428 static bool __is_raid10_far(int layout);
429 static bool rs_is_reshapable(struct raid_set *rs)
430 {
431         return rs_is_raid456(rs) ||
432                (rs_is_raid10(rs) && !__is_raid10_far(rs->md.new_layout));
433 }
434
435 /* Return true, if raid set in @rs is recovering */
436 static bool rs_is_recovering(struct raid_set *rs)
437 {
438         return rs->md.recovery_cp < rs->md.dev_sectors;
439 }
440
441 /* Return true, if raid set in @rs is reshaping */
442 static bool rs_is_reshaping(struct raid_set *rs)
443 {
444         return rs->md.reshape_position != MaxSector;
445 }
446
447 /*
448  * bool helpers to test for various raid levels of a raid type @rt
449  */
450
451 /* Return true, if raid type in @rt is raid0 */
452 static bool rt_is_raid0(struct raid_type *rt)
453 {
454         return !rt->level;
455 }
456
457 /* Return true, if raid type in @rt is raid1 */
458 static bool rt_is_raid1(struct raid_type *rt)
459 {
460         return rt->level == 1;
461 }
462
463 /* Return true, if raid type in @rt is raid10 */
464 static bool rt_is_raid10(struct raid_type *rt)
465 {
466         return rt->level == 10;
467 }
468
469 /* Return true, if raid type in @rt is raid4/5 */
470 static bool rt_is_raid45(struct raid_type *rt)
471 {
472         return __within_range(rt->level, 4, 5);
473 }
474
475 /* Return true, if raid type in @rt is raid6 */
476 static bool rt_is_raid6(struct raid_type *rt)
477 {
478         return rt->level == 6;
479 }
480
481 /* Return true, if raid type in @rt is raid4/5/6 */
482 static bool rt_is_raid456(struct raid_type *rt)
483 {
484         return __within_range(rt->level, 4, 6);
485 }
486 /* END: raid level bools */
487
488 /* Return valid ctr flags for the raid level of @rs */
489 static unsigned long __valid_flags(struct raid_set *rs)
490 {
491         if (rt_is_raid0(rs->raid_type))
492                 return RAID0_VALID_FLAGS;
493         else if (rt_is_raid1(rs->raid_type))
494                 return RAID1_VALID_FLAGS;
495         else if (rt_is_raid10(rs->raid_type))
496                 return RAID10_VALID_FLAGS;
497         else if (rt_is_raid45(rs->raid_type))
498                 return RAID45_VALID_FLAGS;
499         else if (rt_is_raid6(rs->raid_type))
500                 return RAID6_VALID_FLAGS;
501
502         return 0;
503 }
504
505 /*
506  * Check for valid flags set on @rs
507  *
508  * Has to be called after parsing of the ctr flags!
509  */
510 static int rs_check_for_valid_flags(struct raid_set *rs)
511 {
512         if (rs->ctr_flags & ~__valid_flags(rs)) {
513                 rs->ti->error = "Invalid flags combination";
514                 return -EINVAL;
515         }
516
517         return 0;
518 }
519
520 /* MD raid10 bit definitions and helpers */
521 #define RAID10_OFFSET                   (1 << 16) /* stripes with data copies area adjacent on devices */
522 #define RAID10_BROCKEN_USE_FAR_SETS     (1 << 17) /* Broken in raid10.c: use sets instead of whole stripe rotation */
523 #define RAID10_USE_FAR_SETS             (1 << 18) /* Use sets instead of whole stripe rotation */
524 #define RAID10_FAR_COPIES_SHIFT         8         /* raid10 # far copies shift (2nd byte of layout) */
525
526 /* Return md raid10 near copies for @layout */
527 static unsigned int __raid10_near_copies(int layout)
528 {
529         return layout & 0xFF;
530 }
531
532 /* Return md raid10 far copies for @layout */
533 static unsigned int __raid10_far_copies(int layout)
534 {
535         return __raid10_near_copies(layout >> RAID10_FAR_COPIES_SHIFT);
536 }
537
538 /* Return true if md raid10 offset for @layout */
539 static bool __is_raid10_offset(int layout)
540 {
541         return !!(layout & RAID10_OFFSET);
542 }
543
544 /* Return true if md raid10 near for @layout */
545 static bool __is_raid10_near(int layout)
546 {
547         return !__is_raid10_offset(layout) && __raid10_near_copies(layout) > 1;
548 }
549
550 /* Return true if md raid10 far for @layout */
551 static bool __is_raid10_far(int layout)
552 {
553         return !__is_raid10_offset(layout) && __raid10_far_copies(layout) > 1;
554 }
555
556 /* Return md raid10 layout string for @layout */
557 static const char *raid10_md_layout_to_format(int layout)
558 {
559         /*
560          * Bit 16 stands for "offset"
561          * (i.e. adjacent stripes hold copies)
562          *
563          * Refer to MD's raid10.c for details
564          */
565         if (__is_raid10_offset(layout))
566                 return "offset";
567
568         if (__raid10_near_copies(layout) > 1)
569                 return "near";
570
571         if (__raid10_far_copies(layout) > 1)
572                 return "far";
573
574         return "unknown";
575 }
576
577 /* Return md raid10 algorithm for @name */
578 static int raid10_name_to_format(const char *name)
579 {
580         if (!strcasecmp(name, "near"))
581                 return ALGORITHM_RAID10_NEAR;
582         else if (!strcasecmp(name, "offset"))
583                 return ALGORITHM_RAID10_OFFSET;
584         else if (!strcasecmp(name, "far"))
585                 return ALGORITHM_RAID10_FAR;
586
587         return -EINVAL;
588 }
589
590 /* Return md raid10 copies for @layout */
591 static unsigned int raid10_md_layout_to_copies(int layout)
592 {
593         return max(__raid10_near_copies(layout), __raid10_far_copies(layout));
594 }
595
596 /* Return md raid10 format id for @format string */
597 static int raid10_format_to_md_layout(struct raid_set *rs,
598                                       unsigned int algorithm,
599                                       unsigned int copies)
600 {
601         unsigned int n = 1, f = 1, r = 0;
602
603         /*
604          * MD resilienece flaw:
605          *
606          * enabling use_far_sets for far/offset formats causes copies
607          * to be colocated on the same devs together with their origins!
608          *
609          * -> disable it for now in the definition above
610          */
611         if (algorithm == ALGORITHM_RAID10_DEFAULT ||
612             algorithm == ALGORITHM_RAID10_NEAR)
613                 n = copies;
614
615         else if (algorithm == ALGORITHM_RAID10_OFFSET) {
616                 f = copies;
617                 r = RAID10_OFFSET;
618                 if (!test_bit(__CTR_FLAG_RAID10_USE_NEAR_SETS, &rs->ctr_flags))
619                         r |= RAID10_USE_FAR_SETS;
620
621         } else if (algorithm == ALGORITHM_RAID10_FAR) {
622                 f = copies;
623                 if (!test_bit(__CTR_FLAG_RAID10_USE_NEAR_SETS, &rs->ctr_flags))
624                         r |= RAID10_USE_FAR_SETS;
625
626         } else
627                 return -EINVAL;
628
629         return r | (f << RAID10_FAR_COPIES_SHIFT) | n;
630 }
631 /* END: MD raid10 bit definitions and helpers */
632
633 /* Check for any of the raid10 algorithms */
634 static bool __got_raid10(struct raid_type *rtp, const int layout)
635 {
636         if (rtp->level == 10) {
637                 switch (rtp->algorithm) {
638                 case ALGORITHM_RAID10_DEFAULT:
639                 case ALGORITHM_RAID10_NEAR:
640                         return __is_raid10_near(layout);
641                 case ALGORITHM_RAID10_OFFSET:
642                         return __is_raid10_offset(layout);
643                 case ALGORITHM_RAID10_FAR:
644                         return __is_raid10_far(layout);
645                 default:
646                         break;
647                 }
648         }
649
650         return false;
651 }
652
653 /* Return raid_type for @name */
654 static struct raid_type *get_raid_type(const char *name)
655 {
656         struct raid_type *rtp = raid_types + ARRAY_SIZE(raid_types);
657
658         while (rtp-- > raid_types)
659                 if (!strcasecmp(rtp->name, name))
660                         return rtp;
661
662         return NULL;
663 }
664
665 /* Return raid_type for @name based derived from @level and @layout */
666 static struct raid_type *get_raid_type_by_ll(const int level, const int layout)
667 {
668         struct raid_type *rtp = raid_types + ARRAY_SIZE(raid_types);
669
670         while (rtp-- > raid_types) {
671                 /* RAID10 special checks based on @layout flags/properties */
672                 if (rtp->level == level &&
673                     (__got_raid10(rtp, layout) || rtp->algorithm == layout))
674                         return rtp;
675         }
676
677         return NULL;
678 }
679
680 /* Adjust rdev sectors */
681 static void rs_set_rdev_sectors(struct raid_set *rs)
682 {
683         struct mddev *mddev = &rs->md;
684         struct md_rdev *rdev;
685
686         /*
687          * raid10 sets rdev->sector to the device size, which
688          * is unintended in case of out-of-place reshaping
689          */
690         rdev_for_each(rdev, mddev)
691                 if (!test_bit(Journal, &rdev->flags))
692                         rdev->sectors = mddev->dev_sectors;
693 }
694
695 /*
696  * Change bdev capacity of @rs in case of a disk add/remove reshape
697  */
698 static void rs_set_capacity(struct raid_set *rs)
699 {
700         struct gendisk *gendisk = dm_disk(dm_table_get_md(rs->ti->table));
701
702         set_capacity(gendisk, rs->md.array_sectors);
703         revalidate_disk(gendisk);
704 }
705
706 /*
707  * Set the mddev properties in @rs to the current
708  * ones retrieved from the freshest superblock
709  */
710 static void rs_set_cur(struct raid_set *rs)
711 {
712         struct mddev *mddev = &rs->md;
713
714         mddev->new_level = mddev->level;
715         mddev->new_layout = mddev->layout;
716         mddev->new_chunk_sectors = mddev->chunk_sectors;
717 }
718
719 /*
720  * Set the mddev properties in @rs to the new
721  * ones requested by the ctr
722  */
723 static void rs_set_new(struct raid_set *rs)
724 {
725         struct mddev *mddev = &rs->md;
726
727         mddev->level = mddev->new_level;
728         mddev->layout = mddev->new_layout;
729         mddev->chunk_sectors = mddev->new_chunk_sectors;
730         mddev->raid_disks = rs->raid_disks;
731         mddev->delta_disks = 0;
732 }
733
734 static struct raid_set *raid_set_alloc(struct dm_target *ti, struct raid_type *raid_type,
735                                        unsigned int raid_devs)
736 {
737         unsigned int i;
738         struct raid_set *rs;
739
740         if (raid_devs <= raid_type->parity_devs) {
741                 ti->error = "Insufficient number of devices";
742                 return ERR_PTR(-EINVAL);
743         }
744
745         rs = kzalloc(struct_size(rs, dev, raid_devs), GFP_KERNEL);
746         if (!rs) {
747                 ti->error = "Cannot allocate raid context";
748                 return ERR_PTR(-ENOMEM);
749         }
750
751         mddev_init(&rs->md);
752
753         rs->raid_disks = raid_devs;
754         rs->delta_disks = 0;
755
756         rs->ti = ti;
757         rs->raid_type = raid_type;
758         rs->stripe_cache_entries = 256;
759         rs->md.raid_disks = raid_devs;
760         rs->md.level = raid_type->level;
761         rs->md.new_level = rs->md.level;
762         rs->md.layout = raid_type->algorithm;
763         rs->md.new_layout = rs->md.layout;
764         rs->md.delta_disks = 0;
765         rs->md.recovery_cp = MaxSector;
766
767         for (i = 0; i < raid_devs; i++)
768                 md_rdev_init(&rs->dev[i].rdev);
769
770         /*
771          * Remaining items to be initialized by further RAID params:
772          *  rs->md.persistent
773          *  rs->md.external
774          *  rs->md.chunk_sectors
775          *  rs->md.new_chunk_sectors
776          *  rs->md.dev_sectors
777          */
778
779         return rs;
780 }
781
782 /* Free all @rs allocations */
783 static void raid_set_free(struct raid_set *rs)
784 {
785         int i;
786
787         if (rs->journal_dev.dev) {
788                 md_rdev_clear(&rs->journal_dev.rdev);
789                 dm_put_device(rs->ti, rs->journal_dev.dev);
790         }
791
792         for (i = 0; i < rs->raid_disks; i++) {
793                 if (rs->dev[i].meta_dev)
794                         dm_put_device(rs->ti, rs->dev[i].meta_dev);
795                 md_rdev_clear(&rs->dev[i].rdev);
796                 if (rs->dev[i].data_dev)
797                         dm_put_device(rs->ti, rs->dev[i].data_dev);
798         }
799
800         kfree(rs);
801 }
802
803 /*
804  * For every device we have two words
805  *  <meta_dev>: meta device name or '-' if missing
806  *  <data_dev>: data device name or '-' if missing
807  *
808  * The following are permitted:
809  *    - -
810  *    - <data_dev>
811  *    <meta_dev> <data_dev>
812  *
813  * The following is not allowed:
814  *    <meta_dev> -
815  *
816  * This code parses those words.  If there is a failure,
817  * the caller must use raid_set_free() to unwind the operations.
818  */
819 static int parse_dev_params(struct raid_set *rs, struct dm_arg_set *as)
820 {
821         int i;
822         int rebuild = 0;
823         int metadata_available = 0;
824         int r = 0;
825         const char *arg;
826
827         /* Put off the number of raid devices argument to get to dev pairs */
828         arg = dm_shift_arg(as);
829         if (!arg)
830                 return -EINVAL;
831
832         for (i = 0; i < rs->raid_disks; i++) {
833                 rs->dev[i].rdev.raid_disk = i;
834
835                 rs->dev[i].meta_dev = NULL;
836                 rs->dev[i].data_dev = NULL;
837
838                 /*
839                  * There are no offsets initially.
840                  * Out of place reshape will set them accordingly.
841                  */
842                 rs->dev[i].rdev.data_offset = 0;
843                 rs->dev[i].rdev.new_data_offset = 0;
844                 rs->dev[i].rdev.mddev = &rs->md;
845
846                 arg = dm_shift_arg(as);
847                 if (!arg)
848                         return -EINVAL;
849
850                 if (strcmp(arg, "-")) {
851                         r = dm_get_device(rs->ti, arg, dm_table_get_mode(rs->ti->table),
852                                           &rs->dev[i].meta_dev);
853                         if (r) {
854                                 rs->ti->error = "RAID metadata device lookup failure";
855                                 return r;
856                         }
857
858                         rs->dev[i].rdev.sb_page = alloc_page(GFP_KERNEL);
859                         if (!rs->dev[i].rdev.sb_page) {
860                                 rs->ti->error = "Failed to allocate superblock page";
861                                 return -ENOMEM;
862                         }
863                 }
864
865                 arg = dm_shift_arg(as);
866                 if (!arg)
867                         return -EINVAL;
868
869                 if (!strcmp(arg, "-")) {
870                         if (!test_bit(In_sync, &rs->dev[i].rdev.flags) &&
871                             (!rs->dev[i].rdev.recovery_offset)) {
872                                 rs->ti->error = "Drive designated for rebuild not specified";
873                                 return -EINVAL;
874                         }
875
876                         if (rs->dev[i].meta_dev) {
877                                 rs->ti->error = "No data device supplied with metadata device";
878                                 return -EINVAL;
879                         }
880
881                         continue;
882                 }
883
884                 r = dm_get_device(rs->ti, arg, dm_table_get_mode(rs->ti->table),
885                                   &rs->dev[i].data_dev);
886                 if (r) {
887                         rs->ti->error = "RAID device lookup failure";
888                         return r;
889                 }
890
891                 if (rs->dev[i].meta_dev) {
892                         metadata_available = 1;
893                         rs->dev[i].rdev.meta_bdev = rs->dev[i].meta_dev->bdev;
894                 }
895                 rs->dev[i].rdev.bdev = rs->dev[i].data_dev->bdev;
896                 list_add_tail(&rs->dev[i].rdev.same_set, &rs->md.disks);
897                 if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
898                         rebuild++;
899         }
900
901         if (rs->journal_dev.dev)
902                 list_add_tail(&rs->journal_dev.rdev.same_set, &rs->md.disks);
903
904         if (metadata_available) {
905                 rs->md.external = 0;
906                 rs->md.persistent = 1;
907                 rs->md.major_version = 2;
908         } else if (rebuild && !rs->md.recovery_cp) {
909                 /*
910                  * Without metadata, we will not be able to tell if the array
911                  * is in-sync or not - we must assume it is not.  Therefore,
912                  * it is impossible to rebuild a drive.
913                  *
914                  * Even if there is metadata, the on-disk information may
915                  * indicate that the array is not in-sync and it will then
916                  * fail at that time.
917                  *
918                  * User could specify 'nosync' option if desperate.
919                  */
920                 rs->ti->error = "Unable to rebuild drive while array is not in-sync";
921                 return -EINVAL;
922         }
923
924         return 0;
925 }
926
927 /*
928  * validate_region_size
929  * @rs
930  * @region_size:  region size in sectors.  If 0, pick a size (4MiB default).
931  *
932  * Set rs->md.bitmap_info.chunksize (which really refers to 'region size').
933  * Ensure that (ti->len/region_size < 2^21) - required by MD bitmap.
934  *
935  * Returns: 0 on success, -EINVAL on failure.
936  */
937 static int validate_region_size(struct raid_set *rs, unsigned long region_size)
938 {
939         unsigned long min_region_size = rs->ti->len / (1 << 21);
940
941         if (rs_is_raid0(rs))
942                 return 0;
943
944         if (!region_size) {
945                 /*
946                  * Choose a reasonable default.  All figures in sectors.
947                  */
948                 if (min_region_size > (1 << 13)) {
949                         /* If not a power of 2, make it the next power of 2 */
950                         region_size = roundup_pow_of_two(min_region_size);
951                         DMINFO("Choosing default region size of %lu sectors",
952                                region_size);
953                 } else {
954                         DMINFO("Choosing default region size of 4MiB");
955                         region_size = 1 << 13; /* sectors */
956                 }
957         } else {
958                 /*
959                  * Validate user-supplied value.
960                  */
961                 if (region_size > rs->ti->len) {
962                         rs->ti->error = "Supplied region size is too large";
963                         return -EINVAL;
964                 }
965
966                 if (region_size < min_region_size) {
967                         DMERR("Supplied region_size (%lu sectors) below minimum (%lu)",
968                               region_size, min_region_size);
969                         rs->ti->error = "Supplied region size is too small";
970                         return -EINVAL;
971                 }
972
973                 if (!is_power_of_2(region_size)) {
974                         rs->ti->error = "Region size is not a power of 2";
975                         return -EINVAL;
976                 }
977
978                 if (region_size < rs->md.chunk_sectors) {
979                         rs->ti->error = "Region size is smaller than the chunk size";
980                         return -EINVAL;
981                 }
982         }
983
984         /*
985          * Convert sectors to bytes.
986          */
987         rs->md.bitmap_info.chunksize = to_bytes(region_size);
988
989         return 0;
990 }
991
992 /*
993  * validate_raid_redundancy
994  * @rs
995  *
996  * Determine if there are enough devices in the array that haven't
997  * failed (or are being rebuilt) to form a usable array.
998  *
999  * Returns: 0 on success, -EINVAL on failure.
1000  */
1001 static int validate_raid_redundancy(struct raid_set *rs)
1002 {
1003         unsigned int i, rebuild_cnt = 0;
1004         unsigned int rebuilds_per_group = 0, copies;
1005         unsigned int group_size, last_group_start;
1006
1007         for (i = 0; i < rs->md.raid_disks; i++)
1008                 if (!test_bit(In_sync, &rs->dev[i].rdev.flags) ||
1009                     !rs->dev[i].rdev.sb_page)
1010                         rebuild_cnt++;
1011
1012         switch (rs->md.level) {
1013         case 0:
1014                 break;
1015         case 1:
1016                 if (rebuild_cnt >= rs->md.raid_disks)
1017                         goto too_many;
1018                 break;
1019         case 4:
1020         case 5:
1021         case 6:
1022                 if (rebuild_cnt > rs->raid_type->parity_devs)
1023                         goto too_many;
1024                 break;
1025         case 10:
1026                 copies = raid10_md_layout_to_copies(rs->md.new_layout);
1027                 if (copies < 2) {
1028                         DMERR("Bogus raid10 data copies < 2!");
1029                         return -EINVAL;
1030                 }
1031
1032                 if (rebuild_cnt < copies)
1033                         break;
1034
1035                 /*
1036                  * It is possible to have a higher rebuild count for RAID10,
1037                  * as long as the failed devices occur in different mirror
1038                  * groups (i.e. different stripes).
1039                  *
1040                  * When checking "near" format, make sure no adjacent devices
1041                  * have failed beyond what can be handled.  In addition to the
1042                  * simple case where the number of devices is a multiple of the
1043                  * number of copies, we must also handle cases where the number
1044                  * of devices is not a multiple of the number of copies.
1045                  * E.g.    dev1 dev2 dev3 dev4 dev5
1046                  *          A    A    B    B    C
1047                  *          C    D    D    E    E
1048                  */
1049                 if (__is_raid10_near(rs->md.new_layout)) {
1050                         for (i = 0; i < rs->md.raid_disks; i++) {
1051                                 if (!(i % copies))
1052                                         rebuilds_per_group = 0;
1053                                 if ((!rs->dev[i].rdev.sb_page ||
1054                                     !test_bit(In_sync, &rs->dev[i].rdev.flags)) &&
1055                                     (++rebuilds_per_group >= copies))
1056                                         goto too_many;
1057                         }
1058                         break;
1059                 }
1060
1061                 /*
1062                  * When checking "far" and "offset" formats, we need to ensure
1063                  * that the device that holds its copy is not also dead or
1064                  * being rebuilt.  (Note that "far" and "offset" formats only
1065                  * support two copies right now.  These formats also only ever
1066                  * use the 'use_far_sets' variant.)
1067                  *
1068                  * This check is somewhat complicated by the need to account
1069                  * for arrays that are not a multiple of (far) copies.  This
1070                  * results in the need to treat the last (potentially larger)
1071                  * set differently.
1072                  */
1073                 group_size = (rs->md.raid_disks / copies);
1074                 last_group_start = (rs->md.raid_disks / group_size) - 1;
1075                 last_group_start *= group_size;
1076                 for (i = 0; i < rs->md.raid_disks; i++) {
1077                         if (!(i % copies) && !(i > last_group_start))
1078                                 rebuilds_per_group = 0;
1079                         if ((!rs->dev[i].rdev.sb_page ||
1080                              !test_bit(In_sync, &rs->dev[i].rdev.flags)) &&
1081                             (++rebuilds_per_group >= copies))
1082                                         goto too_many;
1083                 }
1084                 break;
1085         default:
1086                 if (rebuild_cnt)
1087                         return -EINVAL;
1088         }
1089
1090         return 0;
1091
1092 too_many:
1093         return -EINVAL;
1094 }
1095
1096 /*
1097  * Possible arguments are...
1098  *      <chunk_size> [optional_args]
1099  *
1100  * Argument definitions
1101  *    <chunk_size>                      The number of sectors per disk that
1102  *                                      will form the "stripe"
1103  *    [[no]sync]                        Force or prevent recovery of the
1104  *                                      entire array
1105  *    [rebuild <idx>]                   Rebuild the drive indicated by the index
1106  *    [daemon_sleep <ms>]               Time between bitmap daemon work to
1107  *                                      clear bits
1108  *    [min_recovery_rate <kB/sec/disk>] Throttle RAID initialization
1109  *    [max_recovery_rate <kB/sec/disk>] Throttle RAID initialization
1110  *    [write_mostly <idx>]              Indicate a write mostly drive via index
1111  *    [max_write_behind <sectors>]      See '-write-behind=' (man mdadm)
1112  *    [stripe_cache <sectors>]          Stripe cache size for higher RAIDs
1113  *    [region_size <sectors>]           Defines granularity of bitmap
1114  *    [journal_dev <dev>]               raid4/5/6 journaling deviice
1115  *                                      (i.e. write hole closing log)
1116  *
1117  * RAID10-only options:
1118  *    [raid10_copies <# copies>]        Number of copies.  (Default: 2)
1119  *    [raid10_format <near|far|offset>] Layout algorithm.  (Default: near)
1120  */
1121 static int parse_raid_params(struct raid_set *rs, struct dm_arg_set *as,
1122                              unsigned int num_raid_params)
1123 {
1124         int value, raid10_format = ALGORITHM_RAID10_DEFAULT;
1125         unsigned int raid10_copies = 2;
1126         unsigned int i, write_mostly = 0;
1127         unsigned int region_size = 0;
1128         sector_t max_io_len;
1129         const char *arg, *key;
1130         struct raid_dev *rd;
1131         struct raid_type *rt = rs->raid_type;
1132
1133         arg = dm_shift_arg(as);
1134         num_raid_params--; /* Account for chunk_size argument */
1135
1136         if (kstrtoint(arg, 10, &value) < 0) {
1137                 rs->ti->error = "Bad numerical argument given for chunk_size";
1138                 return -EINVAL;
1139         }
1140
1141         /*
1142          * First, parse the in-order required arguments
1143          * "chunk_size" is the only argument of this type.
1144          */
1145         if (rt_is_raid1(rt)) {
1146                 if (value)
1147                         DMERR("Ignoring chunk size parameter for RAID 1");
1148                 value = 0;
1149         } else if (!is_power_of_2(value)) {
1150                 rs->ti->error = "Chunk size must be a power of 2";
1151                 return -EINVAL;
1152         } else if (value < 8) {
1153                 rs->ti->error = "Chunk size value is too small";
1154                 return -EINVAL;
1155         }
1156
1157         rs->md.new_chunk_sectors = rs->md.chunk_sectors = value;
1158
1159         /*
1160          * We set each individual device as In_sync with a completed
1161          * 'recovery_offset'.  If there has been a device failure or
1162          * replacement then one of the following cases applies:
1163          *
1164          *   1) User specifies 'rebuild'.
1165          *      - Device is reset when param is read.
1166          *   2) A new device is supplied.
1167          *      - No matching superblock found, resets device.
1168          *   3) Device failure was transient and returns on reload.
1169          *      - Failure noticed, resets device for bitmap replay.
1170          *   4) Device hadn't completed recovery after previous failure.
1171          *      - Superblock is read and overrides recovery_offset.
1172          *
1173          * What is found in the superblocks of the devices is always
1174          * authoritative, unless 'rebuild' or '[no]sync' was specified.
1175          */
1176         for (i = 0; i < rs->raid_disks; i++) {
1177                 set_bit(In_sync, &rs->dev[i].rdev.flags);
1178                 rs->dev[i].rdev.recovery_offset = MaxSector;
1179         }
1180
1181         /*
1182          * Second, parse the unordered optional arguments
1183          */
1184         for (i = 0; i < num_raid_params; i++) {
1185                 key = dm_shift_arg(as);
1186                 if (!key) {
1187                         rs->ti->error = "Not enough raid parameters given";
1188                         return -EINVAL;
1189                 }
1190
1191                 if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_NOSYNC))) {
1192                         if (test_and_set_bit(__CTR_FLAG_NOSYNC, &rs->ctr_flags)) {
1193                                 rs->ti->error = "Only one 'nosync' argument allowed";
1194                                 return -EINVAL;
1195                         }
1196                         continue;
1197                 }
1198                 if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_SYNC))) {
1199                         if (test_and_set_bit(__CTR_FLAG_SYNC, &rs->ctr_flags)) {
1200                                 rs->ti->error = "Only one 'sync' argument allowed";
1201                                 return -EINVAL;
1202                         }
1203                         continue;
1204                 }
1205                 if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_RAID10_USE_NEAR_SETS))) {
1206                         if (test_and_set_bit(__CTR_FLAG_RAID10_USE_NEAR_SETS, &rs->ctr_flags)) {
1207                                 rs->ti->error = "Only one 'raid10_use_new_sets' argument allowed";
1208                                 return -EINVAL;
1209                         }
1210                         continue;
1211                 }
1212
1213                 arg = dm_shift_arg(as);
1214                 i++; /* Account for the argument pairs */
1215                 if (!arg) {
1216                         rs->ti->error = "Wrong number of raid parameters given";
1217                         return -EINVAL;
1218                 }
1219
1220                 /*
1221                  * Parameters that take a string value are checked here.
1222                  */
1223                 /* "raid10_format {near|offset|far} */
1224                 if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_RAID10_FORMAT))) {
1225                         if (test_and_set_bit(__CTR_FLAG_RAID10_FORMAT, &rs->ctr_flags)) {
1226                                 rs->ti->error = "Only one 'raid10_format' argument pair allowed";
1227                                 return -EINVAL;
1228                         }
1229                         if (!rt_is_raid10(rt)) {
1230                                 rs->ti->error = "'raid10_format' is an invalid parameter for this RAID type";
1231                                 return -EINVAL;
1232                         }
1233                         raid10_format = raid10_name_to_format(arg);
1234                         if (raid10_format < 0) {
1235                                 rs->ti->error = "Invalid 'raid10_format' value given";
1236                                 return raid10_format;
1237                         }
1238                         continue;
1239                 }
1240
1241                 /* "journal_dev <dev>" */
1242                 if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_JOURNAL_DEV))) {
1243                         int r;
1244                         struct md_rdev *jdev;
1245
1246                         if (test_and_set_bit(__CTR_FLAG_JOURNAL_DEV, &rs->ctr_flags)) {
1247                                 rs->ti->error = "Only one raid4/5/6 set journaling device allowed";
1248                                 return -EINVAL;
1249                         }
1250                         if (!rt_is_raid456(rt)) {
1251                                 rs->ti->error = "'journal_dev' is an invalid parameter for this RAID type";
1252                                 return -EINVAL;
1253                         }
1254                         r = dm_get_device(rs->ti, arg, dm_table_get_mode(rs->ti->table),
1255                                           &rs->journal_dev.dev);
1256                         if (r) {
1257                                 rs->ti->error = "raid4/5/6 journal device lookup failure";
1258                                 return r;
1259                         }
1260                         jdev = &rs->journal_dev.rdev;
1261                         md_rdev_init(jdev);
1262                         jdev->mddev = &rs->md;
1263                         jdev->bdev = rs->journal_dev.dev->bdev;
1264                         jdev->sectors = to_sector(i_size_read(jdev->bdev->bd_inode));
1265                         if (jdev->sectors < MIN_RAID456_JOURNAL_SPACE) {
1266                                 rs->ti->error = "No space for raid4/5/6 journal";
1267                                 return -ENOSPC;
1268                         }
1269                         rs->journal_dev.mode = R5C_JOURNAL_MODE_WRITE_THROUGH;
1270                         set_bit(Journal, &jdev->flags);
1271                         continue;
1272                 }
1273
1274                 /* "journal_mode <mode>" ("journal_dev" mandatory!) */
1275                 if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_JOURNAL_MODE))) {
1276                         int r;
1277
1278                         if (!test_bit(__CTR_FLAG_JOURNAL_DEV, &rs->ctr_flags)) {
1279                                 rs->ti->error = "raid4/5/6 'journal_mode' is invalid without 'journal_dev'";
1280                                 return -EINVAL;
1281                         }
1282                         if (test_and_set_bit(__CTR_FLAG_JOURNAL_MODE, &rs->ctr_flags)) {
1283                                 rs->ti->error = "Only one raid4/5/6 'journal_mode' argument allowed";
1284                                 return -EINVAL;
1285                         }
1286                         r = dm_raid_journal_mode_to_md(arg);
1287                         if (r < 0) {
1288                                 rs->ti->error = "Invalid 'journal_mode' argument";
1289                                 return r;
1290                         }
1291                         rs->journal_dev.mode = r;
1292                         continue;
1293                 }
1294
1295                 /*
1296                  * Parameters with number values from here on.
1297                  */
1298                 if (kstrtoint(arg, 10, &value) < 0) {
1299                         rs->ti->error = "Bad numerical argument given in raid params";
1300                         return -EINVAL;
1301                 }
1302
1303                 if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_REBUILD))) {
1304                         /*
1305                          * "rebuild" is being passed in by userspace to provide
1306                          * indexes of replaced devices and to set up additional
1307                          * devices on raid level takeover.
1308                          */
1309                         if (!__within_range(value, 0, rs->raid_disks - 1)) {
1310                                 rs->ti->error = "Invalid rebuild index given";
1311                                 return -EINVAL;
1312                         }
1313
1314                         if (test_and_set_bit(value, (void *) rs->rebuild_disks)) {
1315                                 rs->ti->error = "rebuild for this index already given";
1316                                 return -EINVAL;
1317                         }
1318
1319                         rd = rs->dev + value;
1320                         clear_bit(In_sync, &rd->rdev.flags);
1321                         clear_bit(Faulty, &rd->rdev.flags);
1322                         rd->rdev.recovery_offset = 0;
1323                         set_bit(__CTR_FLAG_REBUILD, &rs->ctr_flags);
1324                 } else if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_WRITE_MOSTLY))) {
1325                         if (!rt_is_raid1(rt)) {
1326                                 rs->ti->error = "write_mostly option is only valid for RAID1";
1327                                 return -EINVAL;
1328                         }
1329
1330                         if (!__within_range(value, 0, rs->md.raid_disks - 1)) {
1331                                 rs->ti->error = "Invalid write_mostly index given";
1332                                 return -EINVAL;
1333                         }
1334
1335                         write_mostly++;
1336                         set_bit(WriteMostly, &rs->dev[value].rdev.flags);
1337                         set_bit(__CTR_FLAG_WRITE_MOSTLY, &rs->ctr_flags);
1338                 } else if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_MAX_WRITE_BEHIND))) {
1339                         if (!rt_is_raid1(rt)) {
1340                                 rs->ti->error = "max_write_behind option is only valid for RAID1";
1341                                 return -EINVAL;
1342                         }
1343
1344                         if (test_and_set_bit(__CTR_FLAG_MAX_WRITE_BEHIND, &rs->ctr_flags)) {
1345                                 rs->ti->error = "Only one max_write_behind argument pair allowed";
1346                                 return -EINVAL;
1347                         }
1348
1349                         /*
1350                          * In device-mapper, we specify things in sectors, but
1351                          * MD records this value in kB
1352                          */
1353                         if (value < 0 || value / 2 > COUNTER_MAX) {
1354                                 rs->ti->error = "Max write-behind limit out of range";
1355                                 return -EINVAL;
1356                         }
1357
1358                         rs->md.bitmap_info.max_write_behind = value / 2;
1359                 } else if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_DAEMON_SLEEP))) {
1360                         if (test_and_set_bit(__CTR_FLAG_DAEMON_SLEEP, &rs->ctr_flags)) {
1361                                 rs->ti->error = "Only one daemon_sleep argument pair allowed";
1362                                 return -EINVAL;
1363                         }
1364                         if (value < 0) {
1365                                 rs->ti->error = "daemon sleep period out of range";
1366                                 return -EINVAL;
1367                         }
1368                         rs->md.bitmap_info.daemon_sleep = value;
1369                 } else if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_DATA_OFFSET))) {
1370                         /* Userspace passes new data_offset after having extended the the data image LV */
1371                         if (test_and_set_bit(__CTR_FLAG_DATA_OFFSET, &rs->ctr_flags)) {
1372                                 rs->ti->error = "Only one data_offset argument pair allowed";
1373                                 return -EINVAL;
1374                         }
1375                         /* Ensure sensible data offset */
1376                         if (value < 0 ||
1377                             (value && (value < MIN_FREE_RESHAPE_SPACE || value % to_sector(PAGE_SIZE)))) {
1378                                 rs->ti->error = "Bogus data_offset value";
1379                                 return -EINVAL;
1380                         }
1381                         rs->data_offset = value;
1382                 } else if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_DELTA_DISKS))) {
1383                         /* Define the +/-# of disks to add to/remove from the given raid set */
1384                         if (test_and_set_bit(__CTR_FLAG_DELTA_DISKS, &rs->ctr_flags)) {
1385                                 rs->ti->error = "Only one delta_disks argument pair allowed";
1386                                 return -EINVAL;
1387                         }
1388                         /* Ensure MAX_RAID_DEVICES and raid type minimal_devs! */
1389                         if (!__within_range(abs(value), 1, MAX_RAID_DEVICES - rt->minimal_devs)) {
1390                                 rs->ti->error = "Too many delta_disk requested";
1391                                 return -EINVAL;
1392                         }
1393
1394                         rs->delta_disks = value;
1395                 } else if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_STRIPE_CACHE))) {
1396                         if (test_and_set_bit(__CTR_FLAG_STRIPE_CACHE, &rs->ctr_flags)) {
1397                                 rs->ti->error = "Only one stripe_cache argument pair allowed";
1398                                 return -EINVAL;
1399                         }
1400
1401                         if (!rt_is_raid456(rt)) {
1402                                 rs->ti->error = "Inappropriate argument: stripe_cache";
1403                                 return -EINVAL;
1404                         }
1405
1406                         if (value < 0) {
1407                                 rs->ti->error = "Bogus stripe cache entries value";
1408                                 return -EINVAL;
1409                         }
1410                         rs->stripe_cache_entries = value;
1411                 } else if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_MIN_RECOVERY_RATE))) {
1412                         if (test_and_set_bit(__CTR_FLAG_MIN_RECOVERY_RATE, &rs->ctr_flags)) {
1413                                 rs->ti->error = "Only one min_recovery_rate argument pair allowed";
1414                                 return -EINVAL;
1415                         }
1416
1417                         if (value < 0) {
1418                                 rs->ti->error = "min_recovery_rate out of range";
1419                                 return -EINVAL;
1420                         }
1421                         rs->md.sync_speed_min = value;
1422                 } else if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_MAX_RECOVERY_RATE))) {
1423                         if (test_and_set_bit(__CTR_FLAG_MAX_RECOVERY_RATE, &rs->ctr_flags)) {
1424                                 rs->ti->error = "Only one max_recovery_rate argument pair allowed";
1425                                 return -EINVAL;
1426                         }
1427
1428                         if (value < 0) {
1429                                 rs->ti->error = "max_recovery_rate out of range";
1430                                 return -EINVAL;
1431                         }
1432                         rs->md.sync_speed_max = value;
1433                 } else if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_REGION_SIZE))) {
1434                         if (test_and_set_bit(__CTR_FLAG_REGION_SIZE, &rs->ctr_flags)) {
1435                                 rs->ti->error = "Only one region_size argument pair allowed";
1436                                 return -EINVAL;
1437                         }
1438
1439                         region_size = value;
1440                         rs->requested_bitmap_chunk_sectors = value;
1441                 } else if (!strcasecmp(key, dm_raid_arg_name_by_flag(CTR_FLAG_RAID10_COPIES))) {
1442                         if (test_and_set_bit(__CTR_FLAG_RAID10_COPIES, &rs->ctr_flags)) {
1443                                 rs->ti->error = "Only one raid10_copies argument pair allowed";
1444                                 return -EINVAL;
1445                         }
1446
1447                         if (!__within_range(value, 2, rs->md.raid_disks)) {
1448                                 rs->ti->error = "Bad value for 'raid10_copies'";
1449                                 return -EINVAL;
1450                         }
1451
1452                         raid10_copies = value;
1453                 } else {
1454                         DMERR("Unable to parse RAID parameter: %s", key);
1455                         rs->ti->error = "Unable to parse RAID parameter";
1456                         return -EINVAL;
1457                 }
1458         }
1459
1460         if (test_bit(__CTR_FLAG_SYNC, &rs->ctr_flags) &&
1461             test_bit(__CTR_FLAG_NOSYNC, &rs->ctr_flags)) {
1462                 rs->ti->error = "sync and nosync are mutually exclusive";
1463                 return -EINVAL;
1464         }
1465
1466         if (test_bit(__CTR_FLAG_REBUILD, &rs->ctr_flags) &&
1467             (test_bit(__CTR_FLAG_SYNC, &rs->ctr_flags) ||
1468              test_bit(__CTR_FLAG_NOSYNC, &rs->ctr_flags))) {
1469                 rs->ti->error = "sync/nosync and rebuild are mutually exclusive";
1470                 return -EINVAL;
1471         }
1472
1473         if (write_mostly >= rs->md.raid_disks) {
1474                 rs->ti->error = "Can't set all raid1 devices to write_mostly";
1475                 return -EINVAL;
1476         }
1477
1478         if (rs->md.sync_speed_max &&
1479             rs->md.sync_speed_min > rs->md.sync_speed_max) {
1480                 rs->ti->error = "Bogus recovery rates";
1481                 return -EINVAL;
1482         }
1483
1484         if (validate_region_size(rs, region_size))
1485                 return -EINVAL;
1486
1487         if (rs->md.chunk_sectors)
1488                 max_io_len = rs->md.chunk_sectors;
1489         else
1490                 max_io_len = region_size;
1491
1492         if (dm_set_target_max_io_len(rs->ti, max_io_len))
1493                 return -EINVAL;
1494
1495         if (rt_is_raid10(rt)) {
1496                 if (raid10_copies > rs->md.raid_disks) {
1497                         rs->ti->error = "Not enough devices to satisfy specification";
1498                         return -EINVAL;
1499                 }
1500
1501                 rs->md.new_layout = raid10_format_to_md_layout(rs, raid10_format, raid10_copies);
1502                 if (rs->md.new_layout < 0) {
1503                         rs->ti->error = "Error getting raid10 format";
1504                         return rs->md.new_layout;
1505                 }
1506
1507                 rt = get_raid_type_by_ll(10, rs->md.new_layout);
1508                 if (!rt) {
1509                         rs->ti->error = "Failed to recognize new raid10 layout";
1510                         return -EINVAL;
1511                 }
1512
1513                 if ((rt->algorithm == ALGORITHM_RAID10_DEFAULT ||
1514                      rt->algorithm == ALGORITHM_RAID10_NEAR) &&
1515                     test_bit(__CTR_FLAG_RAID10_USE_NEAR_SETS, &rs->ctr_flags)) {
1516                         rs->ti->error = "RAID10 format 'near' and 'raid10_use_near_sets' are incompatible";
1517                         return -EINVAL;
1518                 }
1519         }
1520
1521         rs->raid10_copies = raid10_copies;
1522
1523         /* Assume there are no metadata devices until the drives are parsed */
1524         rs->md.persistent = 0;
1525         rs->md.external = 1;
1526
1527         /* Check, if any invalid ctr arguments have been passed in for the raid level */
1528         return rs_check_for_valid_flags(rs);
1529 }
1530
1531 /* Set raid4/5/6 cache size */
1532 static int rs_set_raid456_stripe_cache(struct raid_set *rs)
1533 {
1534         int r;
1535         struct r5conf *conf;
1536         struct mddev *mddev = &rs->md;
1537         uint32_t min_stripes = max(mddev->chunk_sectors, mddev->new_chunk_sectors) / 2;
1538         uint32_t nr_stripes = rs->stripe_cache_entries;
1539
1540         if (!rt_is_raid456(rs->raid_type)) {
1541                 rs->ti->error = "Inappropriate raid level; cannot change stripe_cache size";
1542                 return -EINVAL;
1543         }
1544
1545         if (nr_stripes < min_stripes) {
1546                 DMINFO("Adjusting requested %u stripe cache entries to %u to suit stripe size",
1547                        nr_stripes, min_stripes);
1548                 nr_stripes = min_stripes;
1549         }
1550
1551         conf = mddev->private;
1552         if (!conf) {
1553                 rs->ti->error = "Cannot change stripe_cache size on inactive RAID set";
1554                 return -EINVAL;
1555         }
1556
1557         /* Try setting number of stripes in raid456 stripe cache */
1558         if (conf->min_nr_stripes != nr_stripes) {
1559                 r = raid5_set_cache_size(mddev, nr_stripes);
1560                 if (r) {
1561                         rs->ti->error = "Failed to set raid4/5/6 stripe cache size";
1562                         return r;
1563                 }
1564
1565                 DMINFO("%u stripe cache entries", nr_stripes);
1566         }
1567
1568         return 0;
1569 }
1570
1571 /* Return # of data stripes as kept in mddev as of @rs (i.e. as of superblock) */
1572 static unsigned int mddev_data_stripes(struct raid_set *rs)
1573 {
1574         return rs->md.raid_disks - rs->raid_type->parity_devs;
1575 }
1576
1577 /* Return # of data stripes of @rs (i.e. as of ctr) */
1578 static unsigned int rs_data_stripes(struct raid_set *rs)
1579 {
1580         return rs->raid_disks - rs->raid_type->parity_devs;
1581 }
1582
1583 /*
1584  * Retrieve rdev->sectors from any valid raid device of @rs
1585  * to allow userpace to pass in arbitray "- -" device tupples.
1586  */
1587 static sector_t __rdev_sectors(struct raid_set *rs)
1588 {
1589         int i;
1590
1591         for (i = 0; i < rs->md.raid_disks; i++) {
1592                 struct md_rdev *rdev = &rs->dev[i].rdev;
1593
1594                 if (!test_bit(Journal, &rdev->flags) &&
1595                     rdev->bdev && rdev->sectors)
1596                         return rdev->sectors;
1597         }
1598
1599         return 0;
1600 }
1601
1602 /* Check that calculated dev_sectors fits all component devices. */
1603 static int _check_data_dev_sectors(struct raid_set *rs)
1604 {
1605         sector_t ds = ~0;
1606         struct md_rdev *rdev;
1607
1608         rdev_for_each(rdev, &rs->md)
1609                 if (!test_bit(Journal, &rdev->flags) && rdev->bdev) {
1610                         ds = min(ds, to_sector(i_size_read(rdev->bdev->bd_inode)));
1611                         if (ds < rs->md.dev_sectors) {
1612                                 rs->ti->error = "Component device(s) too small";
1613                                 return -EINVAL;
1614                         }
1615                 }
1616
1617         return 0;
1618 }
1619
1620 /* Calculate the sectors per device and per array used for @rs */
1621 static int rs_set_dev_and_array_sectors(struct raid_set *rs, sector_t sectors, bool use_mddev)
1622 {
1623         int delta_disks;
1624         unsigned int data_stripes;
1625         sector_t array_sectors = sectors, dev_sectors = sectors;
1626         struct mddev *mddev = &rs->md;
1627
1628         if (use_mddev) {
1629                 delta_disks = mddev->delta_disks;
1630                 data_stripes = mddev_data_stripes(rs);
1631         } else {
1632                 delta_disks = rs->delta_disks;
1633                 data_stripes = rs_data_stripes(rs);
1634         }
1635
1636         /* Special raid1 case w/o delta_disks support (yet) */
1637         if (rt_is_raid1(rs->raid_type))
1638                 ;
1639         else if (rt_is_raid10(rs->raid_type)) {
1640                 if (rs->raid10_copies < 2 ||
1641                     delta_disks < 0) {
1642                         rs->ti->error = "Bogus raid10 data copies or delta disks";
1643                         return -EINVAL;
1644                 }
1645
1646                 dev_sectors *= rs->raid10_copies;
1647                 if (sector_div(dev_sectors, data_stripes))
1648                         goto bad;
1649
1650                 array_sectors = (data_stripes + delta_disks) * dev_sectors;
1651                 if (sector_div(array_sectors, rs->raid10_copies))
1652                         goto bad;
1653
1654         } else if (sector_div(dev_sectors, data_stripes))
1655                 goto bad;
1656
1657         else
1658                 /* Striped layouts */
1659                 array_sectors = (data_stripes + delta_disks) * dev_sectors;
1660
1661         mddev->array_sectors = array_sectors;
1662         mddev->dev_sectors = dev_sectors;
1663         rs_set_rdev_sectors(rs);
1664
1665         return _check_data_dev_sectors(rs);
1666 bad:
1667         rs->ti->error = "Target length not divisible by number of data devices";
1668         return -EINVAL;
1669 }
1670
1671 /* Setup recovery on @rs */
1672 static void rs_setup_recovery(struct raid_set *rs, sector_t dev_sectors)
1673 {
1674         /* raid0 does not recover */
1675         if (rs_is_raid0(rs))
1676                 rs->md.recovery_cp = MaxSector;
1677         /*
1678          * A raid6 set has to be recovered either
1679          * completely or for the grown part to
1680          * ensure proper parity and Q-Syndrome
1681          */
1682         else if (rs_is_raid6(rs))
1683                 rs->md.recovery_cp = dev_sectors;
1684         /*
1685          * Other raid set types may skip recovery
1686          * depending on the 'nosync' flag.
1687          */
1688         else
1689                 rs->md.recovery_cp = test_bit(__CTR_FLAG_NOSYNC, &rs->ctr_flags)
1690                                      ? MaxSector : dev_sectors;
1691 }
1692
1693 static void do_table_event(struct work_struct *ws)
1694 {
1695         struct raid_set *rs = container_of(ws, struct raid_set, md.event_work);
1696
1697         smp_rmb(); /* Make sure we access most actual mddev properties */
1698         if (!rs_is_reshaping(rs)) {
1699                 if (rs_is_raid10(rs))
1700                         rs_set_rdev_sectors(rs);
1701                 rs_set_capacity(rs);
1702         }
1703         dm_table_event(rs->ti->table);
1704 }
1705
1706 static int raid_is_congested(struct dm_target_callbacks *cb, int bits)
1707 {
1708         struct raid_set *rs = container_of(cb, struct raid_set, callbacks);
1709
1710         return mddev_congested(&rs->md, bits);
1711 }
1712
1713 /*
1714  * Make sure a valid takover (level switch) is being requested on @rs
1715  *
1716  * Conversions of raid sets from one MD personality to another
1717  * have to conform to restrictions which are enforced here.
1718  */
1719 static int rs_check_takeover(struct raid_set *rs)
1720 {
1721         struct mddev *mddev = &rs->md;
1722         unsigned int near_copies;
1723
1724         if (rs->md.degraded) {
1725                 rs->ti->error = "Can't takeover degraded raid set";
1726                 return -EPERM;
1727         }
1728
1729         if (rs_is_reshaping(rs)) {
1730                 rs->ti->error = "Can't takeover reshaping raid set";
1731                 return -EPERM;
1732         }
1733
1734         switch (mddev->level) {
1735         case 0:
1736                 /* raid0 -> raid1/5 with one disk */
1737                 if ((mddev->new_level == 1 || mddev->new_level == 5) &&
1738                     mddev->raid_disks == 1)
1739                         return 0;
1740
1741                 /* raid0 -> raid10 */
1742                 if (mddev->new_level == 10 &&
1743                     !(rs->raid_disks % mddev->raid_disks))
1744                         return 0;
1745
1746                 /* raid0 with multiple disks -> raid4/5/6 */
1747                 if (__within_range(mddev->new_level, 4, 6) &&
1748                     mddev->new_layout == ALGORITHM_PARITY_N &&
1749                     mddev->raid_disks > 1)
1750                         return 0;
1751
1752                 break;
1753
1754         case 10:
1755                 /* Can't takeover raid10_offset! */
1756                 if (__is_raid10_offset(mddev->layout))
1757                         break;
1758
1759                 near_copies = __raid10_near_copies(mddev->layout);
1760
1761                 /* raid10* -> raid0 */
1762                 if (mddev->new_level == 0) {
1763                         /* Can takeover raid10_near with raid disks divisable by data copies! */
1764                         if (near_copies > 1 &&
1765                             !(mddev->raid_disks % near_copies)) {
1766                                 mddev->raid_disks /= near_copies;
1767                                 mddev->delta_disks = mddev->raid_disks;
1768                                 return 0;
1769                         }
1770
1771                         /* Can takeover raid10_far */
1772                         if (near_copies == 1 &&
1773                             __raid10_far_copies(mddev->layout) > 1)
1774                                 return 0;
1775
1776                         break;
1777                 }
1778
1779                 /* raid10_{near,far} -> raid1 */
1780                 if (mddev->new_level == 1 &&
1781                     max(near_copies, __raid10_far_copies(mddev->layout)) == mddev->raid_disks)
1782                         return 0;
1783
1784                 /* raid10_{near,far} with 2 disks -> raid4/5 */
1785                 if (__within_range(mddev->new_level, 4, 5) &&
1786                     mddev->raid_disks == 2)
1787                         return 0;
1788                 break;
1789
1790         case 1:
1791                 /* raid1 with 2 disks -> raid4/5 */
1792                 if (__within_range(mddev->new_level, 4, 5) &&
1793                     mddev->raid_disks == 2) {
1794                         mddev->degraded = 1;
1795                         return 0;
1796                 }
1797
1798                 /* raid1 -> raid0 */
1799                 if (mddev->new_level == 0 &&
1800                     mddev->raid_disks == 1)
1801                         return 0;
1802
1803                 /* raid1 -> raid10 */
1804                 if (mddev->new_level == 10)
1805                         return 0;
1806                 break;
1807
1808         case 4:
1809                 /* raid4 -> raid0 */
1810                 if (mddev->new_level == 0)
1811                         return 0;
1812
1813                 /* raid4 -> raid1/5 with 2 disks */
1814                 if ((mddev->new_level == 1 || mddev->new_level == 5) &&
1815                     mddev->raid_disks == 2)
1816                         return 0;
1817
1818                 /* raid4 -> raid5/6 with parity N */
1819                 if (__within_range(mddev->new_level, 5, 6) &&
1820                     mddev->layout == ALGORITHM_PARITY_N)
1821                         return 0;
1822                 break;
1823
1824         case 5:
1825                 /* raid5 with parity N -> raid0 */
1826                 if (mddev->new_level == 0 &&
1827                     mddev->layout == ALGORITHM_PARITY_N)
1828                         return 0;
1829
1830                 /* raid5 with parity N -> raid4 */
1831                 if (mddev->new_level == 4 &&
1832                     mddev->layout == ALGORITHM_PARITY_N)
1833                         return 0;
1834
1835                 /* raid5 with 2 disks -> raid1/4/10 */
1836                 if ((mddev->new_level == 1 || mddev->new_level == 4 || mddev->new_level == 10) &&
1837                     mddev->raid_disks == 2)
1838                         return 0;
1839
1840                 /* raid5_* ->  raid6_*_6 with Q-Syndrome N (e.g. raid5_ra -> raid6_ra_6 */
1841                 if (mddev->new_level == 6 &&
1842                     ((mddev->layout == ALGORITHM_PARITY_N && mddev->new_layout == ALGORITHM_PARITY_N) ||
1843                       __within_range(mddev->new_layout, ALGORITHM_LEFT_ASYMMETRIC_6, ALGORITHM_RIGHT_SYMMETRIC_6)))
1844                         return 0;
1845                 break;
1846
1847         case 6:
1848                 /* raid6 with parity N -> raid0 */
1849                 if (mddev->new_level == 0 &&
1850                     mddev->layout == ALGORITHM_PARITY_N)
1851                         return 0;
1852
1853                 /* raid6 with parity N -> raid4 */
1854                 if (mddev->new_level == 4 &&
1855                     mddev->layout == ALGORITHM_PARITY_N)
1856                         return 0;
1857
1858                 /* raid6_*_n with Q-Syndrome N -> raid5_* */
1859                 if (mddev->new_level == 5 &&
1860                     ((mddev->layout == ALGORITHM_PARITY_N && mddev->new_layout == ALGORITHM_PARITY_N) ||
1861                      __within_range(mddev->new_layout, ALGORITHM_LEFT_ASYMMETRIC, ALGORITHM_RIGHT_SYMMETRIC)))
1862                         return 0;
1863
1864         default:
1865                 break;
1866         }
1867
1868         rs->ti->error = "takeover not possible";
1869         return -EINVAL;
1870 }
1871
1872 /* True if @rs requested to be taken over */
1873 static bool rs_takeover_requested(struct raid_set *rs)
1874 {
1875         return rs->md.new_level != rs->md.level;
1876 }
1877
1878 /* True if @rs is requested to reshape by ctr */
1879 static bool rs_reshape_requested(struct raid_set *rs)
1880 {
1881         bool change;
1882         struct mddev *mddev = &rs->md;
1883
1884         if (rs_takeover_requested(rs))
1885                 return false;
1886
1887         if (rs_is_raid0(rs))
1888                 return false;
1889
1890         change = mddev->new_layout != mddev->layout ||
1891                  mddev->new_chunk_sectors != mddev->chunk_sectors ||
1892                  rs->delta_disks;
1893
1894         /* Historical case to support raid1 reshape without delta disks */
1895         if (rs_is_raid1(rs)) {
1896                 if (rs->delta_disks)
1897                         return !!rs->delta_disks;
1898
1899                 return !change &&
1900                        mddev->raid_disks != rs->raid_disks;
1901         }
1902
1903         if (rs_is_raid10(rs))
1904                 return change &&
1905                        !__is_raid10_far(mddev->new_layout) &&
1906                        rs->delta_disks >= 0;
1907
1908         return change;
1909 }
1910
1911 /*  Features */
1912 #define FEATURE_FLAG_SUPPORTS_V190      0x1 /* Supports extended superblock */
1913
1914 /* State flags for sb->flags */
1915 #define SB_FLAG_RESHAPE_ACTIVE          0x1
1916 #define SB_FLAG_RESHAPE_BACKWARDS       0x2
1917
1918 /*
1919  * This structure is never routinely used by userspace, unlike md superblocks.
1920  * Devices with this superblock should only ever be accessed via device-mapper.
1921  */
1922 #define DM_RAID_MAGIC 0x64526D44
1923 struct dm_raid_superblock {
1924         __le32 magic;           /* "DmRd" */
1925         __le32 compat_features; /* Used to indicate compatible features (like 1.9.0 ondisk metadata extension) */
1926
1927         __le32 num_devices;     /* Number of devices in this raid set. (Max 64) */
1928         __le32 array_position;  /* The position of this drive in the raid set */
1929
1930         __le64 events;          /* Incremented by md when superblock updated */
1931         __le64 failed_devices;  /* Pre 1.9.0 part of bit field of devices to */
1932                                 /* indicate failures (see extension below) */
1933
1934         /*
1935          * This offset tracks the progress of the repair or replacement of
1936          * an individual drive.
1937          */
1938         __le64 disk_recovery_offset;
1939
1940         /*
1941          * This offset tracks the progress of the initial raid set
1942          * synchronisation/parity calculation.
1943          */
1944         __le64 array_resync_offset;
1945
1946         /*
1947          * raid characteristics
1948          */
1949         __le32 level;
1950         __le32 layout;
1951         __le32 stripe_sectors;
1952
1953         /********************************************************************
1954          * BELOW FOLLOW V1.9.0 EXTENSIONS TO THE PRISTINE SUPERBLOCK FORMAT!!!
1955          *
1956          * FEATURE_FLAG_SUPPORTS_V190 in the compat_features member indicates that those exist
1957          */
1958
1959         __le32 flags; /* Flags defining array states for reshaping */
1960
1961         /*
1962          * This offset tracks the progress of a raid
1963          * set reshape in order to be able to restart it
1964          */
1965         __le64 reshape_position;
1966
1967         /*
1968          * These define the properties of the array in case of an interrupted reshape
1969          */
1970         __le32 new_level;
1971         __le32 new_layout;
1972         __le32 new_stripe_sectors;
1973         __le32 delta_disks;
1974
1975         __le64 array_sectors; /* Array size in sectors */
1976
1977         /*
1978          * Sector offsets to data on devices (reshaping).
1979          * Needed to support out of place reshaping, thus
1980          * not writing over any stripes whilst converting
1981          * them from old to new layout
1982          */
1983         __le64 data_offset;
1984         __le64 new_data_offset;
1985
1986         __le64 sectors; /* Used device size in sectors */
1987
1988         /*
1989          * Additonal Bit field of devices indicating failures to support
1990          * up to 256 devices with the 1.9.0 on-disk metadata format
1991          */
1992         __le64 extended_failed_devices[DISKS_ARRAY_ELEMS - 1];
1993
1994         __le32 incompat_features;       /* Used to indicate any incompatible features */
1995
1996         /* Always set rest up to logical block size to 0 when writing (see get_metadata_device() below). */
1997 } __packed;
1998
1999 /*
2000  * Check for reshape constraints on raid set @rs:
2001  *
2002  * - reshape function non-existent
2003  * - degraded set
2004  * - ongoing recovery
2005  * - ongoing reshape
2006  *
2007  * Returns 0 if none or -EPERM if given constraint
2008  * and error message reference in @errmsg
2009  */
2010 static int rs_check_reshape(struct raid_set *rs)
2011 {
2012         struct mddev *mddev = &rs->md;
2013
2014         if (!mddev->pers || !mddev->pers->check_reshape)
2015                 rs->ti->error = "Reshape not supported";
2016         else if (mddev->degraded)
2017                 rs->ti->error = "Can't reshape degraded raid set";
2018         else if (rs_is_recovering(rs))
2019                 rs->ti->error = "Convert request on recovering raid set prohibited";
2020         else if (rs_is_reshaping(rs))
2021                 rs->ti->error = "raid set already reshaping!";
2022         else if (!(rs_is_raid1(rs) || rs_is_raid10(rs) || rs_is_raid456(rs)))
2023                 rs->ti->error = "Reshaping only supported for raid1/4/5/6/10";
2024         else
2025                 return 0;
2026
2027         return -EPERM;
2028 }
2029
2030 static int read_disk_sb(struct md_rdev *rdev, int size, bool force_reload)
2031 {
2032         BUG_ON(!rdev->sb_page);
2033
2034         if (rdev->sb_loaded && !force_reload)
2035                 return 0;
2036
2037         rdev->sb_loaded = 0;
2038
2039         if (!sync_page_io(rdev, 0, size, rdev->sb_page, REQ_OP_READ, 0, true)) {
2040                 DMERR("Failed to read superblock of device at position %d",
2041                       rdev->raid_disk);
2042                 md_error(rdev->mddev, rdev);
2043                 set_bit(Faulty, &rdev->flags);
2044                 return -EIO;
2045         }
2046
2047         rdev->sb_loaded = 1;
2048
2049         return 0;
2050 }
2051
2052 static void sb_retrieve_failed_devices(struct dm_raid_superblock *sb, uint64_t *failed_devices)
2053 {
2054         failed_devices[0] = le64_to_cpu(sb->failed_devices);
2055         memset(failed_devices + 1, 0, sizeof(sb->extended_failed_devices));
2056
2057         if (le32_to_cpu(sb->compat_features) & FEATURE_FLAG_SUPPORTS_V190) {
2058                 int i = ARRAY_SIZE(sb->extended_failed_devices);
2059
2060                 while (i--)
2061                         failed_devices[i+1] = le64_to_cpu(sb->extended_failed_devices[i]);
2062         }
2063 }
2064
2065 static void sb_update_failed_devices(struct dm_raid_superblock *sb, uint64_t *failed_devices)
2066 {
2067         int i = ARRAY_SIZE(sb->extended_failed_devices);
2068
2069         sb->failed_devices = cpu_to_le64(failed_devices[0]);
2070         while (i--)
2071                 sb->extended_failed_devices[i] = cpu_to_le64(failed_devices[i+1]);
2072 }
2073
2074 /*
2075  * Synchronize the superblock members with the raid set properties
2076  *
2077  * All superblock data is little endian.
2078  */
2079 static void super_sync(struct mddev *mddev, struct md_rdev *rdev)
2080 {
2081         bool update_failed_devices = false;
2082         unsigned int i;
2083         uint64_t failed_devices[DISKS_ARRAY_ELEMS];
2084         struct dm_raid_superblock *sb;
2085         struct raid_set *rs = container_of(mddev, struct raid_set, md);
2086
2087         /* No metadata device, no superblock */
2088         if (!rdev->meta_bdev)
2089                 return;
2090
2091         BUG_ON(!rdev->sb_page);
2092
2093         sb = page_address(rdev->sb_page);
2094
2095         sb_retrieve_failed_devices(sb, failed_devices);
2096
2097         for (i = 0; i < rs->raid_disks; i++)
2098                 if (!rs->dev[i].data_dev || test_bit(Faulty, &rs->dev[i].rdev.flags)) {
2099                         update_failed_devices = true;
2100                         set_bit(i, (void *) failed_devices);
2101                 }
2102
2103         if (update_failed_devices)
2104                 sb_update_failed_devices(sb, failed_devices);
2105
2106         sb->magic = cpu_to_le32(DM_RAID_MAGIC);
2107         sb->compat_features = cpu_to_le32(FEATURE_FLAG_SUPPORTS_V190);
2108
2109         sb->num_devices = cpu_to_le32(mddev->raid_disks);
2110         sb->array_position = cpu_to_le32(rdev->raid_disk);
2111
2112         sb->events = cpu_to_le64(mddev->events);
2113
2114         sb->disk_recovery_offset = cpu_to_le64(rdev->recovery_offset);
2115         sb->array_resync_offset = cpu_to_le64(mddev->recovery_cp);
2116
2117         sb->level = cpu_to_le32(mddev->level);
2118         sb->layout = cpu_to_le32(mddev->layout);
2119         sb->stripe_sectors = cpu_to_le32(mddev->chunk_sectors);
2120
2121         /********************************************************************
2122          * BELOW FOLLOW V1.9.0 EXTENSIONS TO THE PRISTINE SUPERBLOCK FORMAT!!!
2123          *
2124          * FEATURE_FLAG_SUPPORTS_V190 in the compat_features member indicates that those exist
2125          */
2126         sb->new_level = cpu_to_le32(mddev->new_level);
2127         sb->new_layout = cpu_to_le32(mddev->new_layout);
2128         sb->new_stripe_sectors = cpu_to_le32(mddev->new_chunk_sectors);
2129
2130         sb->delta_disks = cpu_to_le32(mddev->delta_disks);
2131
2132         smp_rmb(); /* Make sure we access most recent reshape position */
2133         sb->reshape_position = cpu_to_le64(mddev->reshape_position);
2134         if (le64_to_cpu(sb->reshape_position) != MaxSector) {
2135                 /* Flag ongoing reshape */
2136                 sb->flags |= cpu_to_le32(SB_FLAG_RESHAPE_ACTIVE);
2137
2138                 if (mddev->delta_disks < 0 || mddev->reshape_backwards)
2139                         sb->flags |= cpu_to_le32(SB_FLAG_RESHAPE_BACKWARDS);
2140         } else {
2141                 /* Clear reshape flags */
2142                 sb->flags &= ~(cpu_to_le32(SB_FLAG_RESHAPE_ACTIVE|SB_FLAG_RESHAPE_BACKWARDS));
2143         }
2144
2145         sb->array_sectors = cpu_to_le64(mddev->array_sectors);
2146         sb->data_offset = cpu_to_le64(rdev->data_offset);
2147         sb->new_data_offset = cpu_to_le64(rdev->new_data_offset);
2148         sb->sectors = cpu_to_le64(rdev->sectors);
2149         sb->incompat_features = cpu_to_le32(0);
2150
2151         /* Zero out the rest of the payload after the size of the superblock */
2152         memset(sb + 1, 0, rdev->sb_size - sizeof(*sb));
2153 }
2154
2155 /*
2156  * super_load
2157  *
2158  * This function creates a superblock if one is not found on the device
2159  * and will decide which superblock to use if there's a choice.
2160  *
2161  * Return: 1 if use rdev, 0 if use refdev, -Exxx otherwise
2162  */
2163 static int super_load(struct md_rdev *rdev, struct md_rdev *refdev)
2164 {
2165         int r;
2166         struct dm_raid_superblock *sb;
2167         struct dm_raid_superblock *refsb;
2168         uint64_t events_sb, events_refsb;
2169
2170         r = read_disk_sb(rdev, rdev->sb_size, false);
2171         if (r)
2172                 return r;
2173
2174         sb = page_address(rdev->sb_page);
2175
2176         /*
2177          * Two cases that we want to write new superblocks and rebuild:
2178          * 1) New device (no matching magic number)
2179          * 2) Device specified for rebuild (!In_sync w/ offset == 0)
2180          */
2181         if ((sb->magic != cpu_to_le32(DM_RAID_MAGIC)) ||
2182             (!test_bit(In_sync, &rdev->flags) && !rdev->recovery_offset)) {
2183                 super_sync(rdev->mddev, rdev);
2184
2185                 set_bit(FirstUse, &rdev->flags);
2186                 sb->compat_features = cpu_to_le32(FEATURE_FLAG_SUPPORTS_V190);
2187
2188                 /* Force writing of superblocks to disk */
2189                 set_bit(MD_SB_CHANGE_DEVS, &rdev->mddev->sb_flags);
2190
2191                 /* Any superblock is better than none, choose that if given */
2192                 return refdev ? 0 : 1;
2193         }
2194
2195         if (!refdev)
2196                 return 1;
2197
2198         events_sb = le64_to_cpu(sb->events);
2199
2200         refsb = page_address(refdev->sb_page);
2201         events_refsb = le64_to_cpu(refsb->events);
2202
2203         return (events_sb > events_refsb) ? 1 : 0;
2204 }
2205
2206 static int super_init_validation(struct raid_set *rs, struct md_rdev *rdev)
2207 {
2208         int role;
2209         unsigned int d;
2210         struct mddev *mddev = &rs->md;
2211         uint64_t events_sb;
2212         uint64_t failed_devices[DISKS_ARRAY_ELEMS];
2213         struct dm_raid_superblock *sb;
2214         uint32_t new_devs = 0, rebuild_and_new = 0, rebuilds = 0;
2215         struct md_rdev *r;
2216         struct dm_raid_superblock *sb2;
2217
2218         sb = page_address(rdev->sb_page);
2219         events_sb = le64_to_cpu(sb->events);
2220
2221         /*
2222          * Initialise to 1 if this is a new superblock.
2223          */
2224         mddev->events = events_sb ? : 1;
2225
2226         mddev->reshape_position = MaxSector;
2227
2228         mddev->raid_disks = le32_to_cpu(sb->num_devices);
2229         mddev->level = le32_to_cpu(sb->level);
2230         mddev->layout = le32_to_cpu(sb->layout);
2231         mddev->chunk_sectors = le32_to_cpu(sb->stripe_sectors);
2232
2233         /*
2234          * Reshaping is supported, e.g. reshape_position is valid
2235          * in superblock and superblock content is authoritative.
2236          */
2237         if (le32_to_cpu(sb->compat_features) & FEATURE_FLAG_SUPPORTS_V190) {
2238                 /* Superblock is authoritative wrt given raid set layout! */
2239                 mddev->new_level = le32_to_cpu(sb->new_level);
2240                 mddev->new_layout = le32_to_cpu(sb->new_layout);
2241                 mddev->new_chunk_sectors = le32_to_cpu(sb->new_stripe_sectors);
2242                 mddev->delta_disks = le32_to_cpu(sb->delta_disks);
2243                 mddev->array_sectors = le64_to_cpu(sb->array_sectors);
2244
2245                 /* raid was reshaping and got interrupted */
2246                 if (le32_to_cpu(sb->flags) & SB_FLAG_RESHAPE_ACTIVE) {
2247                         if (test_bit(__CTR_FLAG_DELTA_DISKS, &rs->ctr_flags)) {
2248                                 DMERR("Reshape requested but raid set is still reshaping");
2249                                 return -EINVAL;
2250                         }
2251
2252                         if (mddev->delta_disks < 0 ||
2253                             (!mddev->delta_disks && (le32_to_cpu(sb->flags) & SB_FLAG_RESHAPE_BACKWARDS)))
2254                                 mddev->reshape_backwards = 1;
2255                         else
2256                                 mddev->reshape_backwards = 0;
2257
2258                         mddev->reshape_position = le64_to_cpu(sb->reshape_position);
2259                         rs->raid_type = get_raid_type_by_ll(mddev->level, mddev->layout);
2260                 }
2261
2262         } else {
2263                 /*
2264                  * No takeover/reshaping, because we don't have the extended v1.9.0 metadata
2265                  */
2266                 struct raid_type *rt_cur = get_raid_type_by_ll(mddev->level, mddev->layout);
2267                 struct raid_type *rt_new = get_raid_type_by_ll(mddev->new_level, mddev->new_layout);
2268
2269                 if (rs_takeover_requested(rs)) {
2270                         if (rt_cur && rt_new)
2271                                 DMERR("Takeover raid sets from %s to %s not yet supported by metadata. (raid level change)",
2272                                       rt_cur->name, rt_new->name);
2273                         else
2274                                 DMERR("Takeover raid sets not yet supported by metadata. (raid level change)");
2275                         return -EINVAL;
2276                 } else if (rs_reshape_requested(rs)) {
2277                         DMERR("Reshaping raid sets not yet supported by metadata. (raid layout change keeping level)");
2278                         if (mddev->layout != mddev->new_layout) {
2279                                 if (rt_cur && rt_new)
2280                                         DMERR("  current layout %s vs new layout %s",
2281                                               rt_cur->name, rt_new->name);
2282                                 else
2283                                         DMERR("  current layout 0x%X vs new layout 0x%X",
2284                                               le32_to_cpu(sb->layout), mddev->new_layout);
2285                         }
2286                         if (mddev->chunk_sectors != mddev->new_chunk_sectors)
2287                                 DMERR("  current stripe sectors %u vs new stripe sectors %u",
2288                                       mddev->chunk_sectors, mddev->new_chunk_sectors);
2289                         if (rs->delta_disks)
2290                                 DMERR("  current %u disks vs new %u disks",
2291                                       mddev->raid_disks, mddev->raid_disks + rs->delta_disks);
2292                         if (rs_is_raid10(rs)) {
2293                                 DMERR("  Old layout: %s w/ %u copies",
2294                                       raid10_md_layout_to_format(mddev->layout),
2295                                       raid10_md_layout_to_copies(mddev->layout));
2296                                 DMERR("  New layout: %s w/ %u copies",
2297                                       raid10_md_layout_to_format(mddev->new_layout),
2298                                       raid10_md_layout_to_copies(mddev->new_layout));
2299                         }
2300                         return -EINVAL;
2301                 }
2302
2303                 DMINFO("Discovered old metadata format; upgrading to extended metadata format");
2304         }
2305
2306         if (!test_bit(__CTR_FLAG_NOSYNC, &rs->ctr_flags))
2307                 mddev->recovery_cp = le64_to_cpu(sb->array_resync_offset);
2308
2309         /*
2310          * During load, we set FirstUse if a new superblock was written.
2311          * There are two reasons we might not have a superblock:
2312          * 1) The raid set is brand new - in which case, all of the
2313          *    devices must have their In_sync bit set.  Also,
2314          *    recovery_cp must be 0, unless forced.
2315          * 2) This is a new device being added to an old raid set
2316          *    and the new device needs to be rebuilt - in which
2317          *    case the In_sync bit will /not/ be set and
2318          *    recovery_cp must be MaxSector.
2319          * 3) This is/are a new device(s) being added to an old
2320          *    raid set during takeover to a higher raid level
2321          *    to provide capacity for redundancy or during reshape
2322          *    to add capacity to grow the raid set.
2323          */
2324         d = 0;
2325         rdev_for_each(r, mddev) {
2326                 if (test_bit(Journal, &rdev->flags))
2327                         continue;
2328
2329                 if (test_bit(FirstUse, &r->flags))
2330                         new_devs++;
2331
2332                 if (!test_bit(In_sync, &r->flags)) {
2333                         DMINFO("Device %d specified for rebuild; clearing superblock",
2334                                 r->raid_disk);
2335                         rebuilds++;
2336
2337                         if (test_bit(FirstUse, &r->flags))
2338                                 rebuild_and_new++;
2339                 }
2340
2341                 d++;
2342         }
2343
2344         if (new_devs == rs->raid_disks || !rebuilds) {
2345                 /* Replace a broken device */
2346                 if (new_devs == 1 && !rs->delta_disks)
2347                         ;
2348                 if (new_devs == rs->raid_disks) {
2349                         DMINFO("Superblocks created for new raid set");
2350                         set_bit(MD_ARRAY_FIRST_USE, &mddev->flags);
2351                 } else if (new_devs != rebuilds &&
2352                            new_devs != rs->delta_disks) {
2353                         DMERR("New device injected into existing raid set without "
2354                               "'delta_disks' or 'rebuild' parameter specified");
2355                         return -EINVAL;
2356                 }
2357         } else if (new_devs && new_devs != rebuilds) {
2358                 DMERR("%u 'rebuild' devices cannot be injected into"
2359                       " a raid set with %u other first-time devices",
2360                       rebuilds, new_devs);
2361                 return -EINVAL;
2362         } else if (rebuilds) {
2363                 if (rebuild_and_new && rebuilds != rebuild_and_new) {
2364                         DMERR("new device%s provided without 'rebuild'",
2365                               new_devs > 1 ? "s" : "");
2366                         return -EINVAL;
2367                 } else if (!test_bit(__CTR_FLAG_REBUILD, &rs->ctr_flags) && rs_is_recovering(rs)) {
2368                         DMERR("'rebuild' specified while raid set is not in-sync (recovery_cp=%llu)",
2369                               (unsigned long long) mddev->recovery_cp);
2370                         return -EINVAL;
2371                 } else if (rs_is_reshaping(rs)) {
2372                         DMERR("'rebuild' specified while raid set is being reshaped (reshape_position=%llu)",
2373                               (unsigned long long) mddev->reshape_position);
2374                         return -EINVAL;
2375                 }
2376         }
2377
2378         /*
2379          * Now we set the Faulty bit for those devices that are
2380          * recorded in the superblock as failed.
2381          */
2382         sb_retrieve_failed_devices(sb, failed_devices);
2383         rdev_for_each(r, mddev) {
2384                 if (test_bit(Journal, &rdev->flags) ||
2385                     !r->sb_page)
2386                         continue;
2387                 sb2 = page_address(r->sb_page);
2388                 sb2->failed_devices = 0;
2389                 memset(sb2->extended_failed_devices, 0, sizeof(sb2->extended_failed_devices));
2390
2391                 /*
2392                  * Check for any device re-ordering.
2393                  */
2394                 if (!test_bit(FirstUse, &r->flags) && (r->raid_disk >= 0)) {
2395                         role = le32_to_cpu(sb2->array_position);
2396                         if (role < 0)
2397                                 continue;
2398
2399                         if (role != r->raid_disk) {
2400                                 if (rs_is_raid10(rs) && __is_raid10_near(mddev->layout)) {
2401                                         if (mddev->raid_disks % __raid10_near_copies(mddev->layout) ||
2402                                             rs->raid_disks % rs->raid10_copies) {
2403                                                 rs->ti->error =
2404                                                         "Cannot change raid10 near set to odd # of devices!";
2405                                                 return -EINVAL;
2406                                         }
2407
2408                                         sb2->array_position = cpu_to_le32(r->raid_disk);
2409
2410                                 } else if (!(rs_is_raid10(rs) && rt_is_raid0(rs->raid_type)) &&
2411                                            !(rs_is_raid0(rs) && rt_is_raid10(rs->raid_type)) &&
2412                                            !rt_is_raid1(rs->raid_type)) {
2413                                         rs->ti->error = "Cannot change device positions in raid set";
2414                                         return -EINVAL;
2415                                 }
2416
2417                                 DMINFO("raid device #%d now at position #%d", role, r->raid_disk);
2418                         }
2419
2420                         /*
2421                          * Partial recovery is performed on
2422                          * returning failed devices.
2423                          */
2424                         if (test_bit(role, (void *) failed_devices))
2425                                 set_bit(Faulty, &r->flags);
2426                 }
2427         }
2428
2429         return 0;
2430 }
2431
2432 static int super_validate(struct raid_set *rs, struct md_rdev *rdev)
2433 {
2434         struct mddev *mddev = &rs->md;
2435         struct dm_raid_superblock *sb;
2436
2437         if (rs_is_raid0(rs) || !rdev->sb_page || rdev->raid_disk < 0)
2438                 return 0;
2439
2440         sb = page_address(rdev->sb_page);
2441
2442         /*
2443          * If mddev->events is not set, we know we have not yet initialized
2444          * the array.
2445          */
2446         if (!mddev->events && super_init_validation(rs, rdev))
2447                 return -EINVAL;
2448
2449         if (le32_to_cpu(sb->compat_features) &&
2450             le32_to_cpu(sb->compat_features) != FEATURE_FLAG_SUPPORTS_V190) {
2451                 rs->ti->error = "Unable to assemble array: Unknown flag(s) in compatible feature flags";
2452                 return -EINVAL;
2453         }
2454
2455         if (sb->incompat_features) {
2456                 rs->ti->error = "Unable to assemble array: No incompatible feature flags supported yet";
2457                 return -EINVAL;
2458         }
2459
2460         /* Enable bitmap creation on @rs unless no metadevs or raid0 or journaled raid4/5/6 set. */
2461         mddev->bitmap_info.offset = (rt_is_raid0(rs->raid_type) || rs->journal_dev.dev) ? 0 : to_sector(4096);
2462         mddev->bitmap_info.default_offset = mddev->bitmap_info.offset;
2463
2464         if (!test_and_clear_bit(FirstUse, &rdev->flags)) {
2465                 /*
2466                  * Retrieve rdev size stored in superblock to be prepared for shrink.
2467                  * Check extended superblock members are present otherwise the size
2468                  * will not be set!
2469                  */
2470                 if (le32_to_cpu(sb->compat_features) & FEATURE_FLAG_SUPPORTS_V190)
2471                         rdev->sectors = le64_to_cpu(sb->sectors);
2472
2473                 rdev->recovery_offset = le64_to_cpu(sb->disk_recovery_offset);
2474                 if (rdev->recovery_offset == MaxSector)
2475                         set_bit(In_sync, &rdev->flags);
2476                 /*
2477                  * If no reshape in progress -> we're recovering single
2478                  * disk(s) and have to set the device(s) to out-of-sync
2479                  */
2480                 else if (!rs_is_reshaping(rs))
2481                         clear_bit(In_sync, &rdev->flags); /* Mandatory for recovery */
2482         }
2483
2484         /*
2485          * If a device comes back, set it as not In_sync and no longer faulty.
2486          */
2487         if (test_and_clear_bit(Faulty, &rdev->flags)) {
2488                 rdev->recovery_offset = 0;
2489                 clear_bit(In_sync, &rdev->flags);
2490                 rdev->saved_raid_disk = rdev->raid_disk;
2491         }
2492
2493         /* Reshape support -> restore repective data offsets */
2494         rdev->data_offset = le64_to_cpu(sb->data_offset);
2495         rdev->new_data_offset = le64_to_cpu(sb->new_data_offset);
2496
2497         return 0;
2498 }
2499
2500 /*
2501  * Analyse superblocks and select the freshest.
2502  */
2503 static int analyse_superblocks(struct dm_target *ti, struct raid_set *rs)
2504 {
2505         int r;
2506         struct md_rdev *rdev, *freshest;
2507         struct mddev *mddev = &rs->md;
2508
2509         freshest = NULL;
2510         rdev_for_each(rdev, mddev) {
2511                 if (test_bit(Journal, &rdev->flags))
2512                         continue;
2513
2514                 if (!rdev->meta_bdev)
2515                         continue;
2516
2517                 /* Set superblock offset/size for metadata device. */
2518                 rdev->sb_start = 0;
2519                 rdev->sb_size = bdev_logical_block_size(rdev->meta_bdev);
2520                 if (rdev->sb_size < sizeof(struct dm_raid_superblock) || rdev->sb_size > PAGE_SIZE) {
2521                         DMERR("superblock size of a logical block is no longer valid");
2522                         return -EINVAL;
2523                 }
2524
2525                 /*
2526                  * Skipping super_load due to CTR_FLAG_SYNC will cause
2527                  * the array to undergo initialization again as
2528                  * though it were new.  This is the intended effect
2529                  * of the "sync" directive.
2530                  *
2531                  * With reshaping capability added, we must ensure that
2532                  * that the "sync" directive is disallowed during the reshape.
2533                  */
2534                 if (test_bit(__CTR_FLAG_SYNC, &rs->ctr_flags))
2535                         continue;
2536
2537                 r = super_load(rdev, freshest);
2538
2539                 switch (r) {
2540                 case 1:
2541                         freshest = rdev;
2542                         break;
2543                 case 0:
2544                         break;
2545                 default:
2546                         /* This is a failure to read the superblock from the metadata device. */
2547                         /*
2548                          * We have to keep any raid0 data/metadata device pairs or
2549                          * the MD raid0 personality will fail to start the array.
2550                          */
2551                         if (rs_is_raid0(rs))
2552                                 continue;
2553
2554                         /*
2555                          * We keep the dm_devs to be able to emit the device tuple
2556                          * properly on the table line in raid_status() (rather than
2557                          * mistakenly acting as if '- -' got passed into the constructor).
2558                          *
2559                          * The rdev has to stay on the same_set list to allow for
2560                          * the attempt to restore faulty devices on second resume.
2561                          */
2562                         rdev->raid_disk = rdev->saved_raid_disk = -1;
2563                         break;
2564                 }
2565         }
2566
2567         if (!freshest)
2568                 return 0;
2569
2570         /*
2571          * Validation of the freshest device provides the source of
2572          * validation for the remaining devices.
2573          */
2574         rs->ti->error = "Unable to assemble array: Invalid superblocks";
2575         if (super_validate(rs, freshest))
2576                 return -EINVAL;
2577
2578         if (validate_raid_redundancy(rs)) {
2579                 rs->ti->error = "Insufficient redundancy to activate array";
2580                 return -EINVAL;
2581         }
2582
2583         rdev_for_each(rdev, mddev)
2584                 if (!test_bit(Journal, &rdev->flags) &&
2585                     rdev != freshest &&
2586                     super_validate(rs, rdev))
2587                         return -EINVAL;
2588         return 0;
2589 }
2590
2591 /*
2592  * Adjust data_offset and new_data_offset on all disk members of @rs
2593  * for out of place reshaping if requested by contructor
2594  *
2595  * We need free space at the beginning of each raid disk for forward
2596  * and at the end for backward reshapes which userspace has to provide
2597  * via remapping/reordering of space.
2598  */
2599 static int rs_adjust_data_offsets(struct raid_set *rs)
2600 {
2601         sector_t data_offset = 0, new_data_offset = 0;
2602         struct md_rdev *rdev;
2603
2604         /* Constructor did not request data offset change */
2605         if (!test_bit(__CTR_FLAG_DATA_OFFSET, &rs->ctr_flags)) {
2606                 if (!rs_is_reshapable(rs))
2607                         goto out;
2608
2609                 return 0;
2610         }
2611
2612         /* HM FIXME: get In_Sync raid_dev? */
2613         rdev = &rs->dev[0].rdev;
2614
2615         if (rs->delta_disks < 0) {
2616                 /*
2617                  * Removing disks (reshaping backwards):
2618                  *
2619                  * - before reshape: data is at offset 0 and free space
2620                  *                   is at end of each component LV
2621                  *
2622                  * - after reshape: data is at offset rs->data_offset != 0 on each component LV
2623                  */
2624                 data_offset = 0;
2625                 new_data_offset = rs->data_offset;
2626
2627         } else if (rs->delta_disks > 0) {
2628                 /*
2629                  * Adding disks (reshaping forwards):
2630                  *
2631                  * - before reshape: data is at offset rs->data_offset != 0 and
2632                  *                   free space is at begin of each component LV
2633                  *
2634                  * - after reshape: data is at offset 0 on each component LV
2635                  */
2636                 data_offset = rs->data_offset;
2637                 new_data_offset = 0;
2638
2639         } else {
2640                 /*
2641                  * User space passes in 0 for data offset after having removed reshape space
2642                  *
2643                  * - or - (data offset != 0)
2644                  *
2645                  * Changing RAID layout or chunk size -> toggle offsets
2646                  *
2647                  * - before reshape: data is at offset rs->data_offset 0 and
2648                  *                   free space is at end of each component LV
2649                  *                   -or-
2650                  *                   data is at offset rs->data_offset != 0 and
2651                  *                   free space is at begin of each component LV
2652                  *
2653                  * - after reshape: data is at offset 0 if it was at offset != 0
2654                  *                  or at offset != 0 if it was at offset 0
2655                  *                  on each component LV
2656                  *
2657                  */
2658                 data_offset = rs->data_offset ? rdev->data_offset : 0;
2659                 new_data_offset = data_offset ? 0 : rs->data_offset;
2660                 set_bit(RT_FLAG_UPDATE_SBS, &rs->runtime_flags);
2661         }
2662
2663         /*
2664          * Make sure we got a minimum amount of free sectors per device
2665          */
2666         if (rs->data_offset &&
2667             to_sector(i_size_read(rdev->bdev->bd_inode)) - rs->md.dev_sectors < MIN_FREE_RESHAPE_SPACE) {
2668                 rs->ti->error = data_offset ? "No space for forward reshape" :
2669                                               "No space for backward reshape";
2670                 return -ENOSPC;
2671         }
2672 out:
2673         /*
2674          * Raise recovery_cp in case data_offset != 0 to
2675          * avoid false recovery positives in the constructor.
2676          */
2677         if (rs->md.recovery_cp < rs->md.dev_sectors)
2678                 rs->md.recovery_cp += rs->dev[0].rdev.data_offset;
2679
2680         /* Adjust data offsets on all rdevs but on any raid4/5/6 journal device */
2681         rdev_for_each(rdev, &rs->md) {
2682                 if (!test_bit(Journal, &rdev->flags)) {
2683                         rdev->data_offset = data_offset;
2684                         rdev->new_data_offset = new_data_offset;
2685                 }
2686         }
2687
2688         return 0;
2689 }
2690
2691 /* Userpace reordered disks -> adjust raid_disk indexes in @rs */
2692 static void __reorder_raid_disk_indexes(struct raid_set *rs)
2693 {
2694         int i = 0;
2695         struct md_rdev *rdev;
2696
2697         rdev_for_each(rdev, &rs->md) {
2698                 if (!test_bit(Journal, &rdev->flags)) {
2699                         rdev->raid_disk = i++;
2700                         rdev->saved_raid_disk = rdev->new_raid_disk = -1;
2701                 }
2702         }
2703 }
2704
2705 /*
2706  * Setup @rs for takeover by a different raid level
2707  */
2708 static int rs_setup_takeover(struct raid_set *rs)
2709 {
2710         struct mddev *mddev = &rs->md;
2711         struct md_rdev *rdev;
2712         unsigned int d = mddev->raid_disks = rs->raid_disks;
2713         sector_t new_data_offset = rs->dev[0].rdev.data_offset ? 0 : rs->data_offset;
2714
2715         if (rt_is_raid10(rs->raid_type)) {
2716                 if (rs_is_raid0(rs)) {
2717                         /* Userpace reordered disks -> adjust raid_disk indexes */
2718                         __reorder_raid_disk_indexes(rs);
2719
2720                         /* raid0 -> raid10_far layout */
2721                         mddev->layout = raid10_format_to_md_layout(rs, ALGORITHM_RAID10_FAR,
2722                                                                    rs->raid10_copies);
2723                 } else if (rs_is_raid1(rs))
2724                         /* raid1 -> raid10_near layout */
2725                         mddev->layout = raid10_format_to_md_layout(rs, ALGORITHM_RAID10_NEAR,
2726                                                                    rs->raid_disks);
2727                 else
2728                         return -EINVAL;
2729
2730         }
2731
2732         clear_bit(MD_ARRAY_FIRST_USE, &mddev->flags);
2733         mddev->recovery_cp = MaxSector;
2734
2735         while (d--) {
2736                 rdev = &rs->dev[d].rdev;
2737
2738                 if (test_bit(d, (void *) rs->rebuild_disks)) {
2739                         clear_bit(In_sync, &rdev->flags);
2740                         clear_bit(Faulty, &rdev->flags);
2741                         mddev->recovery_cp = rdev->recovery_offset = 0;
2742                         /* Bitmap has to be created when we do an "up" takeover */
2743                         set_bit(MD_ARRAY_FIRST_USE, &mddev->flags);
2744                 }
2745
2746                 rdev->new_data_offset = new_data_offset;
2747         }
2748
2749         return 0;
2750 }
2751
2752 /* Prepare @rs for reshape */
2753 static int rs_prepare_reshape(struct raid_set *rs)
2754 {
2755         bool reshape;
2756         struct mddev *mddev = &rs->md;
2757
2758         if (rs_is_raid10(rs)) {
2759                 if (rs->raid_disks != mddev->raid_disks &&
2760                     __is_raid10_near(mddev->layout) &&
2761                     rs->raid10_copies &&
2762                     rs->raid10_copies != __raid10_near_copies(mddev->layout)) {
2763                         /*
2764                          * raid disk have to be multiple of data copies to allow this conversion,
2765                          *
2766                          * This is actually not a reshape it is a
2767                          * rebuild of any additional mirrors per group
2768                          */
2769                         if (rs->raid_disks % rs->raid10_copies) {
2770                                 rs->ti->error = "Can't reshape raid10 mirror groups";
2771                                 return -EINVAL;
2772                         }
2773
2774                         /* Userpace reordered disks to add/remove mirrors -> adjust raid_disk indexes */
2775                         __reorder_raid_disk_indexes(rs);
2776                         mddev->layout = raid10_format_to_md_layout(rs, ALGORITHM_RAID10_NEAR,
2777                                                                    rs->raid10_copies);
2778                         mddev->new_layout = mddev->layout;
2779                         reshape = false;
2780                 } else
2781                         reshape = true;
2782
2783         } else if (rs_is_raid456(rs))
2784                 reshape = true;
2785
2786         else if (rs_is_raid1(rs)) {
2787                 if (rs->delta_disks) {
2788                         /* Process raid1 via delta_disks */
2789                         mddev->degraded = rs->delta_disks < 0 ? -rs->delta_disks : rs->delta_disks;
2790                         reshape = true;
2791                 } else {
2792                         /* Process raid1 without delta_disks */
2793                         mddev->raid_disks = rs->raid_disks;
2794                         reshape = false;
2795                 }
2796         } else {
2797                 rs->ti->error = "Called with bogus raid type";
2798                 return -EINVAL;
2799         }
2800
2801         if (reshape) {
2802                 set_bit(RT_FLAG_RESHAPE_RS, &rs->runtime_flags);
2803                 set_bit(RT_FLAG_UPDATE_SBS, &rs->runtime_flags);
2804         } else if (mddev->raid_disks < rs->raid_disks)
2805                 /* Create new superblocks and bitmaps, if any new disks */
2806                 set_bit(RT_FLAG_UPDATE_SBS, &rs->runtime_flags);
2807
2808         return 0;
2809 }
2810
2811 /* Get reshape sectors from data_offsets or raid set */
2812 static sector_t _get_reshape_sectors(struct raid_set *rs)
2813 {
2814         struct md_rdev *rdev;
2815         sector_t reshape_sectors = 0;
2816
2817         rdev_for_each(rdev, &rs->md)
2818                 if (!test_bit(Journal, &rdev->flags)) {
2819                         reshape_sectors = (rdev->data_offset > rdev->new_data_offset) ?
2820                                         rdev->data_offset - rdev->new_data_offset :
2821                                         rdev->new_data_offset - rdev->data_offset;
2822                         break;
2823                 }
2824
2825         return max(reshape_sectors, (sector_t) rs->data_offset);
2826 }
2827
2828 /*
2829  *
2830  * - change raid layout
2831  * - change chunk size
2832  * - add disks
2833  * - remove disks
2834  */
2835 static int rs_setup_reshape(struct raid_set *rs)
2836 {
2837         int r = 0;
2838         unsigned int cur_raid_devs, d;
2839         sector_t reshape_sectors = _get_reshape_sectors(rs);
2840         struct mddev *mddev = &rs->md;
2841         struct md_rdev *rdev;
2842
2843         mddev->delta_disks = rs->delta_disks;
2844         cur_raid_devs = mddev->raid_disks;
2845
2846         /* Ignore impossible layout change whilst adding/removing disks */
2847         if (mddev->delta_disks &&
2848             mddev->layout != mddev->new_layout) {
2849                 DMINFO("Ignoring invalid layout change with delta_disks=%d", rs->delta_disks);
2850                 mddev->new_layout = mddev->layout;
2851         }
2852
2853         /*
2854          * Adjust array size:
2855          *
2856          * - in case of adding disk(s), array size has
2857          *   to grow after the disk adding reshape,
2858          *   which'll hapen in the event handler;
2859          *   reshape will happen forward, so space has to
2860          *   be available at the beginning of each disk
2861          *
2862          * - in case of removing disk(s), array size
2863          *   has to shrink before starting the reshape,
2864          *   which'll happen here;
2865          *   reshape will happen backward, so space has to
2866          *   be available at the end of each disk
2867          *
2868          * - data_offset and new_data_offset are
2869          *   adjusted for aforementioned out of place
2870          *   reshaping based on userspace passing in
2871          *   the "data_offset <sectors>" key/value
2872          *   pair via the constructor
2873          */
2874
2875         /* Add disk(s) */
2876         if (rs->delta_disks > 0) {
2877                 /* Prepare disks for check in raid4/5/6/10 {check|start}_reshape */
2878                 for (d = cur_raid_devs; d < rs->raid_disks; d++) {
2879                         rdev = &rs->dev[d].rdev;
2880                         clear_bit(In_sync, &rdev->flags);
2881
2882                         /*
2883                          * save_raid_disk needs to be -1, or recovery_offset will be set to 0
2884                          * by md, which'll store that erroneously in the superblock on reshape
2885                          */
2886                         rdev->saved_raid_disk = -1;
2887                         rdev->raid_disk = d;
2888
2889                         rdev->sectors = mddev->dev_sectors;
2890                         rdev->recovery_offset = rs_is_raid1(rs) ? 0 : MaxSector;
2891                 }
2892
2893                 mddev->reshape_backwards = 0; /* adding disk(s) -> forward reshape */
2894
2895         /* Remove disk(s) */
2896         } else if (rs->delta_disks < 0) {
2897                 r = rs_set_dev_and_array_sectors(rs, rs->ti->len, true);
2898                 mddev->reshape_backwards = 1; /* removing disk(s) -> backward reshape */
2899
2900         /* Change layout and/or chunk size */
2901         } else {
2902                 /*
2903                  * Reshape layout (e.g. raid5_ls -> raid5_n) and/or chunk size:
2904                  *
2905                  * keeping number of disks and do layout change ->
2906                  *
2907                  * toggle reshape_backward depending on data_offset:
2908                  *
2909                  * - free space upfront -> reshape forward
2910                  *
2911                  * - free space at the end -> reshape backward
2912                  *
2913                  *
2914                  * This utilizes free reshape space avoiding the need
2915                  * for userspace to move (parts of) LV segments in
2916                  * case of layout/chunksize change  (for disk
2917                  * adding/removing reshape space has to be at
2918                  * the proper address (see above with delta_disks):
2919                  *
2920                  * add disk(s)   -> begin
2921                  * remove disk(s)-> end
2922                  */
2923                 mddev->reshape_backwards = rs->dev[0].rdev.data_offset ? 0 : 1;
2924         }
2925
2926         /*
2927          * Adjust device size for forward reshape
2928          * because md_finish_reshape() reduces it.
2929          */
2930         if (!mddev->reshape_backwards)
2931                 rdev_for_each(rdev, &rs->md)
2932                         if (!test_bit(Journal, &rdev->flags))
2933                                 rdev->sectors += reshape_sectors;
2934
2935         return r;
2936 }
2937
2938 /*
2939  * Enable/disable discard support on RAID set depending on
2940  * RAID level and discard properties of underlying RAID members.
2941  */
2942 static void configure_discard_support(struct raid_set *rs)
2943 {
2944         int i;
2945         bool raid456;
2946         struct dm_target *ti = rs->ti;
2947
2948         /*
2949          * XXX: RAID level 4,5,6 require zeroing for safety.
2950          */
2951         raid456 = rs_is_raid456(rs);
2952
2953         for (i = 0; i < rs->raid_disks; i++) {
2954                 struct request_queue *q;
2955
2956                 if (!rs->dev[i].rdev.bdev)
2957                         continue;
2958
2959                 q = bdev_get_queue(rs->dev[i].rdev.bdev);
2960                 if (!q || !blk_queue_discard(q))
2961                         return;
2962
2963                 if (raid456) {
2964                         if (!devices_handle_discard_safely) {
2965                                 DMERR("raid456 discard support disabled due to discard_zeroes_data uncertainty.");
2966                                 DMERR("Set dm-raid.devices_handle_discard_safely=Y to override.");
2967                                 return;
2968                         }
2969                 }
2970         }
2971
2972         ti->num_discard_bios = 1;
2973 }
2974
2975 /*
2976  * Construct a RAID0/1/10/4/5/6 mapping:
2977  * Args:
2978  *      <raid_type> <#raid_params> <raid_params>{0,}    \
2979  *      <#raid_devs> [<meta_dev1> <dev1>]{1,}
2980  *
2981  * <raid_params> varies by <raid_type>.  See 'parse_raid_params' for
2982  * details on possible <raid_params>.
2983  *
2984  * Userspace is free to initialize the metadata devices, hence the superblocks to
2985  * enforce recreation based on the passed in table parameters.
2986  *
2987  */
2988 static int raid_ctr(struct dm_target *ti, unsigned int argc, char **argv)
2989 {
2990         int r;
2991         bool resize = false;
2992         struct raid_type *rt;
2993         unsigned int num_raid_params, num_raid_devs;
2994         sector_t sb_array_sectors, rdev_sectors, reshape_sectors;
2995         struct raid_set *rs = NULL;
2996         const char *arg;
2997         struct rs_layout rs_layout;
2998         struct dm_arg_set as = { argc, argv }, as_nrd;
2999         struct dm_arg _args[] = {
3000                 { 0, as.argc, "Cannot understand number of raid parameters" },
3001                 { 1, 254, "Cannot understand number of raid devices parameters" }
3002         };
3003
3004         /* Must have <raid_type> */
3005         arg = dm_shift_arg(&as);
3006         if (!arg) {
3007                 ti->error = "No arguments";
3008                 return -EINVAL;
3009         }
3010
3011         rt = get_raid_type(arg);
3012         if (!rt) {
3013                 ti->error = "Unrecognised raid_type";
3014                 return -EINVAL;
3015         }
3016
3017         /* Must have <#raid_params> */
3018         if (dm_read_arg_group(_args, &as, &num_raid_params, &ti->error))
3019                 return -EINVAL;
3020
3021         /* number of raid device tupples <meta_dev data_dev> */
3022         as_nrd = as;
3023         dm_consume_args(&as_nrd, num_raid_params);
3024         _args[1].max = (as_nrd.argc - 1) / 2;
3025         if (dm_read_arg(_args + 1, &as_nrd, &num_raid_devs, &ti->error))
3026                 return -EINVAL;
3027
3028         if (!__within_range(num_raid_devs, 1, MAX_RAID_DEVICES)) {
3029                 ti->error = "Invalid number of supplied raid devices";
3030                 return -EINVAL;
3031         }
3032
3033         rs = raid_set_alloc(ti, rt, num_raid_devs);
3034         if (IS_ERR(rs))
3035                 return PTR_ERR(rs);
3036
3037         r = parse_raid_params(rs, &as, num_raid_params);
3038         if (r)
3039                 goto bad;
3040
3041         r = parse_dev_params(rs, &as);
3042         if (r)
3043                 goto bad;
3044
3045         rs->md.sync_super = super_sync;
3046
3047         /*
3048          * Calculate ctr requested array and device sizes to allow
3049          * for superblock analysis needing device sizes defined.
3050          *
3051          * Any existing superblock will overwrite the array and device sizes
3052          */
3053         r = rs_set_dev_and_array_sectors(rs, rs->ti->len, false);
3054         if (r)
3055                 goto bad;
3056
3057         /* Memorize just calculated, potentially larger sizes to grow the raid set in preresume */
3058         rs->array_sectors = rs->md.array_sectors;
3059         rs->dev_sectors = rs->md.dev_sectors;
3060
3061         /*
3062          * Backup any new raid set level, layout, ...
3063          * requested to be able to compare to superblock
3064          * members for conversion decisions.
3065          */
3066         rs_config_backup(rs, &rs_layout);
3067
3068         r = analyse_superblocks(ti, rs);
3069         if (r)
3070                 goto bad;
3071
3072         /* All in-core metadata now as of current superblocks after calling analyse_superblocks() */
3073         sb_array_sectors = rs->md.array_sectors;
3074         rdev_sectors = __rdev_sectors(rs);
3075         if (!rdev_sectors) {
3076                 ti->error = "Invalid rdev size";
3077                 r = -EINVAL;
3078                 goto bad;
3079         }
3080
3081
3082         reshape_sectors = _get_reshape_sectors(rs);
3083         if (rs->dev_sectors != rdev_sectors) {
3084                 resize = (rs->dev_sectors != rdev_sectors - reshape_sectors);
3085                 if (rs->dev_sectors > rdev_sectors - reshape_sectors)
3086                         set_bit(RT_FLAG_RS_GROW, &rs->runtime_flags);
3087         }
3088
3089         INIT_WORK(&rs->md.event_work, do_table_event);
3090         ti->private = rs;
3091         ti->num_flush_bios = 1;
3092
3093         /* Restore any requested new layout for conversion decision */
3094         rs_config_restore(rs, &rs_layout);
3095
3096         /*
3097          * Now that we have any superblock metadata available,
3098          * check for new, recovering, reshaping, to be taken over,
3099          * to be reshaped or an existing, unchanged raid set to
3100          * run in sequence.
3101          */
3102         if (test_bit(MD_ARRAY_FIRST_USE, &rs->md.flags)) {
3103                 /* A new raid6 set has to be recovered to ensure proper parity and Q-Syndrome */
3104                 if (rs_is_raid6(rs) &&
3105                     test_bit(__CTR_FLAG_NOSYNC, &rs->ctr_flags)) {
3106                         ti->error = "'nosync' not allowed for new raid6 set";
3107                         r = -EINVAL;
3108                         goto bad;
3109                 }
3110                 rs_setup_recovery(rs, 0);
3111                 set_bit(RT_FLAG_UPDATE_SBS, &rs->runtime_flags);
3112                 rs_set_new(rs);
3113         } else if (rs_is_recovering(rs)) {
3114                 /* A recovering raid set may be resized */
3115                 goto size_check;
3116         } else if (rs_is_reshaping(rs)) {
3117                 /* Have to reject size change request during reshape */
3118                 if (resize) {
3119                         ti->error = "Can't resize a reshaping raid set";
3120                         r = -EPERM;
3121                         goto bad;
3122                 }
3123                 /* skip setup rs */
3124         } else if (rs_takeover_requested(rs)) {
3125                 if (rs_is_reshaping(rs)) {
3126                         ti->error = "Can't takeover a reshaping raid set";
3127                         r = -EPERM;
3128                         goto bad;
3129                 }
3130
3131                 /* We can't takeover a journaled raid4/5/6 */
3132                 if (test_bit(__CTR_FLAG_JOURNAL_DEV, &rs->ctr_flags)) {
3133                         ti->error = "Can't takeover a journaled raid4/5/6 set";
3134                         r = -EPERM;
3135                         goto bad;
3136                 }
3137
3138                 /*
3139                  * If a takeover is needed, userspace sets any additional
3140                  * devices to rebuild and we can check for a valid request here.
3141                  *
3142                  * If acceptible, set the level to the new requested
3143                  * one, prohibit requesting recovery, allow the raid
3144                  * set to run and store superblocks during resume.
3145                  */
3146                 r = rs_check_takeover(rs);
3147                 if (r)
3148                         goto bad;
3149
3150                 r = rs_setup_takeover(rs);
3151                 if (r)
3152                         goto bad;
3153
3154                 set_bit(RT_FLAG_UPDATE_SBS, &rs->runtime_flags);
3155                 /* Takeover ain't recovery, so disable recovery */
3156                 rs_setup_recovery(rs, MaxSector);
3157                 rs_set_new(rs);
3158         } else if (rs_reshape_requested(rs)) {
3159                 /* Only request grow on raid set size extensions, not on reshapes. */
3160                 clear_bit(RT_FLAG_RS_GROW, &rs->runtime_flags);
3161
3162                 /*
3163                  * No need to check for 'ongoing' takeover here, because takeover
3164                  * is an instant operation as oposed to an ongoing reshape.
3165                  */
3166
3167                 /* We can't reshape a journaled raid4/5/6 */
3168                 if (test_bit(__CTR_FLAG_JOURNAL_DEV, &rs->ctr_flags)) {
3169                         ti->error = "Can't reshape a journaled raid4/5/6 set";
3170                         r = -EPERM;
3171                         goto bad;
3172                 }
3173
3174                 /* Out-of-place space has to be available to allow for a reshape unless raid1! */
3175                 if (reshape_sectors || rs_is_raid1(rs)) {
3176                         /*
3177                           * We can only prepare for a reshape here, because the
3178                           * raid set needs to run to provide the repective reshape
3179                           * check functions via its MD personality instance.
3180                           *
3181                           * So do the reshape check after md_run() succeeded.
3182                           */
3183                         r = rs_prepare_reshape(rs);
3184                         if (r)
3185                                 goto bad;
3186
3187                         /* Reshaping ain't recovery, so disable recovery */
3188                         rs_setup_recovery(rs, MaxSector);
3189                 }
3190                 rs_set_cur(rs);
3191         } else {
3192 size_check:
3193                 /* May not set recovery when a device rebuild is requested */
3194                 if (test_bit(__CTR_FLAG_REBUILD, &rs->ctr_flags)) {
3195                         clear_bit(RT_FLAG_RS_GROW, &rs->runtime_flags);
3196                         set_bit(RT_FLAG_UPDATE_SBS, &rs->runtime_flags);
3197                         rs_setup_recovery(rs, MaxSector);
3198                 } else if (test_bit(RT_FLAG_RS_GROW, &rs->runtime_flags)) {
3199                         /*
3200                          * Set raid set to current size, i.e. size as of
3201                          * superblocks to grow to larger size in preresume.
3202                          */
3203                         r = rs_set_dev_and_array_sectors(rs, sb_array_sectors, false);
3204                         if (r)
3205                                 goto bad;
3206
3207                         rs_setup_recovery(rs, rs->md.recovery_cp < rs->md.dev_sectors ? rs->md.recovery_cp : rs->md.dev_sectors);
3208                 } else {
3209                         /* This is no size change or it is shrinking, update size and record in superblocks */
3210                         r = rs_set_dev_and_array_sectors(rs, rs->ti->len, false);
3211                         if (r)
3212                                 goto bad;
3213
3214                         if (sb_array_sectors > rs->array_sectors)
3215                                 set_bit(RT_FLAG_UPDATE_SBS, &rs->runtime_flags);
3216                 }
3217                 rs_set_cur(rs);
3218         }
3219
3220         /* If constructor requested it, change data and new_data offsets */
3221         r = rs_adjust_data_offsets(rs);
3222         if (r)
3223                 goto bad;
3224
3225         /* Start raid set read-only and assumed clean to change in raid_resume() */
3226         rs->md.ro = 1;
3227         rs->md.in_sync = 1;
3228
3229         /* Keep array frozen */
3230         set_bit(MD_RECOVERY_FROZEN, &rs->md.recovery);
3231
3232         /* Has to be held on running the array */
3233         mddev_lock_nointr(&rs->md);
3234         r = md_run(&rs->md);
3235         rs->md.in_sync = 0; /* Assume already marked dirty */
3236         if (r) {
3237                 ti->error = "Failed to run raid array";
3238                 mddev_unlock(&rs->md);
3239                 goto bad;
3240         }
3241
3242         r = md_start(&rs->md);
3243
3244         if (r) {
3245                 ti->error = "Failed to start raid array";
3246                 mddev_unlock(&rs->md);
3247                 goto bad_md_start;
3248         }
3249
3250         rs->callbacks.congested_fn = raid_is_congested;
3251         dm_table_add_target_callbacks(ti->table, &rs->callbacks);
3252
3253         /* If raid4/5/6 journal mode explicitly requested (only possible with journal dev) -> set it */
3254         if (test_bit(__CTR_FLAG_JOURNAL_MODE, &rs->ctr_flags)) {
3255                 r = r5c_journal_mode_set(&rs->md, rs->journal_dev.mode);
3256                 if (r) {
3257                         ti->error = "Failed to set raid4/5/6 journal mode";
3258                         mddev_unlock(&rs->md);
3259                         goto bad_journal_mode_set;
3260                 }
3261         }
3262
3263         mddev_suspend(&rs->md);
3264         set_bit(RT_FLAG_RS_SUSPENDED, &rs->runtime_flags);
3265
3266         /* Try to adjust the raid4/5/6 stripe cache size to the stripe size */
3267         if (rs_is_raid456(rs)) {
3268                 r = rs_set_raid456_stripe_cache(rs);
3269                 if (r)
3270                         goto bad_stripe_cache;
3271         }
3272
3273         /* Now do an early reshape check */
3274         if (test_bit(RT_FLAG_RESHAPE_RS, &rs->runtime_flags)) {
3275                 r = rs_check_reshape(rs);
3276                 if (r)
3277                         goto bad_check_reshape;
3278
3279                 /* Restore new, ctr requested layout to perform check */
3280                 rs_config_restore(rs, &rs_layout);
3281
3282                 if (rs->md.pers->start_reshape) {
3283                         r = rs->md.pers->check_reshape(&rs->md);
3284                         if (r) {
3285                                 ti->error = "Reshape check failed";
3286                                 goto bad_check_reshape;
3287                         }
3288                 }
3289         }
3290
3291         /* Disable/enable discard support on raid set. */
3292         configure_discard_support(rs);
3293
3294         mddev_unlock(&rs->md);
3295         return 0;
3296
3297 bad_md_start:
3298 bad_journal_mode_set:
3299 bad_stripe_cache:
3300 bad_check_reshape:
3301         md_stop(&rs->md);
3302 bad:
3303         raid_set_free(rs);
3304
3305         return r;
3306 }
3307
3308 static void raid_dtr(struct dm_target *ti)
3309 {
3310         struct raid_set *rs = ti->private;
3311
3312         list_del_init(&rs->callbacks.list);
3313         md_stop(&rs->md);
3314         raid_set_free(rs);
3315 }
3316
3317 static int raid_map(struct dm_target *ti, struct bio *bio)
3318 {
3319         struct raid_set *rs = ti->private;
3320         struct mddev *mddev = &rs->md;
3321
3322         /*
3323          * If we're reshaping to add disk(s)), ti->len and
3324          * mddev->array_sectors will differ during the process
3325          * (ti->len > mddev->array_sectors), so we have to requeue
3326          * bios with addresses > mddev->array_sectors here or
3327          * there will occur accesses past EOD of the component
3328          * data images thus erroring the raid set.
3329          */
3330         if (unlikely(bio_end_sector(bio) > mddev->array_sectors))
3331                 return DM_MAPIO_REQUEUE;
3332
3333         md_handle_request(mddev, bio);
3334
3335         return DM_MAPIO_SUBMITTED;
3336 }
3337
3338 /* Return sync state string for @state */
3339 enum sync_state { st_frozen, st_reshape, st_resync, st_check, st_repair, st_recover, st_idle };
3340 static const char *sync_str(enum sync_state state)
3341 {
3342         /* Has to be in above sync_state order! */
3343         static const char *sync_strs[] = {
3344                 "frozen",
3345                 "reshape",
3346                 "resync",
3347                 "check",
3348                 "repair",
3349                 "recover",
3350                 "idle"
3351         };
3352
3353         return __within_range(state, 0, ARRAY_SIZE(sync_strs) - 1) ? sync_strs[state] : "undef";
3354 };
3355
3356 /* Return enum sync_state for @mddev derived from @recovery flags */
3357 static enum sync_state decipher_sync_action(struct mddev *mddev, unsigned long recovery)
3358 {
3359         if (test_bit(MD_RECOVERY_FROZEN, &recovery))
3360                 return st_frozen;
3361
3362         /* The MD sync thread can be done with io or be interrupted but still be running */
3363         if (!test_bit(MD_RECOVERY_DONE, &recovery) &&
3364             (test_bit(MD_RECOVERY_RUNNING, &recovery) ||
3365              (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &recovery)))) {
3366                 if (test_bit(MD_RECOVERY_RESHAPE, &recovery))
3367                         return st_reshape;
3368
3369                 if (test_bit(MD_RECOVERY_SYNC, &recovery)) {
3370                         if (!test_bit(MD_RECOVERY_REQUESTED, &recovery))
3371                                 return st_resync;
3372                         if (test_bit(MD_RECOVERY_CHECK, &recovery))
3373                                 return st_check;
3374                         return st_repair;
3375                 }
3376
3377                 if (test_bit(MD_RECOVERY_RECOVER, &recovery))
3378                         return st_recover;
3379
3380                 if (mddev->reshape_position != MaxSector)
3381                         return st_reshape;
3382         }
3383
3384         return st_idle;
3385 }
3386
3387 /*
3388  * Return status string for @rdev
3389  *
3390  * Status characters:
3391  *
3392  *  'D' = Dead/Failed raid set component or raid4/5/6 journal device
3393  *  'a' = Alive but not in-sync raid set component _or_ alive raid4/5/6 'write_back' journal device
3394  *  'A' = Alive and in-sync raid set component _or_ alive raid4/5/6 'write_through' journal device
3395  *  '-' = Non-existing device (i.e. uspace passed '- -' into the ctr)
3396  */
3397 static const char *__raid_dev_status(struct raid_set *rs, struct md_rdev *rdev)
3398 {
3399         if (!rdev->bdev)
3400                 return "-";
3401         else if (test_bit(Faulty, &rdev->flags))
3402                 return "D";
3403         else if (test_bit(Journal, &rdev->flags))
3404                 return (rs->journal_dev.mode == R5C_JOURNAL_MODE_WRITE_THROUGH) ? "A" : "a";
3405         else if (test_bit(RT_FLAG_RS_RESYNCING, &rs->runtime_flags) ||
3406                  (!test_bit(RT_FLAG_RS_IN_SYNC, &rs->runtime_flags) &&
3407                   !test_bit(In_sync, &rdev->flags)))
3408                 return "a";
3409         else
3410                 return "A";
3411 }
3412
3413 /* Helper to return resync/reshape progress for @rs and runtime flags for raid set in sync / resynching */
3414 static sector_t rs_get_progress(struct raid_set *rs, unsigned long recovery,
3415                                 enum sync_state state, sector_t resync_max_sectors)
3416 {
3417         sector_t r;
3418         struct mddev *mddev = &rs->md;
3419
3420         clear_bit(RT_FLAG_RS_IN_SYNC, &rs->runtime_flags);
3421         clear_bit(RT_FLAG_RS_RESYNCING, &rs->runtime_flags);
3422
3423         if (rs_is_raid0(rs)) {
3424                 r = resync_max_sectors;
3425                 set_bit(RT_FLAG_RS_IN_SYNC, &rs->runtime_flags);
3426
3427         } else {
3428                 if (state == st_idle && !test_bit(MD_RECOVERY_INTR, &recovery))
3429                         r = mddev->recovery_cp;
3430                 else
3431                         r = mddev->curr_resync_completed;
3432
3433                 if (state == st_idle && r >= resync_max_sectors) {
3434                         /*
3435                          * Sync complete.
3436                          */
3437                         /* In case we have finished recovering, the array is in sync. */
3438                         if (test_bit(MD_RECOVERY_RECOVER, &recovery))
3439                                 set_bit(RT_FLAG_RS_IN_SYNC, &rs->runtime_flags);
3440
3441                 } else if (state == st_recover)
3442                         /*
3443                          * In case we are recovering, the array is not in sync
3444                          * and health chars should show the recovering legs.
3445                          *
3446                          * Already retrieved recovery offset from curr_resync_completed above.
3447                          */
3448                         ;
3449
3450                 else if (state == st_resync || state == st_reshape)
3451                         /*
3452                          * If "resync/reshape" is occurring, the raid set
3453                          * is or may be out of sync hence the health
3454                          * characters shall be 'a'.
3455                          */
3456                         set_bit(RT_FLAG_RS_RESYNCING, &rs->runtime_flags);
3457
3458                 else if (state == st_check || state == st_repair)
3459                         /*
3460                          * If "check" or "repair" is occurring, the raid set has
3461                          * undergone an initial sync and the health characters
3462                          * should not be 'a' anymore.
3463                          */
3464                         set_bit(RT_FLAG_RS_IN_SYNC, &rs->runtime_flags);
3465
3466                 else if (test_bit(MD_RECOVERY_NEEDED, &recovery))
3467                         /*
3468                          * We are idle and recovery is needed, prevent 'A' chars race
3469                          * caused by components still set to in-sync by constructor.
3470                          */
3471                         set_bit(RT_FLAG_RS_RESYNCING, &rs->runtime_flags);
3472
3473                 else {
3474                         /*
3475                          * We are idle and the raid set may be doing an initial
3476                          * sync, or it may be rebuilding individual components.
3477                          * If all the devices are In_sync, then it is the raid set
3478                          * that is being initialized.
3479                          */
3480                         struct md_rdev *rdev;
3481
3482                         set_bit(RT_FLAG_RS_IN_SYNC, &rs->runtime_flags);
3483                         rdev_for_each(rdev, mddev)
3484                                 if (!test_bit(Journal, &rdev->flags) &&
3485                                     !test_bit(In_sync, &rdev->flags)) {
3486                                         clear_bit(RT_FLAG_RS_IN_SYNC, &rs->runtime_flags);
3487                                         break;
3488                                 }
3489                 }
3490         }
3491
3492         return min(r, resync_max_sectors);
3493 }
3494
3495 /* Helper to return @dev name or "-" if !@dev */
3496 static const char *__get_dev_name(struct dm_dev *dev)
3497 {
3498         return dev ? dev->name : "-";
3499 }
3500
3501 static void raid_status(struct dm_target *ti, status_type_t type,
3502                         unsigned int status_flags, char *result, unsigned int maxlen)
3503 {
3504         struct raid_set *rs = ti->private;
3505         struct mddev *mddev = &rs->md;
3506         struct r5conf *conf = mddev->private;
3507         int i, max_nr_stripes = conf ? conf->max_nr_stripes : 0;
3508         unsigned long recovery;
3509         unsigned int raid_param_cnt = 1; /* at least 1 for chunksize */
3510         unsigned int sz = 0;
3511         unsigned int rebuild_disks;
3512         unsigned int write_mostly_params = 0;
3513         sector_t progress, resync_max_sectors, resync_mismatches;
3514         enum sync_state state;
3515         struct raid_type *rt;
3516
3517         switch (type) {
3518         case STATUSTYPE_INFO:
3519                 /* *Should* always succeed */
3520                 rt = get_raid_type_by_ll(mddev->new_level, mddev->new_layout);
3521                 if (!rt)
3522                         return;
3523
3524                 DMEMIT("%s %d ", rt->name, mddev->raid_disks);
3525
3526                 /* Access most recent mddev properties for status output */
3527                 smp_rmb();
3528                 /* Get sensible max sectors even if raid set not yet started */
3529                 resync_max_sectors = test_bit(RT_FLAG_RS_PRERESUMED, &rs->runtime_flags) ?
3530                                       mddev->resync_max_sectors : mddev->dev_sectors;
3531                 recovery = rs->md.recovery;
3532                 state = decipher_sync_action(mddev, recovery);
3533                 progress = rs_get_progress(rs, recovery, state, resync_max_sectors);
3534                 resync_mismatches = (mddev->last_sync_action && !strcasecmp(mddev->last_sync_action, "check")) ?
3535                                     atomic64_read(&mddev->resync_mismatches) : 0;
3536
3537                 /* HM FIXME: do we want another state char for raid0? It shows 'D'/'A'/'-' now */
3538                 for (i = 0; i < rs->raid_disks; i++)
3539                         DMEMIT(__raid_dev_status(rs, &rs->dev[i].rdev));
3540
3541                 /*
3542                  * In-sync/Reshape ratio:
3543                  *  The in-sync ratio shows the progress of:
3544                  *   - Initializing the raid set
3545                  *   - Rebuilding a subset of devices of the raid set
3546                  *  The user can distinguish between the two by referring
3547                  *  to the status characters.
3548                  *
3549                  *  The reshape ratio shows the progress of
3550                  *  changing the raid layout or the number of
3551                  *  disks of a raid set
3552                  */
3553                 DMEMIT(" %llu/%llu", (unsigned long long) progress,
3554                                      (unsigned long long) resync_max_sectors);
3555
3556                 /*
3557                  * v1.5.0+:
3558                  *
3559                  * Sync action:
3560                  *   See Documentation/admin-guide/device-mapper/dm-raid.rst for
3561                  *   information on each of these states.
3562                  */
3563                 DMEMIT(" %s", sync_str(state));
3564
3565                 /*
3566                  * v1.5.0+:
3567                  *
3568                  * resync_mismatches/mismatch_cnt
3569                  *   This field shows the number of discrepancies found when
3570                  *   performing a "check" of the raid set.
3571                  */
3572                 DMEMIT(" %llu", (unsigned long long) resync_mismatches);
3573
3574                 /*
3575                  * v1.9.0+:
3576                  *
3577                  * data_offset (needed for out of space reshaping)
3578                  *   This field shows the data offset into the data
3579                  *   image LV where the first stripes data starts.
3580                  *
3581                  * We keep data_offset equal on all raid disks of the set,
3582                  * so retrieving it from the first raid disk is sufficient.
3583                  */
3584                 DMEMIT(" %llu", (unsigned long long) rs->dev[0].rdev.data_offset);
3585
3586                 /*
3587                  * v1.10.0+:
3588                  */
3589                 DMEMIT(" %s", test_bit(__CTR_FLAG_JOURNAL_DEV, &rs->ctr_flags) ?
3590                               __raid_dev_status(rs, &rs->journal_dev.rdev) : "-");
3591                 break;
3592
3593         case STATUSTYPE_TABLE:
3594                 /* Report the table line string you would use to construct this raid set */
3595
3596                 /* Calculate raid parameter count */
3597                 for (i = 0; i < rs->raid_disks; i++)
3598                         if (test_bit(WriteMostly, &rs->dev[i].rdev.flags))
3599                                 write_mostly_params += 2;
3600                 rebuild_disks = memweight(rs->rebuild_disks, DISKS_ARRAY_ELEMS * sizeof(*rs->rebuild_disks));
3601                 raid_param_cnt += rebuild_disks * 2 +
3602                                   write_mostly_params +
3603                                   hweight32(rs->ctr_flags & CTR_FLAG_OPTIONS_NO_ARGS) +
3604                                   hweight32(rs->ctr_flags & CTR_FLAG_OPTIONS_ONE_ARG) * 2 +
3605                                   (test_bit(__CTR_FLAG_JOURNAL_DEV, &rs->ctr_flags) ? 2 : 0) +
3606                                   (test_bit(__CTR_FLAG_JOURNAL_MODE, &rs->ctr_flags) ? 2 : 0);
3607
3608                 /* Emit table line */
3609                 /* This has to be in the documented order for userspace! */
3610                 DMEMIT("%s %u %u", rs->raid_type->name, raid_param_cnt, mddev->new_chunk_sectors);
3611                 if (test_bit(__CTR_FLAG_SYNC, &rs->ctr_flags))
3612                         DMEMIT(" %s", dm_raid_arg_name_by_flag(CTR_FLAG_SYNC));
3613                 if (test_bit(__CTR_FLAG_NOSYNC, &rs->ctr_flags))
3614                         DMEMIT(" %s", dm_raid_arg_name_by_flag(CTR_FLAG_NOSYNC));
3615                 if (rebuild_disks)
3616                         for (i = 0; i < rs->raid_disks; i++)
3617                                 if (test_bit(rs->dev[i].rdev.raid_disk, (void *) rs->rebuild_disks))
3618                                         DMEMIT(" %s %u", dm_raid_arg_name_by_flag(CTR_FLAG_REBUILD),
3619                                                          rs->dev[i].rdev.raid_disk);
3620                 if (test_bit(__CTR_FLAG_DAEMON_SLEEP, &rs->ctr_flags))
3621                         DMEMIT(" %s %lu", dm_raid_arg_name_by_flag(CTR_FLAG_DAEMON_SLEEP),
3622                                           mddev->bitmap_info.daemon_sleep);
3623                 if (test_bit(__CTR_FLAG_MIN_RECOVERY_RATE, &rs->ctr_flags))
3624                         DMEMIT(" %s %d", dm_raid_arg_name_by_flag(CTR_FLAG_MIN_RECOVERY_RATE),
3625                                          mddev->sync_speed_min);
3626                 if (test_bit(__CTR_FLAG_MAX_RECOVERY_RATE, &rs->ctr_flags))
3627                         DMEMIT(" %s %d", dm_raid_arg_name_by_flag(CTR_FLAG_MAX_RECOVERY_RATE),
3628                                          mddev->sync_speed_max);
3629                 if (write_mostly_params)
3630                         for (i = 0; i < rs->raid_disks; i++)
3631                                 if (test_bit(WriteMostly, &rs->dev[i].rdev.flags))
3632                                         DMEMIT(" %s %d", dm_raid_arg_name_by_flag(CTR_FLAG_WRITE_MOSTLY),
3633                                                rs->dev[i].rdev.raid_disk);
3634                 if (test_bit(__CTR_FLAG_MAX_WRITE_BEHIND, &rs->ctr_flags))
3635                         DMEMIT(" %s %lu", dm_raid_arg_name_by_flag(CTR_FLAG_MAX_WRITE_BEHIND),
3636                                           mddev->bitmap_info.max_write_behind);
3637                 if (test_bit(__CTR_FLAG_STRIPE_CACHE, &rs->ctr_flags))
3638                         DMEMIT(" %s %d", dm_raid_arg_name_by_flag(CTR_FLAG_STRIPE_CACHE),
3639                                          max_nr_stripes);
3640                 if (test_bit(__CTR_FLAG_REGION_SIZE, &rs->ctr_flags))
3641                         DMEMIT(" %s %llu", dm_raid_arg_name_by_flag(CTR_FLAG_REGION_SIZE),
3642                                            (unsigned long long) to_sector(mddev->bitmap_info.chunksize));
3643                 if (test_bit(__CTR_FLAG_RAID10_COPIES, &rs->ctr_flags))
3644                         DMEMIT(" %s %d", dm_raid_arg_name_by_flag(CTR_FLAG_RAID10_COPIES),
3645                                          raid10_md_layout_to_copies(mddev->layout));
3646                 if (test_bit(__CTR_FLAG_RAID10_FORMAT, &rs->ctr_flags))
3647                         DMEMIT(" %s %s", dm_raid_arg_name_by_flag(CTR_FLAG_RAID10_FORMAT),
3648                                          raid10_md_layout_to_format(mddev->layout));
3649                 if (test_bit(__CTR_FLAG_DELTA_DISKS, &rs->ctr_flags))
3650                         DMEMIT(" %s %d", dm_raid_arg_name_by_flag(CTR_FLAG_DELTA_DISKS),
3651                                          max(rs->delta_disks, mddev->delta_disks));
3652                 if (test_bit(__CTR_FLAG_DATA_OFFSET, &rs->ctr_flags))
3653                         DMEMIT(" %s %llu", dm_raid_arg_name_by_flag(CTR_FLAG_DATA_OFFSET),
3654                                            (unsigned long long) rs->data_offset);
3655                 if (test_bit(__CTR_FLAG_JOURNAL_DEV, &rs->ctr_flags))
3656                         DMEMIT(" %s %s", dm_raid_arg_name_by_flag(CTR_FLAG_JOURNAL_DEV),
3657                                         __get_dev_name(rs->journal_dev.dev));
3658                 if (test_bit(__CTR_FLAG_JOURNAL_MODE, &rs->ctr_flags))
3659                         DMEMIT(" %s %s", dm_raid_arg_name_by_flag(CTR_FLAG_JOURNAL_MODE),
3660                                          md_journal_mode_to_dm_raid(rs->journal_dev.mode));
3661                 DMEMIT(" %d", rs->raid_disks);
3662                 for (i = 0; i < rs->raid_disks; i++)
3663                         DMEMIT(" %s %s", __get_dev_name(rs->dev[i].meta_dev),
3664                                          __get_dev_name(rs->dev[i].data_dev));
3665         }
3666 }
3667
3668 static int raid_message(struct dm_target *ti, unsigned int argc, char **argv,
3669                         char *result, unsigned maxlen)
3670 {
3671         struct raid_set *rs = ti->private;
3672         struct mddev *mddev = &rs->md;
3673
3674         if (!mddev->pers || !mddev->pers->sync_request)
3675                 return -EINVAL;
3676
3677         if (!strcasecmp(argv[0], "frozen"))
3678                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3679         else
3680                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3681
3682         if (!strcasecmp(argv[0], "idle") || !strcasecmp(argv[0], "frozen")) {
3683                 if (mddev->sync_thread) {
3684                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3685                         md_reap_sync_thread(mddev);
3686                 }
3687         } else if (decipher_sync_action(mddev, mddev->recovery) != st_idle)
3688                 return -EBUSY;
3689         else if (!strcasecmp(argv[0], "resync"))
3690                 ; /* MD_RECOVERY_NEEDED set below */
3691         else if (!strcasecmp(argv[0], "recover"))
3692                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
3693         else {
3694                 if (!strcasecmp(argv[0], "check")) {
3695                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
3696                         set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
3697                         set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3698                 } else if (!strcasecmp(argv[0], "repair")) {
3699                         set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
3700                         set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3701                 } else
3702                         return -EINVAL;
3703         }
3704         if (mddev->ro == 2) {
3705                 /* A write to sync_action is enough to justify
3706                  * canceling read-auto mode
3707                  */
3708                 mddev->ro = 0;
3709                 if (!mddev->suspended && mddev->sync_thread)
3710                         md_wakeup_thread(mddev->sync_thread);
3711         }
3712         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3713         if (!mddev->suspended && mddev->thread)
3714                 md_wakeup_thread(mddev->thread);
3715
3716         return 0;
3717 }
3718
3719 static int raid_iterate_devices(struct dm_target *ti,
3720                                 iterate_devices_callout_fn fn, void *data)
3721 {
3722         struct raid_set *rs = ti->private;
3723         unsigned int i;
3724         int r = 0;
3725
3726         for (i = 0; !r && i < rs->md.raid_disks; i++)
3727                 if (rs->dev[i].data_dev)
3728                         r = fn(ti,
3729                                  rs->dev[i].data_dev,
3730                                  0, /* No offset on data devs */
3731                                  rs->md.dev_sectors,
3732                                  data);
3733
3734         return r;
3735 }
3736
3737 static void raid_io_hints(struct dm_target *ti, struct queue_limits *limits)
3738 {
3739         struct raid_set *rs = ti->private;
3740         unsigned int chunk_size_bytes = to_bytes(rs->md.chunk_sectors);
3741
3742         blk_limits_io_min(limits, chunk_size_bytes);
3743         blk_limits_io_opt(limits, chunk_size_bytes * mddev_data_stripes(rs));
3744
3745         /*
3746          * RAID1 and RAID10 personalities require bio splitting,
3747          * RAID0/4/5/6 don't and process large discard bios properly.
3748          */
3749         if (rs_is_raid1(rs) || rs_is_raid10(rs)) {
3750                 limits->discard_granularity = chunk_size_bytes;
3751                 limits->max_discard_sectors = rs->md.chunk_sectors;
3752         }
3753 }
3754
3755 static void raid_postsuspend(struct dm_target *ti)
3756 {
3757         struct raid_set *rs = ti->private;
3758
3759         if (!test_and_set_bit(RT_FLAG_RS_SUSPENDED, &rs->runtime_flags)) {
3760                 /* Writes have to be stopped before suspending to avoid deadlocks. */
3761                 if (!test_bit(MD_RECOVERY_FROZEN, &rs->md.recovery))
3762                         md_stop_writes(&rs->md);
3763
3764                 mddev_lock_nointr(&rs->md);
3765                 mddev_suspend(&rs->md);
3766                 mddev_unlock(&rs->md);
3767         }
3768 }
3769
3770 static void attempt_restore_of_faulty_devices(struct raid_set *rs)
3771 {
3772         int i;
3773         uint64_t cleared_failed_devices[DISKS_ARRAY_ELEMS];
3774         unsigned long flags;
3775         bool cleared = false;
3776         struct dm_raid_superblock *sb;
3777         struct mddev *mddev = &rs->md;
3778         struct md_rdev *r;
3779
3780         /* RAID personalities have to provide hot add/remove methods or we need to bail out. */
3781         if (!mddev->pers || !mddev->pers->hot_add_disk || !mddev->pers->hot_remove_disk)
3782                 return;
3783
3784         memset(cleared_failed_devices, 0, sizeof(cleared_failed_devices));
3785
3786         for (i = 0; i < mddev->raid_disks; i++) {
3787                 r = &rs->dev[i].rdev;
3788                 /* HM FIXME: enhance journal device recovery processing */
3789                 if (test_bit(Journal, &r->flags))
3790                         continue;
3791
3792                 if (test_bit(Faulty, &r->flags) &&
3793                     r->meta_bdev && !read_disk_sb(r, r->sb_size, true)) {
3794                         DMINFO("Faulty %s device #%d has readable super block."
3795                                "  Attempting to revive it.",
3796                                rs->raid_type->name, i);
3797
3798                         /*
3799                          * Faulty bit may be set, but sometimes the array can
3800                          * be suspended before the personalities can respond
3801                          * by removing the device from the array (i.e. calling
3802                          * 'hot_remove_disk').  If they haven't yet removed
3803                          * the failed device, its 'raid_disk' number will be
3804                          * '>= 0' - meaning we must call this function
3805                          * ourselves.
3806                          */
3807                         flags = r->flags;
3808                         clear_bit(In_sync, &r->flags); /* Mandatory for hot remove. */
3809                         if (r->raid_disk >= 0) {
3810                                 if (mddev->pers->hot_remove_disk(mddev, r)) {
3811                                         /* Failed to revive this device, try next */
3812                                         r->flags = flags;
3813                                         continue;
3814                                 }
3815                         } else
3816                                 r->raid_disk = r->saved_raid_disk = i;
3817
3818                         clear_bit(Faulty, &r->flags);
3819                         clear_bit(WriteErrorSeen, &r->flags);
3820
3821                         if (mddev->pers->hot_add_disk(mddev, r)) {
3822                                 /* Failed to revive this device, try next */
3823                                 r->raid_disk = r->saved_raid_disk = -1;
3824                                 r->flags = flags;
3825                         } else {
3826                                 clear_bit(In_sync, &r->flags);
3827                                 r->recovery_offset = 0;
3828                                 set_bit(i, (void *) cleared_failed_devices);
3829                                 cleared = true;
3830                         }
3831                 }
3832         }
3833
3834         /* If any failed devices could be cleared, update all sbs failed_devices bits */
3835         if (cleared) {
3836                 uint64_t failed_devices[DISKS_ARRAY_ELEMS];
3837
3838                 rdev_for_each(r, &rs->md) {
3839                         if (test_bit(Journal, &r->flags))
3840                                 continue;
3841
3842                         sb = page_address(r->sb_page);
3843                         sb_retrieve_failed_devices(sb, failed_devices);
3844
3845                         for (i = 0; i < DISKS_ARRAY_ELEMS; i++)
3846                                 failed_devices[i] &= ~cleared_failed_devices[i];
3847
3848                         sb_update_failed_devices(sb, failed_devices);
3849                 }
3850         }
3851 }
3852
3853 static int __load_dirty_region_bitmap(struct raid_set *rs)
3854 {
3855         int r = 0;
3856
3857         /* Try loading the bitmap unless "raid0", which does not have one */
3858         if (!rs_is_raid0(rs) &&
3859             !test_and_set_bit(RT_FLAG_RS_BITMAP_LOADED, &rs->runtime_flags)) {
3860                 r = md_bitmap_load(&rs->md);
3861                 if (r)
3862                         DMERR("Failed to load bitmap");
3863         }
3864
3865         return r;
3866 }
3867
3868 /* Enforce updating all superblocks */
3869 static void rs_update_sbs(struct raid_set *rs)
3870 {
3871         struct mddev *mddev = &rs->md;
3872         int ro = mddev->ro;
3873
3874         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
3875         mddev->ro = 0;
3876         md_update_sb(mddev, 1);
3877         mddev->ro = ro;
3878 }
3879
3880 /*
3881  * Reshape changes raid algorithm of @rs to new one within personality
3882  * (e.g. raid6_zr -> raid6_nc), changes stripe size, adds/removes
3883  * disks from a raid set thus growing/shrinking it or resizes the set
3884  *
3885  * Call mddev_lock_nointr() before!
3886  */
3887 static int rs_start_reshape(struct raid_set *rs)
3888 {
3889         int r;
3890         struct mddev *mddev = &rs->md;
3891         struct md_personality *pers = mddev->pers;
3892
3893         /* Don't allow the sync thread to work until the table gets reloaded. */
3894         set_bit(MD_RECOVERY_WAIT, &mddev->recovery);
3895
3896         r = rs_setup_reshape(rs);
3897         if (r)
3898                 return r;
3899
3900         /*
3901          * Check any reshape constraints enforced by the personalility
3902          *
3903          * May as well already kick the reshape off so that * pers->start_reshape() becomes optional.
3904          */
3905         r = pers->check_reshape(mddev);
3906         if (r) {
3907                 rs->ti->error = "pers->check_reshape() failed";
3908                 return r;
3909         }
3910
3911         /*
3912          * Personality may not provide start reshape method in which
3913          * case check_reshape above has already covered everything
3914          */
3915         if (pers->start_reshape) {
3916                 r = pers->start_reshape(mddev);
3917                 if (r) {
3918                         rs->ti->error = "pers->start_reshape() failed";
3919                         return r;
3920                 }
3921         }
3922
3923         /*
3924          * Now reshape got set up, update superblocks to
3925          * reflect the fact so that a table reload will
3926          * access proper superblock content in the ctr.
3927          */
3928         rs_update_sbs(rs);
3929
3930         return 0;
3931 }
3932
3933 static int raid_preresume(struct dm_target *ti)
3934 {
3935         int r;
3936         struct raid_set *rs = ti->private;
3937         struct mddev *mddev = &rs->md;
3938
3939         /* This is a resume after a suspend of the set -> it's already started. */
3940         if (test_and_set_bit(RT_FLAG_RS_PRERESUMED, &rs->runtime_flags))
3941                 return 0;
3942
3943         /*
3944          * The superblocks need to be updated on disk if the
3945          * array is new or new devices got added (thus zeroed
3946          * out by userspace) or __load_dirty_region_bitmap
3947          * will overwrite them in core with old data or fail.
3948          */
3949         if (test_bit(RT_FLAG_UPDATE_SBS, &rs->runtime_flags))
3950                 rs_update_sbs(rs);
3951
3952         /* Load the bitmap from disk unless raid0 */
3953         r = __load_dirty_region_bitmap(rs);
3954         if (r)
3955                 return r;
3956
3957         /* We are extending the raid set size, adjust mddev/md_rdev sizes and set capacity. */
3958         if (test_bit(RT_FLAG_RS_GROW, &rs->runtime_flags)) {
3959                 mddev->array_sectors = rs->array_sectors;
3960                 mddev->dev_sectors = rs->dev_sectors;
3961                 rs_set_rdev_sectors(rs);
3962                 rs_set_capacity(rs);
3963         }
3964
3965         /* Resize bitmap to adjust to changed region size (aka MD bitmap chunksize) or grown device size */
3966         if (test_bit(RT_FLAG_RS_BITMAP_LOADED, &rs->runtime_flags) && mddev->bitmap &&
3967             (test_bit(RT_FLAG_RS_GROW, &rs->runtime_flags) ||
3968              (rs->requested_bitmap_chunk_sectors &&
3969                mddev->bitmap_info.chunksize != to_bytes(rs->requested_bitmap_chunk_sectors)))) {
3970                 int chunksize = to_bytes(rs->requested_bitmap_chunk_sectors) ?: mddev->bitmap_info.chunksize;
3971
3972                 r = md_bitmap_resize(mddev->bitmap, mddev->dev_sectors, chunksize, 0);
3973                 if (r)
3974                         DMERR("Failed to resize bitmap");
3975         }
3976
3977         /* Check for any resize/reshape on @rs and adjust/initiate */
3978         /* Be prepared for mddev_resume() in raid_resume() */
3979         set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3980         if (mddev->recovery_cp && mddev->recovery_cp < MaxSector) {
3981                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
3982                 mddev->resync_min = mddev->recovery_cp;
3983                 if (test_bit(RT_FLAG_RS_GROW, &rs->runtime_flags))
3984                         mddev->resync_max_sectors = mddev->dev_sectors;
3985         }
3986
3987         /* Check for any reshape request unless new raid set */
3988         if (test_bit(RT_FLAG_RESHAPE_RS, &rs->runtime_flags)) {
3989                 /* Initiate a reshape. */
3990                 rs_set_rdev_sectors(rs);
3991                 mddev_lock_nointr(mddev);
3992                 r = rs_start_reshape(rs);
3993                 mddev_unlock(mddev);
3994                 if (r)
3995                         DMWARN("Failed to check/start reshape, continuing without change");
3996                 r = 0;
3997         }
3998
3999         return r;
4000 }
4001
4002 static void raid_resume(struct dm_target *ti)
4003 {
4004         struct raid_set *rs = ti->private;
4005         struct mddev *mddev = &rs->md;
4006
4007         if (test_and_set_bit(RT_FLAG_RS_RESUMED, &rs->runtime_flags)) {
4008                 /*
4009                  * A secondary resume while the device is active.
4010                  * Take this opportunity to check whether any failed
4011                  * devices are reachable again.
4012                  */
4013                 attempt_restore_of_faulty_devices(rs);
4014         }
4015
4016         if (test_and_clear_bit(RT_FLAG_RS_SUSPENDED, &rs->runtime_flags)) {
4017                 /* Only reduce raid set size before running a disk removing reshape. */
4018                 if (mddev->delta_disks < 0)
4019                         rs_set_capacity(rs);
4020
4021                 mddev_lock_nointr(mddev);
4022                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4023                 mddev->ro = 0;
4024                 mddev->in_sync = 0;
4025                 mddev_resume(mddev);
4026                 mddev_unlock(mddev);
4027         }
4028 }
4029
4030 static struct target_type raid_target = {
4031         .name = "raid",
4032         .version = {1, 15, 0},
4033         .module = THIS_MODULE,
4034         .ctr = raid_ctr,
4035         .dtr = raid_dtr,
4036         .map = raid_map,
4037         .status = raid_status,
4038         .message = raid_message,
4039         .iterate_devices = raid_iterate_devices,
4040         .io_hints = raid_io_hints,
4041         .postsuspend = raid_postsuspend,
4042         .preresume = raid_preresume,
4043         .resume = raid_resume,
4044 };
4045
4046 static int __init dm_raid_init(void)
4047 {
4048         DMINFO("Loading target version %u.%u.%u",
4049                raid_target.version[0],
4050                raid_target.version[1],
4051                raid_target.version[2]);
4052         return dm_register_target(&raid_target);
4053 }
4054
4055 static void __exit dm_raid_exit(void)
4056 {
4057         dm_unregister_target(&raid_target);
4058 }
4059
4060 module_init(dm_raid_init);
4061 module_exit(dm_raid_exit);
4062
4063 module_param(devices_handle_discard_safely, bool, 0644);
4064 MODULE_PARM_DESC(devices_handle_discard_safely,
4065                  "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
4066
4067 MODULE_DESCRIPTION(DM_NAME " raid0/1/10/4/5/6 target");
4068 MODULE_ALIAS("dm-raid0");
4069 MODULE_ALIAS("dm-raid1");
4070 MODULE_ALIAS("dm-raid10");
4071 MODULE_ALIAS("dm-raid4");
4072 MODULE_ALIAS("dm-raid5");
4073 MODULE_ALIAS("dm-raid6");
4074 MODULE_AUTHOR("Neil Brown <dm-devel@redhat.com>");
4075 MODULE_AUTHOR("Heinz Mauelshagen <dm-devel@redhat.com>");
4076 MODULE_LICENSE("GPL");