eb963df3503815f558c14c304489301395e1f5d2
[thirdparty/mdadm.git] / super-intel.c
1 /*
2  * mdadm - Intel(R) Matrix Storage Manager Support
3  *
4  * Copyright (C) 2002-2007 Intel Corporation
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms and conditions of the GNU General Public License,
8  * version 2, as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 #include "mdadm.h"
21 #include "mdmon.h"
22 #include <values.h>
23 #include <scsi/sg.h>
24 #include <ctype.h>
25
26 /* MPB == Metadata Parameter Block */
27 #define MPB_SIGNATURE "Intel Raid ISM Cfg Sig. "
28 #define MPB_SIG_LEN (strlen(MPB_SIGNATURE))
29 #define MPB_VERSION_RAID0 "1.0.00"
30 #define MPB_VERSION_RAID1 "1.1.00"
31 #define MPB_VERSION_RAID5 "1.2.02"
32 #define MAX_SIGNATURE_LENGTH  32
33 #define MAX_RAID_SERIAL_LEN   16
34 #define MPB_SECTOR_CNT 418
35 #define IMSM_RESERVED_SECTORS 4096
36
37 /* Disk configuration info. */
38 #define IMSM_MAX_DEVICES 255
39 struct imsm_disk {
40         __u8 serial[MAX_RAID_SERIAL_LEN];/* 0xD8 - 0xE7 ascii serial number */
41         __u32 total_blocks;              /* 0xE8 - 0xEB total blocks */
42         __u32 scsi_id;                   /* 0xEC - 0xEF scsi ID */
43         __u32 status;                    /* 0xF0 - 0xF3 */
44 #define SPARE_DISK      0x01  /* Spare */
45 #define CONFIGURED_DISK 0x02  /* Member of some RaidDev */
46 #define FAILED_DISK     0x04  /* Permanent failure */
47 #define USABLE_DISK     0x08  /* Fully usable unless FAILED_DISK is set */
48
49 #define IMSM_DISK_FILLERS       5
50         __u32 filler[IMSM_DISK_FILLERS]; /* 0xF4 - 0x107 MPB_DISK_FILLERS for future expansion */
51 };
52
53 /* RAID map configuration infos. */
54 struct imsm_map {
55         __u32 pba_of_lba0;      /* start address of partition */
56         __u32 blocks_per_member;/* blocks per member */
57         __u32 num_data_stripes; /* number of data stripes */
58         __u16 blocks_per_strip;
59         __u8  map_state;        /* Normal, Uninitialized, Degraded, Failed */
60 #define IMSM_T_STATE_NORMAL 0
61 #define IMSM_T_STATE_UNINITIALIZED 1
62 #define IMSM_T_STATE_DEGRADED 2 /* FIXME: is this correct? */
63 #define IMSM_T_STATE_FAILED 3 /* FIXME: is this correct? */
64         __u8  raid_level;
65 #define IMSM_T_RAID0 0
66 #define IMSM_T_RAID1 1
67 #define IMSM_T_RAID5 5          /* since metadata version 1.2.02 ? */
68         __u8  num_members;      /* number of member disks */
69         __u8  reserved[3];
70         __u32 filler[7];        /* expansion area */
71         __u32 disk_ord_tbl[1];  /* disk_ord_tbl[num_members],
72                                    top byte special */
73 } __attribute__ ((packed));
74
75 struct imsm_vol {
76         __u32 reserved[2];
77         __u8  migr_state;       /* Normal or Migrating */
78         __u8  migr_type;        /* Initializing, Rebuilding, ... */
79         __u8  dirty;
80         __u8  fill[1];
81         __u32 filler[5];
82         struct imsm_map map[1];
83         /* here comes another one if migr_state */
84 } __attribute__ ((packed));
85
86 struct imsm_dev {
87         __u8    volume[MAX_RAID_SERIAL_LEN];
88         __u32 size_low;
89         __u32 size_high;
90         __u32 status;   /* Persistent RaidDev status */
91         __u32 reserved_blocks; /* Reserved blocks at beginning of volume */
92 #define IMSM_DEV_FILLERS 12
93         __u32 filler[IMSM_DEV_FILLERS];
94         struct imsm_vol vol;
95 } __attribute__ ((packed));
96
97 struct imsm_super {
98         __u8 sig[MAX_SIGNATURE_LENGTH]; /* 0x00 - 0x1F */
99         __u32 check_sum;                /* 0x20 - 0x23 MPB Checksum */
100         __u32 mpb_size;                 /* 0x24 - 0x27 Size of MPB */
101         __u32 family_num;               /* 0x28 - 0x2B Checksum from first time this config was written */
102         __u32 generation_num;           /* 0x2C - 0x2F Incremented each time this array's MPB is written */
103         __u32 reserved[2];              /* 0x30 - 0x37 */
104         __u8 num_disks;                 /* 0x38 Number of configured disks */
105         __u8 num_raid_devs;             /* 0x39 Number of configured volumes */
106         __u8 fill[2];                   /* 0x3A - 0x3B */
107 #define IMSM_FILLERS 39
108         __u32 filler[IMSM_FILLERS];     /* 0x3C - 0xD7 RAID_MPB_FILLERS */
109         struct imsm_disk disk[1];       /* 0xD8 diskTbl[numDisks] */
110         /* here comes imsm_dev[num_raid_devs] */
111 } __attribute__ ((packed));
112
113 #ifndef MDASSEMBLE
114 static char *map_state_str[] = { "normal", "uninitialized", "degraded", "failed" };
115 #endif
116
117 static unsigned int sector_count(__u32 bytes)
118 {
119         return ((bytes + (512-1)) & (~(512-1))) / 512;
120 }
121
122 static unsigned int mpb_sectors(struct imsm_super *mpb)
123 {
124         return sector_count(__le32_to_cpu(mpb->mpb_size));
125 }
126
127 static struct superswitch super_imsm_volume;
128
129 /* internal representation of IMSM metadata */
130 struct intel_super {
131         union {
132                 struct imsm_super *mpb;
133                 void *buf;
134         };
135         int updates_pending; /* count of pending updates for mdmon */
136         int creating_imsm; /* flag to indicate container creation */
137         int creating_dev; /* index of raid device undergoing creation */
138         struct dl {
139                 struct dl *next;
140                 int index;
141                 __u8 serial[MAX_RAID_SERIAL_LEN];
142                 int major, minor;
143                 char *devname;
144                 int fd;
145         } *disks;
146 };
147
148 struct extent {
149         unsigned long long start, size;
150 };
151
152 static struct supertype *match_metadata_desc_imsm(char *arg)
153 {
154         struct supertype *st;
155
156         if (strcmp(arg, "imsm") != 0 &&
157             strcmp(arg, "default") != 0
158                 )
159                 return NULL;
160
161         st = malloc(sizeof(*st));
162         memset(st, 0, sizeof(*st));
163         st->ss = &super_imsm;
164         st->max_devs = IMSM_MAX_DEVICES;
165         st->minor_version = 0;
166         st->sb = NULL;
167         return st;
168 }
169
170 static struct supertype *match_metadata_desc_imsm_volume(char *arg)
171 {
172         struct supertype *st;
173
174         if (strcmp(arg, "imsm/volume") != 0 &&
175             strcmp(arg, "raid") != 0 &&
176             strcmp(arg, "default") != 0
177                 )
178                 return NULL;
179
180         st = malloc(sizeof(*st));
181         memset(st, 0, sizeof(*st));
182         st->ss = &super_imsm_volume;
183         st->max_devs = IMSM_MAX_DEVICES;
184         st->minor_version = 0;
185         st->sb = NULL;
186         return st;
187 }
188
189 static __u8 *get_imsm_version(struct imsm_super *mpb)
190 {
191         return &mpb->sig[MPB_SIG_LEN];
192 }
193
194 static struct imsm_disk *get_imsm_disk(struct imsm_super *mpb, __u8 index)
195 {
196         if (index > mpb->num_disks - 1)
197                 return NULL;
198         return &mpb->disk[index];
199 }
200
201 static __u32 gen_imsm_checksum(struct imsm_super *mpb)
202 {
203         __u32 end = mpb->mpb_size / sizeof(end);
204         __u32 *p = (__u32 *) mpb;
205         __u32 sum = 0;
206
207         while (end--)
208                 sum += __le32_to_cpu(*p++);
209
210         return sum - __le32_to_cpu(mpb->check_sum);
211 }
212
213 static size_t sizeof_imsm_dev(struct imsm_dev *dev)
214 {
215         size_t size = sizeof(*dev);
216
217         /* each map has disk_ord_tbl[num_members - 1] additional space */
218         size += sizeof(__u32) * (dev->vol.map[0].num_members - 1);
219
220         /* migrating means an additional map */
221         if (dev->vol.migr_state) {
222                 size += sizeof(struct imsm_map);
223                 size += sizeof(__u32) * (dev->vol.map[1].num_members - 1);
224         }
225
226         return size;
227 }
228
229 static struct imsm_dev *get_imsm_dev(struct imsm_super *mpb, __u8 index)
230 {
231         int offset;
232         int i;
233         void *_mpb = mpb;
234
235         if (index > mpb->num_raid_devs - 1)
236                 return NULL;
237
238         /* devices start after all disks */
239         offset = ((void *) &mpb->disk[mpb->num_disks]) - _mpb;
240
241         for (i = 0; i <= index; i++)
242                 if (i == index)
243                         return _mpb + offset;
244                 else
245                         offset += sizeof_imsm_dev(_mpb + offset);
246
247         return NULL;
248 }
249
250 static __u32 get_imsm_disk_idx(struct imsm_map *map, int slot)
251 {
252         __u32 *ord_tbl = &map->disk_ord_tbl[slot];
253
254         /* top byte is 'special' */
255         return __le32_to_cpu(*ord_tbl & ~(0xff << 24));
256 }
257
258 static int get_imsm_raid_level(struct imsm_map *map)
259 {
260         if (map->raid_level == 1) {
261                 if (map->num_members == 2)
262                         return 1;
263                 else
264                         return 10;
265         }
266
267         return map->raid_level;
268 }
269
270 static int cmp_extent(const void *av, const void *bv)
271 {
272         const struct extent *a = av;
273         const struct extent *b = bv;
274         if (a->start < b->start)
275                 return -1;
276         if (a->start > b->start)
277                 return 1;
278         return 0;
279 }
280
281 static struct extent *get_extents(struct intel_super *super, struct dl *dl)
282 {
283         /* find a list of used extents on the given physical device */
284         struct imsm_super *mpb = super->mpb;
285         struct imsm_disk *disk;
286         struct extent *rv, *e;
287         int i, j;
288         int memberships = 0;
289
290         disk = get_imsm_disk(mpb, dl->index);
291         if (!disk)
292                 return NULL;
293
294         for (i = 0; i < mpb->num_raid_devs; i++) {
295                 struct imsm_dev *dev = get_imsm_dev(mpb, i);
296                 struct imsm_map *map = dev->vol.map;
297
298                 for (j = 0; j < map->num_members; j++) {
299                         __u32 index = get_imsm_disk_idx(map, j);
300
301                         if (index == dl->index)
302                                 memberships++;
303                 }
304         }
305         rv = malloc(sizeof(struct extent) * (memberships + 1));
306         if (!rv)
307                 return NULL;
308         e = rv;
309
310         for (i = 0; i < mpb->num_raid_devs; i++) {
311                 struct imsm_dev *dev = get_imsm_dev(mpb, i);
312                 struct imsm_map *map = dev->vol.map;
313
314                 for (j = 0; j < map->num_members; j++) {
315                         __u32 index = get_imsm_disk_idx(map, j);
316
317                         if (index == dl->index) {
318                                 e->start = __le32_to_cpu(map->pba_of_lba0);
319                                 e->size = __le32_to_cpu(map->blocks_per_member);
320                                 e++;
321                         }
322                 }
323         }
324         qsort(rv, memberships, sizeof(*rv), cmp_extent);
325
326         e->start = __le32_to_cpu(disk->total_blocks) -
327                    (MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS);
328         e->size = 0;
329         return rv;
330 }
331
332 #ifndef MDASSEMBLE
333 static void print_imsm_dev(struct imsm_dev *dev, int index)
334 {
335         __u64 sz;
336         int slot;
337         struct imsm_map *map = dev->vol.map;
338
339         printf("\n");
340         printf("[%s]:\n", dev->volume);
341         printf("     RAID Level : %d\n", get_imsm_raid_level(map));
342         printf("        Members : %d\n", map->num_members);
343         for (slot = 0; slot < map->num_members; slot++)
344                 if (index == get_imsm_disk_idx(map, slot))
345                         break;
346         if (slot < map->num_members)
347                 printf("      This Slot : %d\n", slot);
348         else
349                 printf("      This Slot : ?\n");
350         sz = __le32_to_cpu(dev->size_high);
351         sz <<= 32;
352         sz += __le32_to_cpu(dev->size_low);
353         printf("     Array Size : %llu%s\n", (unsigned long long)sz,
354                human_size(sz * 512));
355         sz = __le32_to_cpu(map->blocks_per_member);
356         printf("   Per Dev Size : %llu%s\n", (unsigned long long)sz,
357                human_size(sz * 512));
358         printf("  Sector Offset : %u\n",
359                 __le32_to_cpu(map->pba_of_lba0));
360         printf("    Num Stripes : %u\n",
361                 __le32_to_cpu(map->num_data_stripes));
362         printf("     Chunk Size : %u KiB\n",
363                 __le16_to_cpu(map->blocks_per_strip) / 2);
364         printf("       Reserved : %d\n", __le32_to_cpu(dev->reserved_blocks));
365         printf("  Migrate State : %s\n", dev->vol.migr_state ? "migrating" : "idle");
366         printf("    Dirty State : %s\n", dev->vol.dirty ? "dirty" : "clean");
367         printf("      Map State : %s\n", map_state_str[map->map_state]);
368 }
369
370 static void print_imsm_disk(struct imsm_super *mpb, int index)
371 {
372         struct imsm_disk *disk = get_imsm_disk(mpb, index);
373         char str[MAX_RAID_SERIAL_LEN];
374         __u32 s;
375         __u64 sz;
376
377         printf("\n");
378         snprintf(str, MAX_RAID_SERIAL_LEN, "%s", disk->serial);
379         printf("  Disk%02d Serial : %s\n", index, str);
380         s = __le32_to_cpu(disk->status);
381         printf("          State :%s%s%s%s\n", s&SPARE_DISK ? " spare" : "",
382                                               s&CONFIGURED_DISK ? " active" : "",
383                                               s&FAILED_DISK ? " failed" : "",
384                                               s&USABLE_DISK ? " usable" : "");
385         printf("             Id : %08x\n", __le32_to_cpu(disk->scsi_id));
386         sz = __le32_to_cpu(disk->total_blocks) -
387              (MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS * mpb->num_raid_devs);
388         printf("    Usable Size : %llu%s\n", (unsigned long long)sz,
389                human_size(sz * 512));
390 }
391
392 static void examine_super_imsm(struct supertype *st, char *homehost)
393 {
394         struct intel_super *super = st->sb;
395         struct imsm_super *mpb = super->mpb;
396         char str[MAX_SIGNATURE_LENGTH];
397         int i;
398         __u32 sum;
399
400         snprintf(str, MPB_SIG_LEN, "%s", mpb->sig);
401         printf("          Magic : %s\n", str);
402         snprintf(str, strlen(MPB_VERSION_RAID0), "%s", get_imsm_version(mpb));
403         printf("        Version : %s\n", get_imsm_version(mpb));
404         printf("         Family : %08x\n", __le32_to_cpu(mpb->family_num));
405         printf("     Generation : %08x\n", __le32_to_cpu(mpb->generation_num));
406         sum = __le32_to_cpu(mpb->check_sum);
407         printf("       Checksum : %08x %s\n", sum,
408                 gen_imsm_checksum(mpb) == sum ? "correct" : "incorrect");
409         printf("    MPB Sectors : %d\n", mpb_sectors(mpb));
410         printf("          Disks : %d\n", mpb->num_disks);
411         printf("   RAID Devices : %d\n", mpb->num_raid_devs);
412         print_imsm_disk(mpb, super->disks->index);
413         for (i = 0; i < mpb->num_raid_devs; i++)
414                 print_imsm_dev(get_imsm_dev(mpb, i), super->disks->index);
415         for (i = 0; i < mpb->num_disks; i++) {
416                 if (i == super->disks->index)
417                         continue;
418                 print_imsm_disk(mpb, i);
419         }
420 }
421
422 static void brief_examine_super_imsm(struct supertype *st)
423 {
424         struct intel_super *super = st->sb;
425         struct imsm_super *mpb = super->mpb;
426
427         printf("ARRAY /dev/imsm family=%08x metadata=external:imsm\n",
428                 __le32_to_cpu(mpb->family_num));
429 }
430
431 static void detail_super_imsm(struct supertype *st, char *homehost)
432 {
433         printf("%s\n", __FUNCTION__);
434 }
435
436 static void brief_detail_super_imsm(struct supertype *st)
437 {
438         printf("%s\n", __FUNCTION__);
439 }
440 #endif
441
442 static int match_home_imsm(struct supertype *st, char *homehost)
443 {
444         printf("%s\n", __FUNCTION__);
445
446         return 0;
447 }
448
449 static void uuid_from_super_imsm(struct supertype *st, int uuid[4])
450 {
451         printf("%s\n", __FUNCTION__);
452 }
453
454 #if 0
455 static void
456 get_imsm_numerical_version(struct imsm_super *mpb, int *m, int *p)
457 {
458         __u8 *v = get_imsm_version(mpb);
459         __u8 *end = mpb->sig + MAX_SIGNATURE_LENGTH;
460         char major[] = { 0, 0, 0 };
461         char minor[] = { 0 ,0, 0 };
462         char patch[] = { 0, 0, 0 };
463         char *ver_parse[] = { major, minor, patch };
464         int i, j;
465
466         i = j = 0;
467         while (*v != '\0' && v < end) {
468                 if (*v != '.' && j < 2)
469                         ver_parse[i][j++] = *v;
470                 else {
471                         i++;
472                         j = 0;
473                 }
474                 v++;
475         }
476
477         *m = strtol(minor, NULL, 0);
478         *p = strtol(patch, NULL, 0);
479 }
480 #endif
481
482 static int imsm_level_to_layout(int level)
483 {
484         switch (level) {
485         case 0:
486         case 1:
487                 return 0;
488         case 5:
489         case 6:
490                 return ALGORITHM_LEFT_SYMMETRIC;
491         case 10:
492                 return 0x102; //FIXME is this correct?
493         }
494         return -1;
495 }
496
497 static void getinfo_super_imsm(struct supertype *st, struct mdinfo *info)
498 {
499         struct intel_super *super = st->sb;
500         struct imsm_super *mpb = super->mpb;
501         struct imsm_disk *disk;
502         __u32 s;
503
504         info->array.raid_disks    = mpb->num_disks;
505         info->array.level         = LEVEL_CONTAINER;
506         info->array.layout        = 0;
507         info->array.md_minor      = -1;
508         info->array.ctime         = 0; /* N/A for imsm */ 
509         info->array.utime         = 0;
510         info->array.chunk_size    = 0;
511
512         info->disk.major = 0;
513         info->disk.minor = 0;
514         info->disk.raid_disk = -1;
515         info->reshape_active = 0;
516         strcpy(info->text_version, "imsm");
517         info->disk.number = -1;
518         info->disk.state = 0;
519
520         if (super->disks) {
521                 info->disk.number = super->disks->index;
522                 info->disk.raid_disk = super->disks->index;
523                 disk = get_imsm_disk(mpb, super->disks->index);
524                 s = __le32_to_cpu(disk->status);
525                 info->disk.state  = s & CONFIGURED_DISK ? (1 << MD_DISK_ACTIVE) : 0;
526                 info->disk.state |= s & FAILED_DISK ? (1 << MD_DISK_FAULTY) : 0;
527                 info->disk.state |= s & USABLE_DISK ? (1 << MD_DISK_SYNC) : 0;
528         }
529 }
530
531 static void getinfo_super_imsm_volume(struct supertype *st, struct mdinfo *info)
532 {
533         struct intel_super *super = st->sb;
534         struct imsm_super *mpb = super->mpb;
535         struct imsm_dev *dev = get_imsm_dev(mpb, info->container_member);
536         struct imsm_map *map = &dev->vol.map[0];
537
538         info->array.raid_disks    = map->num_members;
539         info->array.level         = get_imsm_raid_level(map);
540         info->array.layout        = imsm_level_to_layout(info->array.level);
541         info->array.md_minor      = -1;
542         info->array.ctime         = 0;
543         info->array.utime         = 0;
544         info->array.chunk_size    = __le16_to_cpu(map->blocks_per_strip * 512);
545
546         info->data_offset         = __le32_to_cpu(map->pba_of_lba0);
547         info->component_size      = __le32_to_cpu(map->blocks_per_member);
548
549         info->disk.major = 0;
550         info->disk.minor = 0;
551
552         sprintf(info->text_version, "/%s/%d",
553                 devnum2devname(st->container_dev),
554                 info->container_member);
555 }
556
557 static int update_super_imsm(struct supertype *st, struct mdinfo *info,
558                              char *update, char *devname, int verbose,
559                              int uuid_set, char *homehost)
560 {
561         /* FIXME */
562
563         /* For 'assemble' and 'force' we need to return non-zero if any
564          * change was made.  For others, the return value is ignored.
565          * Update options are:
566          *  force-one : This device looks a bit old but needs to be included,
567          *        update age info appropriately.
568          *  assemble: clear any 'faulty' flag to allow this device to
569          *              be assembled.
570          *  force-array: Array is degraded but being forced, mark it clean
571          *         if that will be needed to assemble it.
572          *
573          *  newdev:  not used ????
574          *  grow:  Array has gained a new device - this is currently for
575          *              linear only
576          *  resync: mark as dirty so a resync will happen.
577          *  name:  update the name - preserving the homehost
578          *
579          * Following are not relevant for this imsm:
580          *  sparc2.2 : update from old dodgey metadata
581          *  super-minor: change the preferred_minor number
582          *  summaries:  update redundant counters.
583          *  uuid:  Change the uuid of the array to match watch is given
584          *  homehost:  update the recorded homehost
585          *  _reshape_progress: record new reshape_progress position.
586          */
587         int rv = 0;
588         //struct intel_super *super = st->sb;
589         //struct imsm_super *mpb = super->mpb;
590
591         if (strcmp(update, "grow") == 0) {
592         }
593         if (strcmp(update, "resync") == 0) {
594                 /* dev->vol.dirty = 1; */
595         }
596
597         /* IMSM has no concept of UUID or homehost */
598
599         return rv;
600 }
601
602 static size_t disks_to_mpb_size(int disks)
603 {
604         size_t size;
605
606         size = sizeof(struct imsm_super);
607         size += (disks - 1) * sizeof(struct imsm_disk);
608         size += 2 * sizeof(struct imsm_dev);
609         /* up to 2 maps per raid device (-2 for imsm_maps in imsm_dev */
610         size += (4 - 2) * sizeof(struct imsm_map);
611         /* 4 possible disk_ord_tbl's */
612         size += 4 * (disks - 1) * sizeof(__u32);
613
614         return size;
615 }
616
617 static __u64 avail_size_imsm(struct supertype *st, __u64 devsize)
618 {
619         if (devsize < (MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS))
620                 return 0;
621
622         return devsize - (MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS);
623 }
624
625 static int compare_super_imsm(struct supertype *st, struct supertype *tst)
626 {
627         /*
628          * return:
629          *  0 same, or first was empty, and second was copied
630          *  1 second had wrong number
631          *  2 wrong uuid
632          *  3 wrong other info
633          */
634         struct intel_super *first = st->sb;
635         struct intel_super *sec = tst->sb;
636
637         if (!first) {
638                 st->sb = tst->sb;
639                 tst->sb = NULL;
640                 return 0;
641         }
642
643         if (memcmp(first->mpb->sig, sec->mpb->sig, MAX_SIGNATURE_LENGTH) != 0)
644                 return 3;
645         if (first->mpb->family_num != sec->mpb->family_num)
646                 return 3;
647         if (first->mpb->mpb_size != sec->mpb->mpb_size)
648                 return 3;
649         if (first->mpb->check_sum != sec->mpb->check_sum)
650                 return 3;
651
652         return 0;
653 }
654
655 extern int scsi_get_serial(int fd, void *buf, size_t buf_len);
656
657 static int imsm_read_serial(int fd, char *devname,
658                             __u8 serial[MAX_RAID_SERIAL_LEN])
659 {
660         unsigned char scsi_serial[255];
661         int sg_fd;
662         int rv;
663         int rsp_len;
664         int i, cnt;
665
666         memset(scsi_serial, 0, sizeof(scsi_serial));
667
668         sg_fd = sysfs_disk_to_sg(fd);
669         if (sg_fd < 0) {
670                 if (devname)
671                         fprintf(stderr,
672                                 Name ": Failed to open sg interface for %s: %s\n",
673                                 devname, strerror(errno));
674                 return 1;
675         }
676
677         rv = scsi_get_serial(sg_fd, scsi_serial, sizeof(scsi_serial));
678         close(sg_fd);
679
680         if (rv != 0) {
681                 if (devname)
682                         fprintf(stderr,
683                                 Name ": Failed to retrieve serial for %s\n",
684                                 devname);
685                 return rv;
686         }
687
688         rsp_len = scsi_serial[3];
689         for (i = 0, cnt = 0; i < rsp_len; i++) {
690                 if (!isspace(scsi_serial[4 + i]))
691                         serial[cnt++] = scsi_serial[4 + i];
692                 if (cnt == MAX_RAID_SERIAL_LEN)
693                         break;
694         }
695
696         serial[MAX_RAID_SERIAL_LEN - 1] = '\0';
697
698         return 0;
699 }
700
701 static int
702 load_imsm_disk(int fd, struct intel_super *super, char *devname, int keep_fd)
703 {
704         struct imsm_super *mpb = super->mpb;
705         struct dl *dl;
706         struct stat stb;
707         struct imsm_disk *disk;
708         int rv;
709         int i;
710
711         dl = malloc(sizeof(*dl));
712         if (!dl) {
713                 if (devname)
714                         fprintf(stderr,
715                                 Name ": failed to allocate disk buffer for %s\n",
716                                 devname);
717                 return 2;
718         }
719         memset(dl, 0, sizeof(*dl));
720
721         fstat(fd, &stb);
722         dl->major = major(stb.st_rdev);
723         dl->minor = minor(stb.st_rdev);
724         dl->next = super->disks;
725         dl->fd = keep_fd ? fd : -1;
726         dl->devname = devname ? strdup(devname) : NULL;
727         dl->index = -1;
728         super->disks = dl;
729         rv = imsm_read_serial(fd, devname, dl->serial);
730
731         if (rv != 0)
732                 return 2;
733
734         /* look up this disk's index */
735         for (i = 0; i < mpb->num_disks; i++) {
736                 disk = get_imsm_disk(mpb, i);
737
738                 if (memcmp(disk->serial, dl->serial, MAX_RAID_SERIAL_LEN) == 0)
739                         break;
740         }
741
742         if (i > mpb->num_disks)
743                 return 2;
744
745         dl->index = i;
746
747         return 0;
748 }
749
750 /* load_imsm_mpb - read matrix metadata
751  * allocates super->mpb to be freed by free_super
752  */
753 static int load_imsm_mpb(int fd, struct intel_super *super, char *devname)
754 {
755         unsigned long long dsize;
756         size_t len, mpb_size;
757         unsigned long long sectors;
758         struct stat;
759         struct imsm_super anchor;
760         __u32 check_sum;
761
762         memset(super, 0, sizeof(*super));
763         get_dev_size(fd, NULL, &dsize);
764
765         if (lseek64(fd, dsize - (512 * 2), SEEK_SET) < 0) {
766                 if (devname)
767                         fprintf(stderr,
768                                 Name ": Cannot seek to anchor block on %s: %s\n",
769                                 devname, strerror(errno));
770                 return 1;
771         }
772
773         len = sizeof(anchor);
774         if (read(fd, &anchor, len) != len) {
775                 if (devname)
776                         fprintf(stderr,
777                                 Name ": Cannot read anchor block on %s: %s\n",
778                                 devname, strerror(errno));
779                 return 1;
780         }
781
782         if (strncmp((char *) anchor.sig, MPB_SIGNATURE, MPB_SIG_LEN) != 0) {
783                 if (devname)
784                         fprintf(stderr,
785                                 Name ": no IMSM anchor on %s\n", devname);
786                 return 2;
787         }
788
789         mpb_size = __le32_to_cpu(anchor.mpb_size);
790         super->mpb = malloc(mpb_size < 512 ? 512 : mpb_size);
791         if (!super->mpb) {
792                 if (devname)
793                         fprintf(stderr,
794                                 Name ": unable to allocate %zu byte mpb buffer\n",
795                                 mpb_size);
796                 return 2;
797         }
798         memcpy(super->buf, &anchor, sizeof(anchor));
799
800         /* read the rest of the first block */
801         len = 512 - sizeof(anchor);
802         if (read(fd, super->buf + sizeof(anchor), len) != len) {
803                 if (devname)
804                         fprintf(stderr,
805                                 Name ": Cannot read anchor remainder on %s: %s\n",
806                                 devname, strerror(errno));
807                 return 2;
808         }
809
810         sectors = mpb_sectors(&anchor) - 1;
811         if (!sectors)
812                 return load_imsm_disk(fd, super, devname, 0);
813
814         /* read the extended mpb */
815         if (lseek64(fd, dsize - (512 * (2 + sectors)), SEEK_SET) < 0) {
816                 if (devname)
817                         fprintf(stderr,
818                                 Name ": Cannot seek to extended mpb on %s: %s\n",
819                                 devname, strerror(errno));
820                 return 1;
821         }
822
823         len = mpb_size - 512;
824         if (read(fd, super->buf + 512, len) != len) {
825                 if (devname)
826                         fprintf(stderr,
827                                 Name ": Cannot read extended mpb on %s: %s\n",
828                                 devname, strerror(errno));
829                 return 2;
830         }
831
832         check_sum = gen_imsm_checksum(super->mpb);
833         if (check_sum != __le32_to_cpu(super->mpb->check_sum)) {
834                 if (devname)
835                         fprintf(stderr,
836                                 Name ": IMSM checksum %x != %x on %s\n",
837                                 check_sum, __le32_to_cpu(super->mpb->check_sum),
838                                 devname);
839                 return 2;
840         }
841
842         return load_imsm_disk(fd, super, devname, 0);
843 }
844
845 struct superswitch super_imsm_container;
846
847 static void free_imsm_disks(struct intel_super *super)
848 {
849         while (super->disks) {
850                 struct dl *d = super->disks;
851
852                 super->disks = d->next;
853                 if (d->fd >= 0)
854                         close(d->fd);
855                 if (d->devname)
856                         free(d->devname);
857                 free(d);
858         }
859 }
860
861 static void free_imsm(struct intel_super *super)
862 {
863         if (super->mpb)
864                 free(super->mpb);
865         free_imsm_disks(super);
866         free(super);
867 }
868
869
870 static void free_super_imsm(struct supertype *st)
871 {
872         struct intel_super *super = st->sb;
873
874         if (!super)
875                 return;
876
877         free_imsm(super);
878         st->sb = NULL;
879 }
880
881 static struct intel_super *alloc_super(int creating_imsm)
882 {
883         struct intel_super *super = malloc(sizeof(*super));
884
885         if (super) {
886                 memset(super, 0, sizeof(*super));
887                 super->creating_imsm = creating_imsm;
888                 super->creating_dev = -1;
889         }
890
891         return super;
892 }
893
894 #ifndef MDASSEMBLE
895 static int load_super_imsm_all(struct supertype *st, int fd, void **sbp,
896                                char *devname, int keep_fd)
897 {
898         struct mdinfo *sra;
899         struct intel_super *super;
900         struct mdinfo *sd, *best = NULL;
901         __u32 bestgen = 0;
902         __u32 gen;
903         char nm[20];
904         int dfd;
905         int rv;
906
907         /* check if this disk is a member of an active array */
908         sra = sysfs_read(fd, 0, GET_LEVEL|GET_VERSION|GET_DEVS|GET_STATE);
909         if (!sra)
910                 return 1;
911
912         if (sra->array.major_version != -1 ||
913             sra->array.minor_version != -2 ||
914             strcmp(sra->text_version, "imsm") != 0)
915                 return 1;
916
917         super = alloc_super(0);
918         if (!super)
919                 return 1;
920
921         /* find the most up to date disk in this array */
922         for (sd = sra->devs; sd; sd = sd->next) {
923                 sprintf(nm, "%d:%d", sd->disk.major, sd->disk.minor);
924                 dfd = dev_open(nm, keep_fd ? O_RDWR : O_RDONLY);
925                 if (!dfd) {
926                         free_imsm(super);
927                         return 2;
928                 }
929                 rv = load_imsm_mpb(dfd, super, NULL);
930                 if (!keep_fd)
931                         close(dfd);
932                 if (rv == 0) {
933                         gen = __le32_to_cpu(super->mpb->generation_num);
934                         if (!best || gen > bestgen) {
935                                 bestgen = gen;
936                                 best = sd;
937                         }
938                 } else {
939                         free_imsm(super);
940                         return 2;
941                 }
942         }
943
944         if (!best) {
945                 free_imsm(super);
946                 return 1;
947         }
948
949         /* load the most up to date anchor */
950         sprintf(nm, "%d:%d", best->disk.major, best->disk.minor);
951         dfd = dev_open(nm, O_RDONLY);
952         if (!dfd) {
953                 free_imsm(super);
954                 return 1;
955         }
956         rv = load_imsm_mpb(dfd, super, NULL);
957         close(dfd);
958         if (rv != 0) {
959                 free_imsm(super);
960                 return 2;
961         }
962
963         /* reset the disk list */
964         free_imsm_disks(super);
965
966         /* populate disk list */
967         for (sd = sra->devs ; sd ; sd = sd->next) {
968                 sprintf(nm, "%d:%d", sd->disk.major, sd->disk.minor);
969                 dfd = dev_open(nm, keep_fd? O_RDWR : O_RDONLY);
970                 if (!dfd) {
971                         free_imsm(super);
972                         return 2;
973                 }
974                 load_imsm_disk(dfd, super, NULL, keep_fd);
975                 if (!keep_fd)
976                         close(dfd);
977         }
978
979         if (st->subarray[0]) {
980                 /* FIXME */
981         }
982
983         *sbp = super;
984         if (st->ss == NULL) {
985                 st->ss = &super_imsm_container;
986                 st->minor_version = 0;
987                 st->max_devs = IMSM_MAX_DEVICES;
988                 st->container_dev = fd2devnum(fd);
989         }
990
991         return 0;
992 }
993 #endif
994
995 static int load_super_imsm(struct supertype *st, int fd, char *devname)
996 {
997         struct intel_super *super;
998         int rv;
999
1000 #ifndef MDASSEMBLE
1001         if (load_super_imsm_all(st, fd, &st->sb, devname, 1) == 0)
1002                 return 0;
1003 #endif
1004         if (st->subarray[0])
1005                 return 1; /* FIXME */
1006
1007         super = alloc_super(0);
1008         if (!super) {
1009                 fprintf(stderr,
1010                         Name ": malloc of %zu failed.\n",
1011                         sizeof(*super));
1012                 return 1;
1013         }
1014
1015         rv = load_imsm_mpb(fd, super, devname);
1016
1017         if (rv) {
1018                 if (devname)
1019                         fprintf(stderr,
1020                                 Name ": Failed to load all information "
1021                                 "sections on %s\n", devname);
1022                 free_imsm(super);
1023                 return rv;
1024         }
1025
1026         st->sb = super;
1027         if (st->ss == NULL) {
1028                 st->ss = &super_imsm;
1029                 st->minor_version = 0;
1030                 st->max_devs = IMSM_MAX_DEVICES;
1031         }
1032
1033         return 0;
1034 }
1035
1036 static int init_zero_imsm(struct supertype *st, mdu_array_info_t *info,
1037                           unsigned long long size, char *name,
1038                           char *homehost, int *uuid)
1039 {
1040         st->sb = NULL;
1041         return 0;
1042 }
1043
1044 static int init_super_imsm(struct supertype *st, mdu_array_info_t *info,
1045                            unsigned long long size, char *name,
1046                            char *homehost, int *uuid)
1047 {
1048         /* This is primarily called by Create when creating a new array.
1049          * We will then get add_to_super called for each component, and then
1050          * write_init_super called to write it out to each device.
1051          * For IMSM, Create can create on fresh devices or on a pre-existing
1052          * array.
1053          * To create on a pre-existing array a different method will be called.
1054          * This one is just for fresh drives.
1055          */
1056         struct intel_super *super;
1057         struct imsm_super *mpb;
1058         size_t mpb_size;
1059
1060         super = alloc_super(1);
1061         if (!super)
1062                 return 0;
1063         mpb_size = disks_to_mpb_size(info->nr_disks);
1064         mpb = malloc(mpb_size);
1065         if (!mpb) {
1066                 free(super);
1067                 return 0;
1068         }
1069         memset(mpb, 0, mpb_size); 
1070
1071         memcpy(mpb->sig, MPB_SIGNATURE, strlen(MPB_SIGNATURE));
1072         memcpy(mpb->sig + strlen(MPB_SIGNATURE), MPB_VERSION_RAID5,
1073                strlen(MPB_VERSION_RAID5)); 
1074         mpb->mpb_size = mpb_size;
1075
1076         super->mpb = mpb;
1077         st->sb = super;
1078         return 1;
1079 }
1080
1081 static int init_super_imsm_volume(struct supertype *st, mdu_array_info_t *info,
1082                                   unsigned long long size, char *name,
1083                                   char *homehost, int *uuid)
1084 {
1085         /* We are creating a volume inside a pre-existing container.
1086          * so st->sb is already set.
1087          */
1088         struct intel_super *super = st->sb;
1089         struct imsm_super *mpb = super->mpb;
1090         struct imsm_dev *dev;
1091         struct imsm_vol *vol;
1092         struct imsm_map *map;
1093         int idx = mpb->num_raid_devs;
1094         int i;
1095         unsigned long long array_blocks;
1096         unsigned long long sz;
1097         __u32 offset = 0;
1098
1099         if (mpb->num_raid_devs >= 2) {
1100                 fprintf(stderr, Name": This imsm-container already has the "
1101                         "maximum of 2 volumes\n");
1102                 return 0;
1103         }
1104
1105         super->creating_dev = idx;
1106         mpb->num_raid_devs++;
1107         dev = get_imsm_dev(mpb, idx);
1108         strncpy((char *) dev->volume, name, MAX_RAID_SERIAL_LEN);
1109         array_blocks = calc_array_size(info->level, info->raid_disks,
1110                                        info->layout, info->chunk_size,
1111                                        info->size*2);
1112         dev->size_low = __cpu_to_le32((__u32) array_blocks);
1113         dev->size_high = __cpu_to_le32((__u32) (array_blocks >> 32));
1114         dev->status = __cpu_to_le32(0);
1115         dev->reserved_blocks = __cpu_to_le32(0);
1116         vol = &dev->vol;
1117         vol->migr_state = 0;
1118         vol->migr_type = 0;
1119         vol->dirty = 0;
1120         for (i = 0; i < idx; i++) {
1121                 struct imsm_dev *prev = get_imsm_dev(mpb, i);
1122                 struct imsm_map *pmap = &prev->vol.map[0];
1123
1124                 offset += __le32_to_cpu(pmap->blocks_per_member);
1125                 offset += IMSM_RESERVED_SECTORS;
1126         }
1127         map = &vol->map[0];
1128         map->pba_of_lba0 = __cpu_to_le32(offset);
1129         sz = info->size * 2;
1130         map->blocks_per_member = __cpu_to_le32(sz);
1131         map->blocks_per_strip = __cpu_to_le16(info->chunk_size >> 9);
1132         map->num_data_stripes = __cpu_to_le32(sz / (info->chunk_size >> 9));
1133         map->map_state = info->level ? IMSM_T_STATE_UNINITIALIZED :
1134                                        IMSM_T_STATE_NORMAL;
1135         if (info->level == 10)
1136                 map->raid_level = 1;
1137         else
1138                 map->raid_level = info->level;
1139         map->num_members = info->raid_disks;
1140         for (i = 0; i < map->num_members; i++) {
1141                 /* initialized in add_to_super */
1142                 map->disk_ord_tbl[i] = __cpu_to_le32(0);
1143         }
1144
1145         return 1;
1146 }
1147
1148 static void add_to_super_imsm(struct supertype *st, mdu_disk_info_t *dk,
1149                               int fd, char *devname)
1150 {
1151         struct intel_super *super = st->sb;
1152         struct imsm_super *mpb = super->mpb;
1153         struct imsm_disk *disk;
1154         struct dl *dd;
1155         unsigned long long size;
1156         __u32 status, id;
1157         int rv;
1158         struct stat stb;
1159
1160         fstat(fd, &stb);
1161         dd = malloc(sizeof(*dd));
1162         if (!dd) {
1163                 fprintf(stderr,
1164                         Name ": malloc failed %s:%d.\n", __func__, __LINE__);
1165                 abort();
1166         }
1167         memset(dd, 0, sizeof(*dd));
1168         dd->major = major(stb.st_rdev);
1169         dd->minor = minor(stb.st_rdev);
1170         dd->index = dk->number;
1171         dd->devname = devname ? strdup(devname) : NULL;
1172         dd->next = super->disks;
1173         dd->fd = fd;
1174         rv = imsm_read_serial(fd, devname, dd->serial);
1175         if (rv) {
1176                 fprintf(stderr,
1177                         Name ": failed to retrieve scsi serial "
1178                         "using \'%s\' instead\n", devname);
1179                 strcpy((char *) dd->serial, devname);
1180         }
1181
1182         if (mpb->num_disks <= dk->number)
1183                 mpb->num_disks = dk->number + 1;
1184
1185         disk = get_imsm_disk(mpb, dk->number);
1186         get_dev_size(fd, NULL, &size);
1187         size /= 512;
1188         status = USABLE_DISK | SPARE_DISK;
1189         strcpy((char *) disk->serial, (char *) dd->serial);
1190         disk->total_blocks = __cpu_to_le32(size);
1191         disk->status = __cpu_to_le32(status);
1192         if (sysfs_disk_to_scsi_id(fd, &id) == 0)
1193                 disk->scsi_id = __cpu_to_le32(id);
1194         else
1195                 disk->scsi_id = __cpu_to_le32(0);
1196
1197         /* update the family number if we are creating a container */
1198         if (super->creating_imsm)
1199                 mpb->family_num = __cpu_to_le32(gen_imsm_checksum(mpb));
1200         
1201         super->disks = dd;
1202 }
1203
1204 static void add_to_super_imsm_volume(struct supertype *st, mdu_disk_info_t *dk,
1205                                      int fd, char *devname)
1206 {
1207         struct intel_super *super = st->sb;
1208         struct imsm_super *mpb = super->mpb;
1209         struct dl *dl;
1210         struct imsm_dev *dev;
1211         struct imsm_map *map;
1212         struct imsm_disk *disk;
1213         __u32 status;
1214
1215         if (super->creating_dev == -1) {
1216                 fprintf(stderr, Name ": no active raid device\n");
1217                 abort();
1218         }
1219
1220         dev = get_imsm_dev(mpb, super->creating_dev);
1221         map = &dev->vol.map[0];
1222
1223         for (dl = super->disks; dl ; dl = dl->next)
1224                 if (dl->major == dk->major &&
1225                     dl->minor == dk->minor)
1226                         break;
1227         if (!dl || ! (dk->state & (1<<MD_DISK_SYNC)))
1228                 return;
1229
1230         map->disk_ord_tbl[dk->number] = __cpu_to_le32(dl->index);
1231
1232         disk = get_imsm_disk(mpb, dl->index);
1233         status = CONFIGURED_DISK | USABLE_DISK;
1234         disk->status = __cpu_to_le32(status);
1235 }
1236
1237 static int store_imsm_mpb(int fd, struct intel_super *super);
1238
1239 static int write_super_imsm(struct intel_super *super, int doclose)
1240 {
1241         struct imsm_super *mpb = super->mpb;
1242         struct dl *d;
1243         __u32 generation;
1244         __u32 sum;
1245
1246         /* 'generation' is incremented everytime the metadata is written */
1247         generation = __le32_to_cpu(mpb->generation_num);
1248         generation++;
1249         mpb->generation_num = __cpu_to_le32(generation);
1250
1251         /* recalculate checksum */
1252         sum = gen_imsm_checksum(mpb);
1253         mpb->check_sum = __cpu_to_le32(sum);
1254
1255         for (d = super->disks; d ; d = d->next) {
1256                 if (store_imsm_mpb(d->fd, super)) {
1257                         fprintf(stderr, "%s: failed for device %d:%d %s\n",
1258                                 __func__, d->major, d->minor, strerror(errno));
1259                         return 0;
1260                 }
1261                 if (doclose) {
1262                         close(d->fd);
1263                         d->fd = -1;
1264                 }
1265         }
1266
1267         return 1;
1268 }
1269
1270 static int write_init_super_imsm(struct supertype *st)
1271 {
1272         return write_super_imsm(st->sb, 1);
1273 }
1274
1275 static int store_zero_imsm(struct supertype *st, int fd)
1276 {
1277         unsigned long long dsize;
1278         char buf[512];
1279
1280         get_dev_size(fd, NULL, &dsize);
1281
1282         /* first block is stored on second to last sector of the disk */
1283         if (lseek64(fd, dsize - (512 * 2), SEEK_SET) < 0)
1284                 return 1;
1285
1286         memset(buf, 0, sizeof(buf));
1287         if (write(fd, buf, sizeof(buf)) != sizeof(buf))
1288                 return 1;
1289
1290         return 0;
1291 }
1292
1293 static void getinfo_super_n_imsm_container(struct supertype *st, struct mdinfo *info)
1294 {
1295         /* just need offset and size...
1296          * of the metadata
1297          */
1298         struct intel_super *super = st->sb;
1299         struct imsm_super *mpb = super->mpb;
1300         struct imsm_disk *disk = get_imsm_disk(mpb, info->disk.number);
1301
1302         info->data_offset = __le32_to_cpu(disk->total_blocks) -
1303                             (MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS);
1304         info->component_size = MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS;
1305 }
1306
1307 static void getinfo_super_n_imsm_volume(struct supertype *st, struct mdinfo *info)
1308 {
1309         /* Find the particular details for info->disk.raid_disk.
1310          * This includes data_offset, component_size,
1311          */
1312         struct intel_super *super = st->sb;
1313         struct imsm_super *mpb = super->mpb;
1314         struct imsm_dev *dev = get_imsm_dev(mpb, super->creating_dev);
1315         struct imsm_map *map = &dev->vol.map[0];
1316
1317         info->data_offset = __le32_to_cpu(map->pba_of_lba0);
1318         info->component_size = __le32_to_cpu(map->blocks_per_member);
1319 }
1320
1321 static int validate_geometry_imsm(struct supertype *st, int level, int layout,
1322                                   int raiddisks, int chunk, unsigned long long size,
1323                                   char *dev, unsigned long long *freesize)
1324 {
1325         int fd, cfd;
1326         struct mdinfo *sra;
1327
1328         /* if given unused devices create a container 
1329          * if given given devices in a container create a member volume
1330          */
1331         if (level == LEVEL_CONTAINER) {
1332                 st->ss = &super_imsm_container;
1333                 if (dev) {
1334                         /* validate the container, dev == NULL */
1335                         int rv = st->ss->validate_geometry(st, level, layout,
1336                                                            raiddisks, chunk,
1337                                                            size,
1338                                                            NULL, freesize);
1339                         if (rv)
1340                                 return rv;
1341                 }
1342                 return st->ss->validate_geometry(st, level, layout, raiddisks,
1343                                                  chunk, size, dev, freesize);
1344         }
1345         
1346         if (st->sb) {
1347                 /* creating in a given container */
1348                 st->ss = &super_imsm_volume;
1349                 if (dev) {
1350                         int rv = st->ss->validate_geometry(st, level, layout,
1351                                                            raiddisks, chunk,
1352                                                            size,
1353                                                            NULL, freesize);
1354                         if (rv)
1355                                 return rv;
1356                 }
1357                 return st->ss->validate_geometry(st, level, layout, raiddisks,
1358                                                  chunk, size, dev, freesize);
1359         }
1360
1361         /* limit creation to the following levels */
1362         if (!dev)
1363                 switch (level) {
1364                 case 0:
1365                 case 1:
1366                 case 10:
1367                 case 5:
1368                         break;
1369                 default:
1370                         return 1;
1371                 }
1372
1373         /* This device needs to be a device in an 'imsm' container */
1374         fd = open(dev, O_RDONLY|O_EXCL, 0);
1375         if (fd >= 0) {
1376                 fprintf(stderr,
1377                         Name ": Cannot create this array on device %s\n",
1378                         dev);
1379                 close(fd);
1380                 return 0;
1381         }
1382         if (errno != EBUSY || (fd = open(dev, O_RDONLY, 0)) < 0) {
1383                 fprintf(stderr, Name ": Cannot open %s: %s\n",
1384                         dev, strerror(errno));
1385                 return 0;
1386         }
1387         /* Well, it is in use by someone, maybe an 'imsm' container. */
1388         cfd = open_container(fd);
1389         if (cfd < 0) {
1390                 close(fd);
1391                 fprintf(stderr, Name ": Cannot use %s: It is busy\n",
1392                         dev);
1393                 return 0;
1394         }
1395         sra = sysfs_read(cfd, 0, GET_VERSION);
1396         close(fd);
1397         if (sra && sra->array.major_version == -1 &&
1398             strcmp(sra->text_version, "imsm") == 0) {
1399                 /* This is a member of a imsm container.  Load the container
1400                  * and try to create a volume
1401                  */
1402                 struct intel_super *super;
1403                 st->ss = &super_imsm_volume;
1404                 if (load_super_imsm_all(st, cfd, (void **) &super, NULL, 1) == 0) {
1405                         st->sb = super;
1406                         st->container_dev = fd2devnum(cfd);
1407                         close(cfd);
1408                         return st->ss->validate_geometry(st, level, layout,
1409                                                          raiddisks, chunk, size,
1410                                                          dev, freesize);
1411                 }
1412                 close(cfd);
1413         } else /* may belong to another container */
1414                 return 0;
1415
1416         return 1;
1417 }
1418
1419 static int validate_geometry_imsm_container(struct supertype *st, int level,
1420                                             int layout, int raiddisks, int chunk,
1421                                             unsigned long long size, char *dev,
1422                                             unsigned long long *freesize)
1423 {
1424         int fd;
1425         unsigned long long ldsize;
1426
1427         if (level != LEVEL_CONTAINER)
1428                 return 0;
1429         if (!dev)
1430                 return 1;
1431
1432         fd = open(dev, O_RDONLY|O_EXCL, 0);
1433         if (fd < 0) {
1434                 fprintf(stderr, Name ": Cannot open %s: %s\n",
1435                         dev, strerror(errno));
1436                 return 0;
1437         }
1438         if (!get_dev_size(fd, dev, &ldsize)) {
1439                 close(fd);
1440                 return 0;
1441         }
1442         close(fd);
1443
1444         *freesize = avail_size_imsm(st, ldsize >> 9);
1445
1446         return 1;
1447 }
1448
1449 /* validate_geometry_imsm_volume - lifted from validate_geometry_ddf_bvd 
1450  * FIX ME add ahci details
1451  */
1452 static int validate_geometry_imsm_volume(struct supertype *st, int level,
1453                                          int layout, int raiddisks, int chunk,
1454                                          unsigned long long size, char *dev,
1455                                          unsigned long long *freesize)
1456 {
1457         struct stat stb;
1458         struct intel_super *super = st->sb;
1459         struct dl *dl;
1460         unsigned long long pos = 0;
1461         unsigned long long maxsize;
1462         struct extent *e;
1463         int i;
1464
1465         if (level == LEVEL_CONTAINER)
1466                 return 0;
1467
1468         if (level == 1 && raiddisks > 2) {
1469                 fprintf(stderr, Name ": imsm does not support more than 2 "
1470                         "in a raid1 configuration\n");
1471                 return 0;
1472         }
1473
1474         /* We must have the container info already read in. */
1475         if (!super)
1476                 return 0;
1477
1478         if (!dev) {
1479                 /* General test:  make sure there is space for
1480                  * 'raiddisks' device extents of size 'size'.
1481                  */
1482                 unsigned long long minsize = size*2 /* convert to blocks */;
1483                 int dcnt = 0;
1484                 if (minsize == 0)
1485                         minsize = MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS;
1486                 for (dl = super->disks; dl ; dl = dl->next) {
1487                         int found = 0;
1488
1489                         i = 0;
1490                         e = get_extents(super, dl);
1491                         if (!e) continue;
1492                         do {
1493                                 unsigned long long esize;
1494                                 esize = e[i].start - pos;
1495                                 if (esize >= minsize)
1496                                         found = 1;
1497                                 pos = e[i].start + e[i].size;
1498                                 i++;
1499                         } while (e[i-1].size);
1500                         if (found)
1501                                 dcnt++;
1502                         free(e);
1503                 }
1504                 if (dcnt < raiddisks) {
1505                         fprintf(stderr, Name ": Not enough devices with space "
1506                                 "for this array (%d < %d)\n",
1507                                 dcnt, raiddisks);
1508                         return 0;
1509                 }
1510                 return 1;
1511         }
1512         /* This device must be a member of the set */
1513         if (stat(dev, &stb) < 0)
1514                 return 0;
1515         if ((S_IFMT & stb.st_mode) != S_IFBLK)
1516                 return 0;
1517         for (dl = super->disks ; dl ; dl = dl->next) {
1518                 if (dl->major == major(stb.st_rdev) &&
1519                     dl->minor == minor(stb.st_rdev))
1520                         break;
1521         }
1522         if (!dl) {
1523                 fprintf(stderr, Name ": %s is not in the same imsm set\n",
1524                         dev);
1525                 return 0;
1526         }
1527         e = get_extents(super, dl);
1528         maxsize = 0;
1529         i = 0;
1530         if (e) do {
1531                 unsigned long long esize;
1532                 esize = e[i].start - pos;
1533                 if (esize >= maxsize)
1534                         maxsize = esize;
1535                 pos = e[i].start + e[i].size;
1536                 i++;
1537         } while (e[i-1].size);
1538         *freesize = maxsize;
1539
1540         return 1;
1541 }
1542
1543 static struct mdinfo *container_content_imsm(struct supertype *st)
1544 {
1545         /* Given a container loaded by load_super_imsm_all,
1546          * extract information about all the arrays into
1547          * an mdinfo tree.
1548          *
1549          * For each imsm_dev create an mdinfo, fill it in,
1550          *  then look for matching devices in super->disks
1551          *  and create appropriate device mdinfo.
1552          */
1553         struct intel_super *super = st->sb;
1554         struct imsm_super *mpb = super->mpb;
1555         struct mdinfo *rest = NULL;
1556         int i;
1557
1558         for (i = 0; i < mpb->num_raid_devs; i++) {
1559                 struct imsm_dev *dev = get_imsm_dev(mpb, i);
1560                 struct imsm_vol *vol = &dev->vol;
1561                 struct imsm_map *map = vol->map;
1562                 struct mdinfo *this;
1563                 __u64 sz;
1564                 int slot;
1565
1566                 this = malloc(sizeof(*this));
1567                 memset(this, 0, sizeof(*this));
1568                 this->next = rest;
1569                 rest = this;
1570
1571                 this->array.level = get_imsm_raid_level(map);
1572                 this->array.raid_disks = map->num_members;
1573                 this->array.layout = imsm_level_to_layout(this->array.level);
1574                 this->array.md_minor = -1;
1575                 this->array.ctime = 0;
1576                 this->array.utime = 0;
1577                 this->array.chunk_size = __le16_to_cpu(map->blocks_per_strip) << 9;
1578                 this->array.state = !vol->dirty;
1579                 this->container_member = i;
1580                 if (map->map_state == IMSM_T_STATE_UNINITIALIZED || dev->vol.dirty)
1581                         this->resync_start = 0;
1582                 else
1583                         this->resync_start = ~0ULL;
1584
1585                 strncpy(this->name, (char *) dev->volume, MAX_RAID_SERIAL_LEN);
1586                 this->name[MAX_RAID_SERIAL_LEN] = 0;
1587
1588                 sprintf(this->text_version, "/%s/%d",
1589                         devnum2devname(st->container_dev),
1590                         this->container_member);
1591
1592                 memset(this->uuid, 0, sizeof(this->uuid));
1593
1594                 sz = __le32_to_cpu(dev->size_high);
1595                 sz <<= 32;
1596                 sz += __le32_to_cpu(dev->size_low);
1597                 this->component_size = sz;
1598                 this->array.size = this->component_size / 2;
1599
1600                 for (slot = 0 ; slot <  map->num_members; slot++) {
1601                         struct imsm_disk *disk;
1602                         struct mdinfo *info_d;
1603                         struct dl *d;
1604                         int idx;
1605                         __u32 s;
1606
1607                         idx = __le32_to_cpu(map->disk_ord_tbl[slot] & ~(0xff << 24));
1608                         for (d = super->disks; d ; d = d->next)
1609                                 if (d->index == idx)
1610                                         break;
1611
1612                         if (d == NULL)
1613                                 break; /* shouldn't this be continue ?? */
1614
1615                         info_d = malloc(sizeof(*info_d));
1616                         if (!info_d)
1617                                 break; /* ditto ?? */
1618                         memset(info_d, 0, sizeof(*info_d));
1619                         info_d->next = this->devs;
1620                         this->devs = info_d;
1621
1622                         disk = get_imsm_disk(mpb, idx);
1623                         s = __le32_to_cpu(disk->status);
1624
1625                         info_d->disk.number = d->index;
1626                         info_d->disk.major = d->major;
1627                         info_d->disk.minor = d->minor;
1628                         info_d->disk.raid_disk = slot;
1629                         info_d->disk.state  = s & CONFIGURED_DISK ? (1 << MD_DISK_ACTIVE) : 0;
1630                         info_d->disk.state |= s & FAILED_DISK ? (1 << MD_DISK_FAULTY) : 0;
1631                         info_d->disk.state |= s & USABLE_DISK ? (1 << MD_DISK_SYNC) : 0;
1632
1633                         this->array.working_disks++;
1634
1635                         info_d->events = __le32_to_cpu(mpb->generation_num);
1636                         info_d->data_offset = __le32_to_cpu(map->pba_of_lba0);
1637                         info_d->component_size = __le32_to_cpu(map->blocks_per_member);
1638                         if (d->devname)
1639                                 strcpy(info_d->name, d->devname);
1640                 }
1641         }
1642
1643         return rest;
1644 }
1645
1646
1647 static int imsm_open_new(struct supertype *c, struct active_array *a,
1648                          char *inst)
1649 {
1650         dprintf("imsm: open_new %s\n", inst);
1651         a->info.container_member = atoi(inst);
1652         return 0;
1653 }
1654
1655 static __u8 imsm_check_degraded(struct imsm_super *mpb, int n, int failed)
1656 {
1657         struct imsm_dev *dev = get_imsm_dev(mpb, n);
1658         struct imsm_map *map = dev->vol.map;
1659
1660         if (!failed)
1661                 return map->map_state;
1662
1663         switch (get_imsm_raid_level(map)) {
1664         case 0:
1665                 return IMSM_T_STATE_FAILED;
1666                 break;
1667         case 1:
1668                 if (failed < map->num_members)
1669                         return IMSM_T_STATE_DEGRADED;
1670                 else
1671                         return IMSM_T_STATE_FAILED;
1672                 break;
1673         case 10:
1674         {
1675                 /**
1676                  * check to see if any mirrors have failed,
1677                  * otherwise we are degraded
1678                  */
1679                 int device_per_mirror = 2; /* FIXME is this always the case?
1680                                             * and are they always adjacent?
1681                                             */
1682                 int failed = 0;
1683                 int i;
1684
1685                 for (i = 0; i < map->num_members; i++) {
1686                         int idx = get_imsm_disk_idx(map, i);
1687                         struct imsm_disk *disk = get_imsm_disk(mpb, idx);
1688
1689                         if (__le32_to_cpu(disk->status) & FAILED_DISK)
1690                                 failed++;
1691
1692                         if (failed >= device_per_mirror)
1693                                 return IMSM_T_STATE_FAILED;
1694
1695                         /* reset 'failed' for next mirror set */
1696                         if (!((i + 1) % device_per_mirror))
1697                                 failed = 0;
1698                 }
1699
1700                 return IMSM_T_STATE_DEGRADED;
1701         }
1702         case 5:
1703                 if (failed < 2)
1704                         return IMSM_T_STATE_DEGRADED;
1705                 else
1706                         return IMSM_T_STATE_FAILED;
1707                 break;
1708         default:
1709                 break;
1710         }
1711
1712         return map->map_state;
1713 }
1714
1715 static int imsm_count_failed(struct imsm_super *mpb, struct imsm_map *map)
1716 {
1717         int i;
1718         int failed = 0;
1719         struct imsm_disk *disk;
1720
1721         for (i = 0; i < map->num_members; i++) {
1722                 int idx = get_imsm_disk_idx(map, i);
1723
1724                 disk = get_imsm_disk(mpb, idx);
1725                 if (__le32_to_cpu(disk->status) & FAILED_DISK)
1726                         failed++;
1727         }
1728
1729         return failed;
1730 }
1731
1732 static void imsm_set_array_state(struct active_array *a, int consistent)
1733 {
1734         int inst = a->info.container_member;
1735         struct intel_super *super = a->container->sb;
1736         struct imsm_dev *dev = get_imsm_dev(super->mpb, inst);
1737         struct imsm_map *map = &dev->vol.map[0];
1738         int dirty = !consistent;
1739         int failed;
1740         __u8 map_state;
1741
1742         if (a->resync_start == ~0ULL) {
1743                 failed = imsm_count_failed(super->mpb, map);
1744                 map_state = imsm_check_degraded(super->mpb, inst, failed);
1745                 if (!failed)
1746                         map_state = IMSM_T_STATE_NORMAL;
1747                 if (map->map_state != map_state) {
1748                         dprintf("imsm: map_state %d: %d\n",
1749                                 inst, map_state);
1750                         map->map_state = map_state;
1751                         super->updates_pending++;
1752                 }
1753         }
1754
1755         if (dev->vol.dirty != dirty) {
1756                 dprintf("imsm: mark '%s' (%llu)\n",
1757                         dirty?"dirty":"clean", a->resync_start);
1758
1759                 dev->vol.dirty = dirty;
1760                 super->updates_pending++;
1761         }
1762 }
1763
1764 static void imsm_set_disk(struct active_array *a, int n, int state)
1765 {
1766         int inst = a->info.container_member;
1767         struct intel_super *super = a->container->sb;
1768         struct imsm_dev *dev = get_imsm_dev(super->mpb, inst);
1769         struct imsm_map *map = dev->vol.map;
1770         struct imsm_disk *disk;
1771         __u32 status;
1772         int failed = 0;
1773         int new_failure = 0;
1774
1775         if (n > map->num_members)
1776                 fprintf(stderr, "imsm: set_disk %d out of range 0..%d\n",
1777                         n, map->num_members - 1);
1778
1779         if (n < 0)
1780                 return;
1781
1782         dprintf("imsm: set_disk %d:%x\n", n, state);
1783
1784         disk = get_imsm_disk(super->mpb, get_imsm_disk_idx(map, n));
1785
1786         /* check if we have seen this failure before */
1787         status = __le32_to_cpu(disk->status);
1788         if ((state & DS_FAULTY) && !(status & FAILED_DISK)) {
1789                 status |= FAILED_DISK;
1790                 disk->status = __cpu_to_le32(status);
1791                 new_failure = 1;
1792         }
1793
1794         /**
1795          * the number of failures have changed, count up 'failed' to determine
1796          * degraded / failed status
1797          */
1798         if (new_failure && map->map_state != IMSM_T_STATE_FAILED)
1799                 failed = imsm_count_failed(super->mpb, map);
1800
1801         if (failed)
1802                 map->map_state = imsm_check_degraded(super->mpb, inst, failed);
1803
1804         if (new_failure)
1805                 super->updates_pending++;
1806 }
1807
1808 static int store_imsm_mpb(int fd, struct intel_super *super)
1809 {
1810         struct imsm_super *mpb = super->mpb;
1811         __u32 mpb_size = __le32_to_cpu(mpb->mpb_size);
1812         unsigned long long dsize;
1813         unsigned long long sectors;
1814
1815         get_dev_size(fd, NULL, &dsize);
1816
1817         if (mpb_size > 512) {
1818                 /* -1 to account for anchor */
1819                 sectors = mpb_sectors(mpb) - 1;
1820
1821                 /* write the extended mpb to the sectors preceeding the anchor */
1822                 if (lseek64(fd, dsize - (512 * (2 + sectors)), SEEK_SET) < 0)
1823                         return 1;
1824
1825                 if (write(fd, super->buf + 512, mpb_size - 512) != mpb_size - 512)
1826                         return 1;
1827         }
1828
1829         /* first block is stored on second to last sector of the disk */
1830         if (lseek64(fd, dsize - (512 * 2), SEEK_SET) < 0)
1831                 return 1;
1832
1833         if (write(fd, super->buf, 512) != 512)
1834                 return 1;
1835
1836         fsync(fd);
1837
1838         return 0;
1839 }
1840
1841 static void imsm_sync_metadata(struct supertype *container)
1842 {
1843         struct intel_super *super = container->sb;
1844
1845         if (!super->updates_pending)
1846                 return;
1847
1848         write_super_imsm(super, 0);
1849
1850         super->updates_pending = 0;
1851 }
1852
1853 struct superswitch super_imsm = {
1854 #ifndef MDASSEMBLE
1855         .examine_super  = examine_super_imsm,
1856         .brief_examine_super = brief_examine_super_imsm,
1857         .detail_super   = detail_super_imsm,
1858         .brief_detail_super = brief_detail_super_imsm,
1859 #endif
1860         .match_home     = match_home_imsm,
1861         .uuid_from_super= uuid_from_super_imsm,
1862         .getinfo_super  = getinfo_super_imsm,
1863         .update_super   = update_super_imsm,
1864
1865         .avail_size     = avail_size_imsm,
1866
1867         .compare_super  = compare_super_imsm,
1868
1869         .load_super     = load_super_imsm,
1870         .init_super     = init_zero_imsm,
1871         .store_super    = store_zero_imsm,
1872         .free_super     = free_super_imsm,
1873         .match_metadata_desc = match_metadata_desc_imsm,
1874         .getinfo_super_n  = getinfo_super_n_imsm_container,
1875
1876         .validate_geometry = validate_geometry_imsm,
1877         .swapuuid       = 0,
1878         .external       = 1,
1879
1880 /* for mdmon */
1881         .open_new       = imsm_open_new,
1882         .load_super     = load_super_imsm,
1883         .set_array_state= imsm_set_array_state,
1884         .set_disk       = imsm_set_disk,
1885         .sync_metadata  = imsm_sync_metadata,
1886 };
1887
1888 /* super_imsm_container is set by validate_geometry_imsm when given a
1889  * device that is not part of any array
1890  */
1891 struct superswitch super_imsm_container = {
1892
1893         .validate_geometry = validate_geometry_imsm_container,
1894         .init_super     = init_super_imsm,
1895         .add_to_super   = add_to_super_imsm,
1896         .write_init_super = write_init_super_imsm,
1897         .getinfo_super  = getinfo_super_imsm,
1898         .getinfo_super_n  = getinfo_super_n_imsm_container,
1899         .load_super     = load_super_imsm,
1900
1901 #ifndef MDASSEMBLE
1902         .examine_super  = examine_super_imsm,
1903         .brief_examine_super = brief_examine_super_imsm,
1904         .detail_super   = detail_super_imsm,
1905         .brief_detail_super = brief_detail_super_imsm,
1906 #endif
1907
1908         .free_super     = free_super_imsm,
1909
1910         .container_content = container_content_imsm,
1911
1912         .swapuuid       = 0,
1913         .external       = 1,
1914 };
1915
1916 static struct superswitch super_imsm_volume = {
1917         .update_super   = update_super_imsm,
1918         .init_super     = init_super_imsm_volume,
1919         .add_to_super   = add_to_super_imsm_volume,
1920         .getinfo_super  = getinfo_super_imsm_volume,
1921         .getinfo_super_n  = getinfo_super_n_imsm_volume,
1922         .write_init_super = write_init_super_imsm,
1923
1924         .load_super     = load_super_imsm,
1925         .free_super     = free_super_imsm,
1926         .match_metadata_desc = match_metadata_desc_imsm_volume,
1927
1928
1929         .validate_geometry = validate_geometry_imsm_volume,
1930         .swapuuid       = 0,
1931         .external       = 2,
1932 };