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