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