dm: support non power of two target max_io_len
[platform/adaptation/renesas_rcar/renesas_kernel.git] / drivers / md / dm-raid.c
1 /*
2  * Copyright (C) 2010-2011 Neil Brown
3  * Copyright (C) 2010-2011 Red Hat, Inc. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7
8 #include <linux/slab.h>
9 #include <linux/module.h>
10
11 #include "md.h"
12 #include "raid1.h"
13 #include "raid5.h"
14 #include "bitmap.h"
15
16 #include <linux/device-mapper.h>
17
18 #define DM_MSG_PREFIX "raid"
19
20 /*
21  * The following flags are used by dm-raid.c to set up the array state.
22  * They must be cleared before md_run is called.
23  */
24 #define FirstUse 10             /* rdev flag */
25
26 struct raid_dev {
27         /*
28          * Two DM devices, one to hold metadata and one to hold the
29          * actual data/parity.  The reason for this is to not confuse
30          * ti->len and give more flexibility in altering size and
31          * characteristics.
32          *
33          * While it is possible for this device to be associated
34          * with a different physical device than the data_dev, it
35          * is intended for it to be the same.
36          *    |--------- Physical Device ---------|
37          *    |- meta_dev -|------ data_dev ------|
38          */
39         struct dm_dev *meta_dev;
40         struct dm_dev *data_dev;
41         struct md_rdev rdev;
42 };
43
44 /*
45  * Flags for rs->print_flags field.
46  */
47 #define DMPF_SYNC              0x1
48 #define DMPF_NOSYNC            0x2
49 #define DMPF_REBUILD           0x4
50 #define DMPF_DAEMON_SLEEP      0x8
51 #define DMPF_MIN_RECOVERY_RATE 0x10
52 #define DMPF_MAX_RECOVERY_RATE 0x20
53 #define DMPF_MAX_WRITE_BEHIND  0x40
54 #define DMPF_STRIPE_CACHE      0x80
55 #define DMPF_REGION_SIZE       0X100
56 struct raid_set {
57         struct dm_target *ti;
58
59         uint32_t bitmap_loaded;
60         uint32_t print_flags;
61
62         struct mddev md;
63         struct raid_type *raid_type;
64         struct dm_target_callbacks callbacks;
65
66         struct raid_dev dev[0];
67 };
68
69 /* Supported raid types and properties. */
70 static struct raid_type {
71         const char *name;               /* RAID algorithm. */
72         const char *descr;              /* Descriptor text for logging. */
73         const unsigned parity_devs;     /* # of parity devices. */
74         const unsigned minimal_devs;    /* minimal # of devices in set. */
75         const unsigned level;           /* RAID level. */
76         const unsigned algorithm;       /* RAID algorithm. */
77 } raid_types[] = {
78         {"raid1",    "RAID1 (mirroring)",               0, 2, 1, 0 /* NONE */},
79         {"raid4",    "RAID4 (dedicated parity disk)",   1, 2, 5, ALGORITHM_PARITY_0},
80         {"raid5_la", "RAID5 (left asymmetric)",         1, 2, 5, ALGORITHM_LEFT_ASYMMETRIC},
81         {"raid5_ra", "RAID5 (right asymmetric)",        1, 2, 5, ALGORITHM_RIGHT_ASYMMETRIC},
82         {"raid5_ls", "RAID5 (left symmetric)",          1, 2, 5, ALGORITHM_LEFT_SYMMETRIC},
83         {"raid5_rs", "RAID5 (right symmetric)",         1, 2, 5, ALGORITHM_RIGHT_SYMMETRIC},
84         {"raid6_zr", "RAID6 (zero restart)",            2, 4, 6, ALGORITHM_ROTATING_ZERO_RESTART},
85         {"raid6_nr", "RAID6 (N restart)",               2, 4, 6, ALGORITHM_ROTATING_N_RESTART},
86         {"raid6_nc", "RAID6 (N continue)",              2, 4, 6, ALGORITHM_ROTATING_N_CONTINUE}
87 };
88
89 static struct raid_type *get_raid_type(char *name)
90 {
91         int i;
92
93         for (i = 0; i < ARRAY_SIZE(raid_types); i++)
94                 if (!strcmp(raid_types[i].name, name))
95                         return &raid_types[i];
96
97         return NULL;
98 }
99
100 static struct raid_set *context_alloc(struct dm_target *ti, struct raid_type *raid_type, unsigned raid_devs)
101 {
102         unsigned i;
103         struct raid_set *rs;
104         sector_t sectors_per_dev;
105
106         if (raid_devs <= raid_type->parity_devs) {
107                 ti->error = "Insufficient number of devices";
108                 return ERR_PTR(-EINVAL);
109         }
110
111         sectors_per_dev = ti->len;
112         if ((raid_type->level > 1) &&
113             sector_div(sectors_per_dev, (raid_devs - raid_type->parity_devs))) {
114                 ti->error = "Target length not divisible by number of data devices";
115                 return ERR_PTR(-EINVAL);
116         }
117
118         rs = kzalloc(sizeof(*rs) + raid_devs * sizeof(rs->dev[0]), GFP_KERNEL);
119         if (!rs) {
120                 ti->error = "Cannot allocate raid context";
121                 return ERR_PTR(-ENOMEM);
122         }
123
124         mddev_init(&rs->md);
125
126         rs->ti = ti;
127         rs->raid_type = raid_type;
128         rs->md.raid_disks = raid_devs;
129         rs->md.level = raid_type->level;
130         rs->md.new_level = rs->md.level;
131         rs->md.dev_sectors = sectors_per_dev;
132         rs->md.layout = raid_type->algorithm;
133         rs->md.new_layout = rs->md.layout;
134         rs->md.delta_disks = 0;
135         rs->md.recovery_cp = 0;
136
137         for (i = 0; i < raid_devs; i++)
138                 md_rdev_init(&rs->dev[i].rdev);
139
140         /*
141          * Remaining items to be initialized by further RAID params:
142          *  rs->md.persistent
143          *  rs->md.external
144          *  rs->md.chunk_sectors
145          *  rs->md.new_chunk_sectors
146          */
147
148         return rs;
149 }
150
151 static void context_free(struct raid_set *rs)
152 {
153         int i;
154
155         for (i = 0; i < rs->md.raid_disks; i++) {
156                 if (rs->dev[i].meta_dev)
157                         dm_put_device(rs->ti, rs->dev[i].meta_dev);
158                 md_rdev_clear(&rs->dev[i].rdev);
159                 if (rs->dev[i].data_dev)
160                         dm_put_device(rs->ti, rs->dev[i].data_dev);
161         }
162
163         kfree(rs);
164 }
165
166 /*
167  * For every device we have two words
168  *  <meta_dev>: meta device name or '-' if missing
169  *  <data_dev>: data device name or '-' if missing
170  *
171  * The following are permitted:
172  *    - -
173  *    - <data_dev>
174  *    <meta_dev> <data_dev>
175  *
176  * The following is not allowed:
177  *    <meta_dev> -
178  *
179  * This code parses those words.  If there is a failure,
180  * the caller must use context_free to unwind the operations.
181  */
182 static int dev_parms(struct raid_set *rs, char **argv)
183 {
184         int i;
185         int rebuild = 0;
186         int metadata_available = 0;
187         int ret = 0;
188
189         for (i = 0; i < rs->md.raid_disks; i++, argv += 2) {
190                 rs->dev[i].rdev.raid_disk = i;
191
192                 rs->dev[i].meta_dev = NULL;
193                 rs->dev[i].data_dev = NULL;
194
195                 /*
196                  * There are no offsets, since there is a separate device
197                  * for data and metadata.
198                  */
199                 rs->dev[i].rdev.data_offset = 0;
200                 rs->dev[i].rdev.mddev = &rs->md;
201
202                 if (strcmp(argv[0], "-")) {
203                         ret = dm_get_device(rs->ti, argv[0],
204                                             dm_table_get_mode(rs->ti->table),
205                                             &rs->dev[i].meta_dev);
206                         rs->ti->error = "RAID metadata device lookup failure";
207                         if (ret)
208                                 return ret;
209
210                         rs->dev[i].rdev.sb_page = alloc_page(GFP_KERNEL);
211                         if (!rs->dev[i].rdev.sb_page)
212                                 return -ENOMEM;
213                 }
214
215                 if (!strcmp(argv[1], "-")) {
216                         if (!test_bit(In_sync, &rs->dev[i].rdev.flags) &&
217                             (!rs->dev[i].rdev.recovery_offset)) {
218                                 rs->ti->error = "Drive designated for rebuild not specified";
219                                 return -EINVAL;
220                         }
221
222                         rs->ti->error = "No data device supplied with metadata device";
223                         if (rs->dev[i].meta_dev)
224                                 return -EINVAL;
225
226                         continue;
227                 }
228
229                 ret = dm_get_device(rs->ti, argv[1],
230                                     dm_table_get_mode(rs->ti->table),
231                                     &rs->dev[i].data_dev);
232                 if (ret) {
233                         rs->ti->error = "RAID device lookup failure";
234                         return ret;
235                 }
236
237                 if (rs->dev[i].meta_dev) {
238                         metadata_available = 1;
239                         rs->dev[i].rdev.meta_bdev = rs->dev[i].meta_dev->bdev;
240                 }
241                 rs->dev[i].rdev.bdev = rs->dev[i].data_dev->bdev;
242                 list_add(&rs->dev[i].rdev.same_set, &rs->md.disks);
243                 if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
244                         rebuild++;
245         }
246
247         if (metadata_available) {
248                 rs->md.external = 0;
249                 rs->md.persistent = 1;
250                 rs->md.major_version = 2;
251         } else if (rebuild && !rs->md.recovery_cp) {
252                 /*
253                  * Without metadata, we will not be able to tell if the array
254                  * is in-sync or not - we must assume it is not.  Therefore,
255                  * it is impossible to rebuild a drive.
256                  *
257                  * Even if there is metadata, the on-disk information may
258                  * indicate that the array is not in-sync and it will then
259                  * fail at that time.
260                  *
261                  * User could specify 'nosync' option if desperate.
262                  */
263                 DMERR("Unable to rebuild drive while array is not in-sync");
264                 rs->ti->error = "RAID device lookup failure";
265                 return -EINVAL;
266         }
267
268         return 0;
269 }
270
271 /*
272  * validate_region_size
273  * @rs
274  * @region_size:  region size in sectors.  If 0, pick a size (4MiB default).
275  *
276  * Set rs->md.bitmap_info.chunksize (which really refers to 'region size').
277  * Ensure that (ti->len/region_size < 2^21) - required by MD bitmap.
278  *
279  * Returns: 0 on success, -EINVAL on failure.
280  */
281 static int validate_region_size(struct raid_set *rs, unsigned long region_size)
282 {
283         unsigned long min_region_size = rs->ti->len / (1 << 21);
284
285         if (!region_size) {
286                 /*
287                  * Choose a reasonable default.  All figures in sectors.
288                  */
289                 if (min_region_size > (1 << 13)) {
290                         DMINFO("Choosing default region size of %lu sectors",
291                                region_size);
292                         region_size = min_region_size;
293                 } else {
294                         DMINFO("Choosing default region size of 4MiB");
295                         region_size = 1 << 13; /* sectors */
296                 }
297         } else {
298                 /*
299                  * Validate user-supplied value.
300                  */
301                 if (region_size > rs->ti->len) {
302                         rs->ti->error = "Supplied region size is too large";
303                         return -EINVAL;
304                 }
305
306                 if (region_size < min_region_size) {
307                         DMERR("Supplied region_size (%lu sectors) below minimum (%lu)",
308                               region_size, min_region_size);
309                         rs->ti->error = "Supplied region size is too small";
310                         return -EINVAL;
311                 }
312
313                 if (!is_power_of_2(region_size)) {
314                         rs->ti->error = "Region size is not a power of 2";
315                         return -EINVAL;
316                 }
317
318                 if (region_size < rs->md.chunk_sectors) {
319                         rs->ti->error = "Region size is smaller than the chunk size";
320                         return -EINVAL;
321                 }
322         }
323
324         /*
325          * Convert sectors to bytes.
326          */
327         rs->md.bitmap_info.chunksize = (region_size << 9);
328
329         return 0;
330 }
331
332 /*
333  * Possible arguments are...
334  *      <chunk_size> [optional_args]
335  *
336  * Argument definitions
337  *    <chunk_size>                      The number of sectors per disk that
338  *                                      will form the "stripe"
339  *    [[no]sync]                        Force or prevent recovery of the
340  *                                      entire array
341  *    [rebuild <idx>]                   Rebuild the drive indicated by the index
342  *    [daemon_sleep <ms>]               Time between bitmap daemon work to
343  *                                      clear bits
344  *    [min_recovery_rate <kB/sec/disk>] Throttle RAID initialization
345  *    [max_recovery_rate <kB/sec/disk>] Throttle RAID initialization
346  *    [write_mostly <idx>]              Indicate a write mostly drive via index
347  *    [max_write_behind <sectors>]      See '-write-behind=' (man mdadm)
348  *    [stripe_cache <sectors>]          Stripe cache size for higher RAIDs
349  *    [region_size <sectors>]           Defines granularity of bitmap
350  */
351 static int parse_raid_params(struct raid_set *rs, char **argv,
352                              unsigned num_raid_params)
353 {
354         unsigned i, rebuild_cnt = 0;
355         unsigned long value, region_size = 0;
356         sector_t max_io_len;
357         char *key;
358
359         /*
360          * First, parse the in-order required arguments
361          * "chunk_size" is the only argument of this type.
362          */
363         if ((strict_strtoul(argv[0], 10, &value) < 0)) {
364                 rs->ti->error = "Bad chunk size";
365                 return -EINVAL;
366         } else if (rs->raid_type->level == 1) {
367                 if (value)
368                         DMERR("Ignoring chunk size parameter for RAID 1");
369                 value = 0;
370         } else if (!is_power_of_2(value)) {
371                 rs->ti->error = "Chunk size must be a power of 2";
372                 return -EINVAL;
373         } else if (value < 8) {
374                 rs->ti->error = "Chunk size value is too small";
375                 return -EINVAL;
376         }
377
378         rs->md.new_chunk_sectors = rs->md.chunk_sectors = value;
379         argv++;
380         num_raid_params--;
381
382         /*
383          * We set each individual device as In_sync with a completed
384          * 'recovery_offset'.  If there has been a device failure or
385          * replacement then one of the following cases applies:
386          *
387          *   1) User specifies 'rebuild'.
388          *      - Device is reset when param is read.
389          *   2) A new device is supplied.
390          *      - No matching superblock found, resets device.
391          *   3) Device failure was transient and returns on reload.
392          *      - Failure noticed, resets device for bitmap replay.
393          *   4) Device hadn't completed recovery after previous failure.
394          *      - Superblock is read and overrides recovery_offset.
395          *
396          * What is found in the superblocks of the devices is always
397          * authoritative, unless 'rebuild' or '[no]sync' was specified.
398          */
399         for (i = 0; i < rs->md.raid_disks; i++) {
400                 set_bit(In_sync, &rs->dev[i].rdev.flags);
401                 rs->dev[i].rdev.recovery_offset = MaxSector;
402         }
403
404         /*
405          * Second, parse the unordered optional arguments
406          */
407         for (i = 0; i < num_raid_params; i++) {
408                 if (!strcasecmp(argv[i], "nosync")) {
409                         rs->md.recovery_cp = MaxSector;
410                         rs->print_flags |= DMPF_NOSYNC;
411                         continue;
412                 }
413                 if (!strcasecmp(argv[i], "sync")) {
414                         rs->md.recovery_cp = 0;
415                         rs->print_flags |= DMPF_SYNC;
416                         continue;
417                 }
418
419                 /* The rest of the optional arguments come in key/value pairs */
420                 if ((i + 1) >= num_raid_params) {
421                         rs->ti->error = "Wrong number of raid parameters given";
422                         return -EINVAL;
423                 }
424
425                 key = argv[i++];
426                 if (strict_strtoul(argv[i], 10, &value) < 0) {
427                         rs->ti->error = "Bad numerical argument given in raid params";
428                         return -EINVAL;
429                 }
430
431                 if (!strcasecmp(key, "rebuild")) {
432                         rebuild_cnt++;
433                         if (((rs->raid_type->level != 1) &&
434                              (rebuild_cnt > rs->raid_type->parity_devs)) ||
435                             ((rs->raid_type->level == 1) &&
436                              (rebuild_cnt > (rs->md.raid_disks - 1)))) {
437                                 rs->ti->error = "Too many rebuild devices specified for given RAID type";
438                                 return -EINVAL;
439                         }
440                         if (value > rs->md.raid_disks) {
441                                 rs->ti->error = "Invalid rebuild index given";
442                                 return -EINVAL;
443                         }
444                         clear_bit(In_sync, &rs->dev[value].rdev.flags);
445                         rs->dev[value].rdev.recovery_offset = 0;
446                         rs->print_flags |= DMPF_REBUILD;
447                 } else if (!strcasecmp(key, "write_mostly")) {
448                         if (rs->raid_type->level != 1) {
449                                 rs->ti->error = "write_mostly option is only valid for RAID1";
450                                 return -EINVAL;
451                         }
452                         if (value >= rs->md.raid_disks) {
453                                 rs->ti->error = "Invalid write_mostly drive index given";
454                                 return -EINVAL;
455                         }
456                         set_bit(WriteMostly, &rs->dev[value].rdev.flags);
457                 } else if (!strcasecmp(key, "max_write_behind")) {
458                         if (rs->raid_type->level != 1) {
459                                 rs->ti->error = "max_write_behind option is only valid for RAID1";
460                                 return -EINVAL;
461                         }
462                         rs->print_flags |= DMPF_MAX_WRITE_BEHIND;
463
464                         /*
465                          * In device-mapper, we specify things in sectors, but
466                          * MD records this value in kB
467                          */
468                         value /= 2;
469                         if (value > COUNTER_MAX) {
470                                 rs->ti->error = "Max write-behind limit out of range";
471                                 return -EINVAL;
472                         }
473                         rs->md.bitmap_info.max_write_behind = value;
474                 } else if (!strcasecmp(key, "daemon_sleep")) {
475                         rs->print_flags |= DMPF_DAEMON_SLEEP;
476                         if (!value || (value > MAX_SCHEDULE_TIMEOUT)) {
477                                 rs->ti->error = "daemon sleep period out of range";
478                                 return -EINVAL;
479                         }
480                         rs->md.bitmap_info.daemon_sleep = value;
481                 } else if (!strcasecmp(key, "stripe_cache")) {
482                         rs->print_flags |= DMPF_STRIPE_CACHE;
483
484                         /*
485                          * In device-mapper, we specify things in sectors, but
486                          * MD records this value in kB
487                          */
488                         value /= 2;
489
490                         if (rs->raid_type->level < 5) {
491                                 rs->ti->error = "Inappropriate argument: stripe_cache";
492                                 return -EINVAL;
493                         }
494                         if (raid5_set_cache_size(&rs->md, (int)value)) {
495                                 rs->ti->error = "Bad stripe_cache size";
496                                 return -EINVAL;
497                         }
498                 } else if (!strcasecmp(key, "min_recovery_rate")) {
499                         rs->print_flags |= DMPF_MIN_RECOVERY_RATE;
500                         if (value > INT_MAX) {
501                                 rs->ti->error = "min_recovery_rate out of range";
502                                 return -EINVAL;
503                         }
504                         rs->md.sync_speed_min = (int)value;
505                 } else if (!strcasecmp(key, "max_recovery_rate")) {
506                         rs->print_flags |= DMPF_MAX_RECOVERY_RATE;
507                         if (value > INT_MAX) {
508                                 rs->ti->error = "max_recovery_rate out of range";
509                                 return -EINVAL;
510                         }
511                         rs->md.sync_speed_max = (int)value;
512                 } else if (!strcasecmp(key, "region_size")) {
513                         rs->print_flags |= DMPF_REGION_SIZE;
514                         region_size = value;
515                 } else {
516                         DMERR("Unable to parse RAID parameter: %s", key);
517                         rs->ti->error = "Unable to parse RAID parameters";
518                         return -EINVAL;
519                 }
520         }
521
522         if (validate_region_size(rs, region_size))
523                 return -EINVAL;
524
525         if (rs->md.chunk_sectors)
526                 max_io_len = rs->md.chunk_sectors;
527         else
528                 max_io_len = region_size;
529
530         if (dm_set_target_max_io_len(rs->ti, max_io_len))
531                 return -EINVAL;
532
533         /* Assume there are no metadata devices until the drives are parsed */
534         rs->md.persistent = 0;
535         rs->md.external = 1;
536
537         return 0;
538 }
539
540 static void do_table_event(struct work_struct *ws)
541 {
542         struct raid_set *rs = container_of(ws, struct raid_set, md.event_work);
543
544         dm_table_event(rs->ti->table);
545 }
546
547 static int raid_is_congested(struct dm_target_callbacks *cb, int bits)
548 {
549         struct raid_set *rs = container_of(cb, struct raid_set, callbacks);
550
551         if (rs->raid_type->level == 1)
552                 return md_raid1_congested(&rs->md, bits);
553
554         return md_raid5_congested(&rs->md, bits);
555 }
556
557 /*
558  * This structure is never routinely used by userspace, unlike md superblocks.
559  * Devices with this superblock should only ever be accessed via device-mapper.
560  */
561 #define DM_RAID_MAGIC 0x64526D44
562 struct dm_raid_superblock {
563         __le32 magic;           /* "DmRd" */
564         __le32 features;        /* Used to indicate possible future changes */
565
566         __le32 num_devices;     /* Number of devices in this array. (Max 64) */
567         __le32 array_position;  /* The position of this drive in the array */
568
569         __le64 events;          /* Incremented by md when superblock updated */
570         __le64 failed_devices;  /* Bit field of devices to indicate failures */
571
572         /*
573          * This offset tracks the progress of the repair or replacement of
574          * an individual drive.
575          */
576         __le64 disk_recovery_offset;
577
578         /*
579          * This offset tracks the progress of the initial array
580          * synchronisation/parity calculation.
581          */
582         __le64 array_resync_offset;
583
584         /*
585          * RAID characteristics
586          */
587         __le32 level;
588         __le32 layout;
589         __le32 stripe_sectors;
590
591         __u8 pad[452];          /* Round struct to 512 bytes. */
592                                 /* Always set to 0 when writing. */
593 } __packed;
594
595 static int read_disk_sb(struct md_rdev *rdev, int size)
596 {
597         BUG_ON(!rdev->sb_page);
598
599         if (rdev->sb_loaded)
600                 return 0;
601
602         if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, 1)) {
603                 DMERR("Failed to read superblock of device at position %d",
604                       rdev->raid_disk);
605                 md_error(rdev->mddev, rdev);
606                 return -EINVAL;
607         }
608
609         rdev->sb_loaded = 1;
610
611         return 0;
612 }
613
614 static void super_sync(struct mddev *mddev, struct md_rdev *rdev)
615 {
616         int i;
617         uint64_t failed_devices;
618         struct dm_raid_superblock *sb;
619         struct raid_set *rs = container_of(mddev, struct raid_set, md);
620
621         sb = page_address(rdev->sb_page);
622         failed_devices = le64_to_cpu(sb->failed_devices);
623
624         for (i = 0; i < mddev->raid_disks; i++)
625                 if (!rs->dev[i].data_dev ||
626                     test_bit(Faulty, &(rs->dev[i].rdev.flags)))
627                         failed_devices |= (1ULL << i);
628
629         memset(sb, 0, sizeof(*sb));
630
631         sb->magic = cpu_to_le32(DM_RAID_MAGIC);
632         sb->features = cpu_to_le32(0);  /* No features yet */
633
634         sb->num_devices = cpu_to_le32(mddev->raid_disks);
635         sb->array_position = cpu_to_le32(rdev->raid_disk);
636
637         sb->events = cpu_to_le64(mddev->events);
638         sb->failed_devices = cpu_to_le64(failed_devices);
639
640         sb->disk_recovery_offset = cpu_to_le64(rdev->recovery_offset);
641         sb->array_resync_offset = cpu_to_le64(mddev->recovery_cp);
642
643         sb->level = cpu_to_le32(mddev->level);
644         sb->layout = cpu_to_le32(mddev->layout);
645         sb->stripe_sectors = cpu_to_le32(mddev->chunk_sectors);
646 }
647
648 /*
649  * super_load
650  *
651  * This function creates a superblock if one is not found on the device
652  * and will decide which superblock to use if there's a choice.
653  *
654  * Return: 1 if use rdev, 0 if use refdev, -Exxx otherwise
655  */
656 static int super_load(struct md_rdev *rdev, struct md_rdev *refdev)
657 {
658         int ret;
659         struct dm_raid_superblock *sb;
660         struct dm_raid_superblock *refsb;
661         uint64_t events_sb, events_refsb;
662
663         rdev->sb_start = 0;
664         rdev->sb_size = sizeof(*sb);
665
666         ret = read_disk_sb(rdev, rdev->sb_size);
667         if (ret)
668                 return ret;
669
670         sb = page_address(rdev->sb_page);
671
672         /*
673          * Two cases that we want to write new superblocks and rebuild:
674          * 1) New device (no matching magic number)
675          * 2) Device specified for rebuild (!In_sync w/ offset == 0)
676          */
677         if ((sb->magic != cpu_to_le32(DM_RAID_MAGIC)) ||
678             (!test_bit(In_sync, &rdev->flags) && !rdev->recovery_offset)) {
679                 super_sync(rdev->mddev, rdev);
680
681                 set_bit(FirstUse, &rdev->flags);
682
683                 /* Force writing of superblocks to disk */
684                 set_bit(MD_CHANGE_DEVS, &rdev->mddev->flags);
685
686                 /* Any superblock is better than none, choose that if given */
687                 return refdev ? 0 : 1;
688         }
689
690         if (!refdev)
691                 return 1;
692
693         events_sb = le64_to_cpu(sb->events);
694
695         refsb = page_address(refdev->sb_page);
696         events_refsb = le64_to_cpu(refsb->events);
697
698         return (events_sb > events_refsb) ? 1 : 0;
699 }
700
701 static int super_init_validation(struct mddev *mddev, struct md_rdev *rdev)
702 {
703         int role;
704         struct raid_set *rs = container_of(mddev, struct raid_set, md);
705         uint64_t events_sb;
706         uint64_t failed_devices;
707         struct dm_raid_superblock *sb;
708         uint32_t new_devs = 0;
709         uint32_t rebuilds = 0;
710         struct md_rdev *r;
711         struct dm_raid_superblock *sb2;
712
713         sb = page_address(rdev->sb_page);
714         events_sb = le64_to_cpu(sb->events);
715         failed_devices = le64_to_cpu(sb->failed_devices);
716
717         /*
718          * Initialise to 1 if this is a new superblock.
719          */
720         mddev->events = events_sb ? : 1;
721
722         /*
723          * Reshaping is not currently allowed
724          */
725         if ((le32_to_cpu(sb->level) != mddev->level) ||
726             (le32_to_cpu(sb->layout) != mddev->layout) ||
727             (le32_to_cpu(sb->stripe_sectors) != mddev->chunk_sectors)) {
728                 DMERR("Reshaping arrays not yet supported.");
729                 return -EINVAL;
730         }
731
732         /* We can only change the number of devices in RAID1 right now */
733         if ((rs->raid_type->level != 1) &&
734             (le32_to_cpu(sb->num_devices) != mddev->raid_disks)) {
735                 DMERR("Reshaping arrays not yet supported.");
736                 return -EINVAL;
737         }
738
739         if (!(rs->print_flags & (DMPF_SYNC | DMPF_NOSYNC)))
740                 mddev->recovery_cp = le64_to_cpu(sb->array_resync_offset);
741
742         /*
743          * During load, we set FirstUse if a new superblock was written.
744          * There are two reasons we might not have a superblock:
745          * 1) The array is brand new - in which case, all of the
746          *    devices must have their In_sync bit set.  Also,
747          *    recovery_cp must be 0, unless forced.
748          * 2) This is a new device being added to an old array
749          *    and the new device needs to be rebuilt - in which
750          *    case the In_sync bit will /not/ be set and
751          *    recovery_cp must be MaxSector.
752          */
753         rdev_for_each(r, mddev) {
754                 if (!test_bit(In_sync, &r->flags)) {
755                         DMINFO("Device %d specified for rebuild: "
756                                "Clearing superblock", r->raid_disk);
757                         rebuilds++;
758                 } else if (test_bit(FirstUse, &r->flags))
759                         new_devs++;
760         }
761
762         if (!rebuilds) {
763                 if (new_devs == mddev->raid_disks) {
764                         DMINFO("Superblocks created for new array");
765                         set_bit(MD_ARRAY_FIRST_USE, &mddev->flags);
766                 } else if (new_devs) {
767                         DMERR("New device injected "
768                               "into existing array without 'rebuild' "
769                               "parameter specified");
770                         return -EINVAL;
771                 }
772         } else if (new_devs) {
773                 DMERR("'rebuild' devices cannot be "
774                       "injected into an array with other first-time devices");
775                 return -EINVAL;
776         } else if (mddev->recovery_cp != MaxSector) {
777                 DMERR("'rebuild' specified while array is not in-sync");
778                 return -EINVAL;
779         }
780
781         /*
782          * Now we set the Faulty bit for those devices that are
783          * recorded in the superblock as failed.
784          */
785         rdev_for_each(r, mddev) {
786                 if (!r->sb_page)
787                         continue;
788                 sb2 = page_address(r->sb_page);
789                 sb2->failed_devices = 0;
790
791                 /*
792                  * Check for any device re-ordering.
793                  */
794                 if (!test_bit(FirstUse, &r->flags) && (r->raid_disk >= 0)) {
795                         role = le32_to_cpu(sb2->array_position);
796                         if (role != r->raid_disk) {
797                                 if (rs->raid_type->level != 1) {
798                                         rs->ti->error = "Cannot change device "
799                                                 "positions in RAID array";
800                                         return -EINVAL;
801                                 }
802                                 DMINFO("RAID1 device #%d now at position #%d",
803                                        role, r->raid_disk);
804                         }
805
806                         /*
807                          * Partial recovery is performed on
808                          * returning failed devices.
809                          */
810                         if (failed_devices & (1 << role))
811                                 set_bit(Faulty, &r->flags);
812                 }
813         }
814
815         return 0;
816 }
817
818 static int super_validate(struct mddev *mddev, struct md_rdev *rdev)
819 {
820         struct dm_raid_superblock *sb = page_address(rdev->sb_page);
821
822         /*
823          * If mddev->events is not set, we know we have not yet initialized
824          * the array.
825          */
826         if (!mddev->events && super_init_validation(mddev, rdev))
827                 return -EINVAL;
828
829         mddev->bitmap_info.offset = 4096 >> 9; /* Enable bitmap creation */
830         rdev->mddev->bitmap_info.default_offset = 4096 >> 9;
831         if (!test_bit(FirstUse, &rdev->flags)) {
832                 rdev->recovery_offset = le64_to_cpu(sb->disk_recovery_offset);
833                 if (rdev->recovery_offset != MaxSector)
834                         clear_bit(In_sync, &rdev->flags);
835         }
836
837         /*
838          * If a device comes back, set it as not In_sync and no longer faulty.
839          */
840         if (test_bit(Faulty, &rdev->flags)) {
841                 clear_bit(Faulty, &rdev->flags);
842                 clear_bit(In_sync, &rdev->flags);
843                 rdev->saved_raid_disk = rdev->raid_disk;
844                 rdev->recovery_offset = 0;
845         }
846
847         clear_bit(FirstUse, &rdev->flags);
848
849         return 0;
850 }
851
852 /*
853  * Analyse superblocks and select the freshest.
854  */
855 static int analyse_superblocks(struct dm_target *ti, struct raid_set *rs)
856 {
857         int ret;
858         unsigned redundancy = 0;
859         struct raid_dev *dev;
860         struct md_rdev *rdev, *tmp, *freshest;
861         struct mddev *mddev = &rs->md;
862
863         switch (rs->raid_type->level) {
864         case 1:
865                 redundancy = rs->md.raid_disks - 1;
866                 break;
867         case 4:
868         case 5:
869         case 6:
870                 redundancy = rs->raid_type->parity_devs;
871                 break;
872         default:
873                 ti->error = "Unknown RAID type";
874                 return -EINVAL;
875         }
876
877         freshest = NULL;
878         rdev_for_each_safe(rdev, tmp, mddev) {
879                 if (!rdev->meta_bdev)
880                         continue;
881
882                 ret = super_load(rdev, freshest);
883
884                 switch (ret) {
885                 case 1:
886                         freshest = rdev;
887                         break;
888                 case 0:
889                         break;
890                 default:
891                         dev = container_of(rdev, struct raid_dev, rdev);
892                         if (redundancy--) {
893                                 if (dev->meta_dev)
894                                         dm_put_device(ti, dev->meta_dev);
895
896                                 dev->meta_dev = NULL;
897                                 rdev->meta_bdev = NULL;
898
899                                 if (rdev->sb_page)
900                                         put_page(rdev->sb_page);
901
902                                 rdev->sb_page = NULL;
903
904                                 rdev->sb_loaded = 0;
905
906                                 /*
907                                  * We might be able to salvage the data device
908                                  * even though the meta device has failed.  For
909                                  * now, we behave as though '- -' had been
910                                  * set for this device in the table.
911                                  */
912                                 if (dev->data_dev)
913                                         dm_put_device(ti, dev->data_dev);
914
915                                 dev->data_dev = NULL;
916                                 rdev->bdev = NULL;
917
918                                 list_del(&rdev->same_set);
919
920                                 continue;
921                         }
922                         ti->error = "Failed to load superblock";
923                         return ret;
924                 }
925         }
926
927         if (!freshest)
928                 return 0;
929
930         /*
931          * Validation of the freshest device provides the source of
932          * validation for the remaining devices.
933          */
934         ti->error = "Unable to assemble array: Invalid superblocks";
935         if (super_validate(mddev, freshest))
936                 return -EINVAL;
937
938         rdev_for_each(rdev, mddev)
939                 if ((rdev != freshest) && super_validate(mddev, rdev))
940                         return -EINVAL;
941
942         return 0;
943 }
944
945 /*
946  * Construct a RAID4/5/6 mapping:
947  * Args:
948  *      <raid_type> <#raid_params> <raid_params>                \
949  *      <#raid_devs> { <meta_dev1> <dev1> .. <meta_devN> <devN> }
950  *
951  * <raid_params> varies by <raid_type>.  See 'parse_raid_params' for
952  * details on possible <raid_params>.
953  */
954 static int raid_ctr(struct dm_target *ti, unsigned argc, char **argv)
955 {
956         int ret;
957         struct raid_type *rt;
958         unsigned long num_raid_params, num_raid_devs;
959         struct raid_set *rs = NULL;
960
961         /* Must have at least <raid_type> <#raid_params> */
962         if (argc < 2) {
963                 ti->error = "Too few arguments";
964                 return -EINVAL;
965         }
966
967         /* raid type */
968         rt = get_raid_type(argv[0]);
969         if (!rt) {
970                 ti->error = "Unrecognised raid_type";
971                 return -EINVAL;
972         }
973         argc--;
974         argv++;
975
976         /* number of RAID parameters */
977         if (strict_strtoul(argv[0], 10, &num_raid_params) < 0) {
978                 ti->error = "Cannot understand number of RAID parameters";
979                 return -EINVAL;
980         }
981         argc--;
982         argv++;
983
984         /* Skip over RAID params for now and find out # of devices */
985         if (num_raid_params + 1 > argc) {
986                 ti->error = "Arguments do not agree with counts given";
987                 return -EINVAL;
988         }
989
990         if ((strict_strtoul(argv[num_raid_params], 10, &num_raid_devs) < 0) ||
991             (num_raid_devs >= INT_MAX)) {
992                 ti->error = "Cannot understand number of raid devices";
993                 return -EINVAL;
994         }
995
996         rs = context_alloc(ti, rt, (unsigned)num_raid_devs);
997         if (IS_ERR(rs))
998                 return PTR_ERR(rs);
999
1000         ret = parse_raid_params(rs, argv, (unsigned)num_raid_params);
1001         if (ret)
1002                 goto bad;
1003
1004         ret = -EINVAL;
1005
1006         argc -= num_raid_params + 1; /* +1: we already have num_raid_devs */
1007         argv += num_raid_params + 1;
1008
1009         if (argc != (num_raid_devs * 2)) {
1010                 ti->error = "Supplied RAID devices does not match the count given";
1011                 goto bad;
1012         }
1013
1014         ret = dev_parms(rs, argv);
1015         if (ret)
1016                 goto bad;
1017
1018         rs->md.sync_super = super_sync;
1019         ret = analyse_superblocks(ti, rs);
1020         if (ret)
1021                 goto bad;
1022
1023         INIT_WORK(&rs->md.event_work, do_table_event);
1024         ti->private = rs;
1025         ti->num_flush_requests = 1;
1026
1027         mutex_lock(&rs->md.reconfig_mutex);
1028         ret = md_run(&rs->md);
1029         rs->md.in_sync = 0; /* Assume already marked dirty */
1030         mutex_unlock(&rs->md.reconfig_mutex);
1031
1032         if (ret) {
1033                 ti->error = "Fail to run raid array";
1034                 goto bad;
1035         }
1036
1037         rs->callbacks.congested_fn = raid_is_congested;
1038         dm_table_add_target_callbacks(ti->table, &rs->callbacks);
1039
1040         mddev_suspend(&rs->md);
1041         return 0;
1042
1043 bad:
1044         context_free(rs);
1045
1046         return ret;
1047 }
1048
1049 static void raid_dtr(struct dm_target *ti)
1050 {
1051         struct raid_set *rs = ti->private;
1052
1053         list_del_init(&rs->callbacks.list);
1054         md_stop(&rs->md);
1055         context_free(rs);
1056 }
1057
1058 static int raid_map(struct dm_target *ti, struct bio *bio, union map_info *map_context)
1059 {
1060         struct raid_set *rs = ti->private;
1061         struct mddev *mddev = &rs->md;
1062
1063         mddev->pers->make_request(mddev, bio);
1064
1065         return DM_MAPIO_SUBMITTED;
1066 }
1067
1068 static int raid_status(struct dm_target *ti, status_type_t type,
1069                        char *result, unsigned maxlen)
1070 {
1071         struct raid_set *rs = ti->private;
1072         unsigned raid_param_cnt = 1; /* at least 1 for chunksize */
1073         unsigned sz = 0;
1074         int i, array_in_sync = 0;
1075         sector_t sync;
1076
1077         switch (type) {
1078         case STATUSTYPE_INFO:
1079                 DMEMIT("%s %d ", rs->raid_type->name, rs->md.raid_disks);
1080
1081                 if (test_bit(MD_RECOVERY_RUNNING, &rs->md.recovery))
1082                         sync = rs->md.curr_resync_completed;
1083                 else
1084                         sync = rs->md.recovery_cp;
1085
1086                 if (sync >= rs->md.resync_max_sectors) {
1087                         array_in_sync = 1;
1088                         sync = rs->md.resync_max_sectors;
1089                 } else {
1090                         /*
1091                          * The array may be doing an initial sync, or it may
1092                          * be rebuilding individual components.  If all the
1093                          * devices are In_sync, then it is the array that is
1094                          * being initialized.
1095                          */
1096                         for (i = 0; i < rs->md.raid_disks; i++)
1097                                 if (!test_bit(In_sync, &rs->dev[i].rdev.flags))
1098                                         array_in_sync = 1;
1099                 }
1100                 /*
1101                  * Status characters:
1102                  *  'D' = Dead/Failed device
1103                  *  'a' = Alive but not in-sync
1104                  *  'A' = Alive and in-sync
1105                  */
1106                 for (i = 0; i < rs->md.raid_disks; i++) {
1107                         if (test_bit(Faulty, &rs->dev[i].rdev.flags))
1108                                 DMEMIT("D");
1109                         else if (!array_in_sync ||
1110                                  !test_bit(In_sync, &rs->dev[i].rdev.flags))
1111                                 DMEMIT("a");
1112                         else
1113                                 DMEMIT("A");
1114                 }
1115
1116                 /*
1117                  * In-sync ratio:
1118                  *  The in-sync ratio shows the progress of:
1119                  *   - Initializing the array
1120                  *   - Rebuilding a subset of devices of the array
1121                  *  The user can distinguish between the two by referring
1122                  *  to the status characters.
1123                  */
1124                 DMEMIT(" %llu/%llu",
1125                        (unsigned long long) sync,
1126                        (unsigned long long) rs->md.resync_max_sectors);
1127
1128                 break;
1129         case STATUSTYPE_TABLE:
1130                 /* The string you would use to construct this array */
1131                 for (i = 0; i < rs->md.raid_disks; i++) {
1132                         if ((rs->print_flags & DMPF_REBUILD) &&
1133                             rs->dev[i].data_dev &&
1134                             !test_bit(In_sync, &rs->dev[i].rdev.flags))
1135                                 raid_param_cnt += 2; /* for rebuilds */
1136                         if (rs->dev[i].data_dev &&
1137                             test_bit(WriteMostly, &rs->dev[i].rdev.flags))
1138                                 raid_param_cnt += 2;
1139                 }
1140
1141                 raid_param_cnt += (hweight32(rs->print_flags & ~DMPF_REBUILD) * 2);
1142                 if (rs->print_flags & (DMPF_SYNC | DMPF_NOSYNC))
1143                         raid_param_cnt--;
1144
1145                 DMEMIT("%s %u %u", rs->raid_type->name,
1146                        raid_param_cnt, rs->md.chunk_sectors);
1147
1148                 if ((rs->print_flags & DMPF_SYNC) &&
1149                     (rs->md.recovery_cp == MaxSector))
1150                         DMEMIT(" sync");
1151                 if (rs->print_flags & DMPF_NOSYNC)
1152                         DMEMIT(" nosync");
1153
1154                 for (i = 0; i < rs->md.raid_disks; i++)
1155                         if ((rs->print_flags & DMPF_REBUILD) &&
1156                             rs->dev[i].data_dev &&
1157                             !test_bit(In_sync, &rs->dev[i].rdev.flags))
1158                                 DMEMIT(" rebuild %u", i);
1159
1160                 if (rs->print_flags & DMPF_DAEMON_SLEEP)
1161                         DMEMIT(" daemon_sleep %lu",
1162                                rs->md.bitmap_info.daemon_sleep);
1163
1164                 if (rs->print_flags & DMPF_MIN_RECOVERY_RATE)
1165                         DMEMIT(" min_recovery_rate %d", rs->md.sync_speed_min);
1166
1167                 if (rs->print_flags & DMPF_MAX_RECOVERY_RATE)
1168                         DMEMIT(" max_recovery_rate %d", rs->md.sync_speed_max);
1169
1170                 for (i = 0; i < rs->md.raid_disks; i++)
1171                         if (rs->dev[i].data_dev &&
1172                             test_bit(WriteMostly, &rs->dev[i].rdev.flags))
1173                                 DMEMIT(" write_mostly %u", i);
1174
1175                 if (rs->print_flags & DMPF_MAX_WRITE_BEHIND)
1176                         DMEMIT(" max_write_behind %lu",
1177                                rs->md.bitmap_info.max_write_behind);
1178
1179                 if (rs->print_flags & DMPF_STRIPE_CACHE) {
1180                         struct r5conf *conf = rs->md.private;
1181
1182                         /* convert from kiB to sectors */
1183                         DMEMIT(" stripe_cache %d",
1184                                conf ? conf->max_nr_stripes * 2 : 0);
1185                 }
1186
1187                 if (rs->print_flags & DMPF_REGION_SIZE)
1188                         DMEMIT(" region_size %lu",
1189                                rs->md.bitmap_info.chunksize >> 9);
1190
1191                 DMEMIT(" %d", rs->md.raid_disks);
1192                 for (i = 0; i < rs->md.raid_disks; i++) {
1193                         if (rs->dev[i].meta_dev)
1194                                 DMEMIT(" %s", rs->dev[i].meta_dev->name);
1195                         else
1196                                 DMEMIT(" -");
1197
1198                         if (rs->dev[i].data_dev)
1199                                 DMEMIT(" %s", rs->dev[i].data_dev->name);
1200                         else
1201                                 DMEMIT(" -");
1202                 }
1203         }
1204
1205         return 0;
1206 }
1207
1208 static int raid_iterate_devices(struct dm_target *ti, iterate_devices_callout_fn fn, void *data)
1209 {
1210         struct raid_set *rs = ti->private;
1211         unsigned i;
1212         int ret = 0;
1213
1214         for (i = 0; !ret && i < rs->md.raid_disks; i++)
1215                 if (rs->dev[i].data_dev)
1216                         ret = fn(ti,
1217                                  rs->dev[i].data_dev,
1218                                  0, /* No offset on data devs */
1219                                  rs->md.dev_sectors,
1220                                  data);
1221
1222         return ret;
1223 }
1224
1225 static void raid_io_hints(struct dm_target *ti, struct queue_limits *limits)
1226 {
1227         struct raid_set *rs = ti->private;
1228         unsigned chunk_size = rs->md.chunk_sectors << 9;
1229         struct r5conf *conf = rs->md.private;
1230
1231         blk_limits_io_min(limits, chunk_size);
1232         blk_limits_io_opt(limits, chunk_size * (conf->raid_disks - conf->max_degraded));
1233 }
1234
1235 static void raid_presuspend(struct dm_target *ti)
1236 {
1237         struct raid_set *rs = ti->private;
1238
1239         md_stop_writes(&rs->md);
1240 }
1241
1242 static void raid_postsuspend(struct dm_target *ti)
1243 {
1244         struct raid_set *rs = ti->private;
1245
1246         mddev_suspend(&rs->md);
1247 }
1248
1249 static void raid_resume(struct dm_target *ti)
1250 {
1251         struct raid_set *rs = ti->private;
1252
1253         set_bit(MD_CHANGE_DEVS, &rs->md.flags);
1254         if (!rs->bitmap_loaded) {
1255                 bitmap_load(&rs->md);
1256                 rs->bitmap_loaded = 1;
1257         }
1258
1259         clear_bit(MD_RECOVERY_FROZEN, &rs->md.recovery);
1260         mddev_resume(&rs->md);
1261 }
1262
1263 static struct target_type raid_target = {
1264         .name = "raid",
1265         .version = {1, 2, 0},
1266         .module = THIS_MODULE,
1267         .ctr = raid_ctr,
1268         .dtr = raid_dtr,
1269         .map = raid_map,
1270         .status = raid_status,
1271         .iterate_devices = raid_iterate_devices,
1272         .io_hints = raid_io_hints,
1273         .presuspend = raid_presuspend,
1274         .postsuspend = raid_postsuspend,
1275         .resume = raid_resume,
1276 };
1277
1278 static int __init dm_raid_init(void)
1279 {
1280         return dm_register_target(&raid_target);
1281 }
1282
1283 static void __exit dm_raid_exit(void)
1284 {
1285         dm_unregister_target(&raid_target);
1286 }
1287
1288 module_init(dm_raid_init);
1289 module_exit(dm_raid_exit);
1290
1291 MODULE_DESCRIPTION(DM_NAME " raid4/5/6 target");
1292 MODULE_ALIAS("dm-raid4");
1293 MODULE_ALIAS("dm-raid5");
1294 MODULE_ALIAS("dm-raid6");
1295 MODULE_AUTHOR("Neil Brown <dm-devel@redhat.com>");
1296 MODULE_LICENSE("GPL");