Remove getinfo_super_n and do some other cleaning up.
[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         int sect = mpb_sectors(mpb);
503         __u32 s;
504
505         info->array.raid_disks    = mpb->num_disks;
506         info->array.level         = LEVEL_CONTAINER;
507         info->array.layout        = 0;
508         info->array.md_minor      = -1;
509         info->array.ctime         = 0; /* N/A for imsm */ 
510         info->array.utime         = 0;
511         info->array.chunk_size    = 0;
512
513         info->disk.major = 0;
514         info->disk.minor = 0;
515         info->disk.raid_disk = -1;
516         info->reshape_active = 0;
517         strcpy(info->text_version, "imsm");
518         info->disk.number = -1;
519         info->disk.state = 0;
520
521         info->data_offset = __le32_to_cpu(get_imsm_disk(super->mpb,
522                                                         super->disks->index)
523                                           ->total_blocks) - (2 + sect - 1);
524         info->component_size = sect;
525
526         if (super->disks) {
527                 info->disk.number = super->disks->index;
528                 info->disk.raid_disk = super->disks->index;
529                 disk = get_imsm_disk(mpb, super->disks->index);
530                 s = __le32_to_cpu(disk->status);
531                 info->disk.state  = s & CONFIGURED_DISK ? (1 << MD_DISK_ACTIVE) : 0;
532                 info->disk.state |= s & FAILED_DISK ? (1 << MD_DISK_FAULTY) : 0;
533                 info->disk.state |= s & USABLE_DISK ? (1 << MD_DISK_SYNC) : 0;
534         }
535 }
536
537 static void getinfo_super_imsm_volume(struct supertype *st, struct mdinfo *info)
538 {
539         struct intel_super *super = st->sb;
540         struct imsm_super *mpb = super->mpb;
541         struct imsm_dev *dev = get_imsm_dev(mpb, info->container_member);
542         struct imsm_map *map = &dev->vol.map[0];
543
544         info->array.raid_disks    = map->num_members;
545         info->array.level         = get_imsm_raid_level(map);
546         info->array.layout        = imsm_level_to_layout(info->array.level);
547         info->array.md_minor      = -1;
548         info->array.ctime         = 0;
549         info->array.utime         = 0;
550         info->array.chunk_size    = __le16_to_cpu(map->blocks_per_strip * 512);
551
552         info->data_offset         = __le32_to_cpu(map->pba_of_lba0);
553         info->component_size      = __le32_to_cpu(map->blocks_per_member);
554
555         info->disk.major = 0;
556         info->disk.minor = 0;
557
558         sprintf(info->text_version, "/%s/%d",
559                 devnum2devname(st->container_dev),
560                 info->container_member);
561 }
562
563 static int update_super_imsm(struct supertype *st, struct mdinfo *info,
564                              char *update, char *devname, int verbose,
565                              int uuid_set, char *homehost)
566 {
567         /* FIXME */
568
569         /* For 'assemble' and 'force' we need to return non-zero if any
570          * change was made.  For others, the return value is ignored.
571          * Update options are:
572          *  force-one : This device looks a bit old but needs to be included,
573          *        update age info appropriately.
574          *  assemble: clear any 'faulty' flag to allow this device to
575          *              be assembled.
576          *  force-array: Array is degraded but being forced, mark it clean
577          *         if that will be needed to assemble it.
578          *
579          *  newdev:  not used ????
580          *  grow:  Array has gained a new device - this is currently for
581          *              linear only
582          *  resync: mark as dirty so a resync will happen.
583          *  name:  update the name - preserving the homehost
584          *
585          * Following are not relevant for this imsm:
586          *  sparc2.2 : update from old dodgey metadata
587          *  super-minor: change the preferred_minor number
588          *  summaries:  update redundant counters.
589          *  uuid:  Change the uuid of the array to match watch is given
590          *  homehost:  update the recorded homehost
591          *  _reshape_progress: record new reshape_progress position.
592          */
593         int rv = 0;
594         //struct intel_super *super = st->sb;
595         //struct imsm_super *mpb = super->mpb;
596
597         if (strcmp(update, "grow") == 0) {
598         }
599         if (strcmp(update, "resync") == 0) {
600                 /* dev->vol.dirty = 1; */
601         }
602
603         /* IMSM has no concept of UUID or homehost */
604
605         return rv;
606 }
607
608 static size_t disks_to_mpb_size(int disks)
609 {
610         size_t size;
611
612         size = sizeof(struct imsm_super);
613         size += (disks - 1) * sizeof(struct imsm_disk);
614         size += 2 * sizeof(struct imsm_dev);
615         /* up to 2 maps per raid device (-2 for imsm_maps in imsm_dev */
616         size += (4 - 2) * sizeof(struct imsm_map);
617         /* 4 possible disk_ord_tbl's */
618         size += 4 * (disks - 1) * sizeof(__u32);
619
620         return size;
621 }
622
623 static __u64 avail_size_imsm(struct supertype *st, __u64 devsize)
624 {
625         if (devsize < (MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS))
626                 return 0;
627
628         return devsize - (MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS);
629 }
630
631 static int compare_super_imsm(struct supertype *st, struct supertype *tst)
632 {
633         /*
634          * return:
635          *  0 same, or first was empty, and second was copied
636          *  1 second had wrong number
637          *  2 wrong uuid
638          *  3 wrong other info
639          */
640         struct intel_super *first = st->sb;
641         struct intel_super *sec = tst->sb;
642
643         if (!first) {
644                 st->sb = tst->sb;
645                 tst->sb = NULL;
646                 return 0;
647         }
648
649         if (memcmp(first->mpb->sig, sec->mpb->sig, MAX_SIGNATURE_LENGTH) != 0)
650                 return 3;
651         if (first->mpb->family_num != sec->mpb->family_num)
652                 return 3;
653         if (first->mpb->mpb_size != sec->mpb->mpb_size)
654                 return 3;
655         if (first->mpb->check_sum != sec->mpb->check_sum)
656                 return 3;
657
658         return 0;
659 }
660
661 extern int scsi_get_serial(int fd, void *buf, size_t buf_len);
662
663 static int imsm_read_serial(int fd, char *devname,
664                             __u8 serial[MAX_RAID_SERIAL_LEN])
665 {
666         unsigned char scsi_serial[255];
667         int sg_fd;
668         int rv;
669         int rsp_len;
670         int i, cnt;
671
672         memset(scsi_serial, 0, sizeof(scsi_serial));
673
674         sg_fd = sysfs_disk_to_sg(fd);
675         if (sg_fd < 0) {
676                 if (devname)
677                         fprintf(stderr,
678                                 Name ": Failed to open sg interface for %s: %s\n",
679                                 devname, strerror(errno));
680                 return 1;
681         }
682
683         rv = scsi_get_serial(sg_fd, scsi_serial, sizeof(scsi_serial));
684         close(sg_fd);
685
686         if (rv != 0) {
687                 if (devname)
688                         fprintf(stderr,
689                                 Name ": Failed to retrieve serial for %s\n",
690                                 devname);
691                 return rv;
692         }
693
694         rsp_len = scsi_serial[3];
695         for (i = 0, cnt = 0; i < rsp_len; i++) {
696                 if (!isspace(scsi_serial[4 + i]))
697                         serial[cnt++] = scsi_serial[4 + i];
698                 if (cnt == MAX_RAID_SERIAL_LEN)
699                         break;
700         }
701
702         serial[MAX_RAID_SERIAL_LEN - 1] = '\0';
703
704         return 0;
705 }
706
707 static int
708 load_imsm_disk(int fd, struct intel_super *super, char *devname, int keep_fd)
709 {
710         struct imsm_super *mpb = super->mpb;
711         struct dl *dl;
712         struct stat stb;
713         struct imsm_disk *disk;
714         int rv;
715         int i;
716
717         dl = malloc(sizeof(*dl));
718         if (!dl) {
719                 if (devname)
720                         fprintf(stderr,
721                                 Name ": failed to allocate disk buffer for %s\n",
722                                 devname);
723                 return 2;
724         }
725         memset(dl, 0, sizeof(*dl));
726
727         fstat(fd, &stb);
728         dl->major = major(stb.st_rdev);
729         dl->minor = minor(stb.st_rdev);
730         dl->next = super->disks;
731         dl->fd = keep_fd ? fd : -1;
732         dl->devname = devname ? strdup(devname) : NULL;
733         dl->index = -1;
734         super->disks = dl;
735         rv = imsm_read_serial(fd, devname, dl->serial);
736
737         if (rv != 0)
738                 return 2;
739
740         /* look up this disk's index */
741         for (i = 0; i < mpb->num_disks; i++) {
742                 disk = get_imsm_disk(mpb, i);
743
744                 if (memcmp(disk->serial, dl->serial, MAX_RAID_SERIAL_LEN) == 0)
745                         break;
746         }
747
748         if (i > mpb->num_disks)
749                 return 2;
750
751         dl->index = i;
752
753         return 0;
754 }
755
756 /* load_imsm_mpb - read matrix metadata
757  * allocates super->mpb to be freed by free_super
758  */
759 static int load_imsm_mpb(int fd, struct intel_super *super, char *devname)
760 {
761         unsigned long long dsize;
762         size_t len, mpb_size;
763         unsigned long long sectors;
764         struct stat;
765         struct imsm_super anchor;
766         __u32 check_sum;
767
768         memset(super, 0, sizeof(*super));
769         get_dev_size(fd, NULL, &dsize);
770
771         if (lseek64(fd, dsize - (512 * 2), SEEK_SET) < 0) {
772                 if (devname)
773                         fprintf(stderr,
774                                 Name ": Cannot seek to anchor block on %s: %s\n",
775                                 devname, strerror(errno));
776                 return 1;
777         }
778
779         len = sizeof(anchor);
780         if (read(fd, &anchor, len) != len) {
781                 if (devname)
782                         fprintf(stderr,
783                                 Name ": Cannot read anchor block on %s: %s\n",
784                                 devname, strerror(errno));
785                 return 1;
786         }
787
788         if (strncmp((char *) anchor.sig, MPB_SIGNATURE, MPB_SIG_LEN) != 0) {
789                 if (devname)
790                         fprintf(stderr,
791                                 Name ": no IMSM anchor on %s\n", devname);
792                 return 2;
793         }
794
795         mpb_size = __le32_to_cpu(anchor.mpb_size);
796         super->mpb = malloc(mpb_size < 512 ? 512 : mpb_size);
797         if (!super->mpb) {
798                 if (devname)
799                         fprintf(stderr,
800                                 Name ": unable to allocate %zu byte mpb buffer\n",
801                                 mpb_size);
802                 return 2;
803         }
804         memcpy(super->buf, &anchor, sizeof(anchor));
805
806         /* read the rest of the first block */
807         len = 512 - sizeof(anchor);
808         if (read(fd, super->buf + sizeof(anchor), len) != len) {
809                 if (devname)
810                         fprintf(stderr,
811                                 Name ": Cannot read anchor remainder on %s: %s\n",
812                                 devname, strerror(errno));
813                 return 2;
814         }
815
816         sectors = mpb_sectors(&anchor) - 1;
817         if (!sectors)
818                 return load_imsm_disk(fd, super, devname, 0);
819
820         /* read the extended mpb */
821         if (lseek64(fd, dsize - (512 * (2 + sectors)), SEEK_SET) < 0) {
822                 if (devname)
823                         fprintf(stderr,
824                                 Name ": Cannot seek to extended mpb on %s: %s\n",
825                                 devname, strerror(errno));
826                 return 1;
827         }
828
829         len = mpb_size - 512;
830         if (read(fd, super->buf + 512, len) != len) {
831                 if (devname)
832                         fprintf(stderr,
833                                 Name ": Cannot read extended mpb on %s: %s\n",
834                                 devname, strerror(errno));
835                 return 2;
836         }
837
838         check_sum = gen_imsm_checksum(super->mpb);
839         if (check_sum != __le32_to_cpu(super->mpb->check_sum)) {
840                 if (devname)
841                         fprintf(stderr,
842                                 Name ": IMSM checksum %x != %x on %s\n",
843                                 check_sum, __le32_to_cpu(super->mpb->check_sum),
844                                 devname);
845                 return 2;
846         }
847
848         return load_imsm_disk(fd, super, devname, 0);
849 }
850
851 struct superswitch super_imsm_container;
852
853 static void free_imsm_disks(struct intel_super *super)
854 {
855         while (super->disks) {
856                 struct dl *d = super->disks;
857
858                 super->disks = d->next;
859                 if (d->fd >= 0)
860                         close(d->fd);
861                 if (d->devname)
862                         free(d->devname);
863                 free(d);
864         }
865 }
866
867 static void free_imsm(struct intel_super *super)
868 {
869         if (super->mpb)
870                 free(super->mpb);
871         free_imsm_disks(super);
872         free(super);
873 }
874
875
876 static void free_super_imsm(struct supertype *st)
877 {
878         struct intel_super *super = st->sb;
879
880         if (!super)
881                 return;
882
883         free_imsm(super);
884         st->sb = NULL;
885 }
886
887 static struct intel_super *alloc_super(int creating_imsm)
888 {
889         struct intel_super *super = malloc(sizeof(*super));
890
891         if (super) {
892                 memset(super, 0, sizeof(*super));
893                 super->creating_imsm = creating_imsm;
894                 super->creating_dev = -1;
895         }
896
897         return super;
898 }
899
900 #ifndef MDASSEMBLE
901 static int load_super_imsm_all(struct supertype *st, int fd, void **sbp,
902                                char *devname, int keep_fd)
903 {
904         struct mdinfo *sra;
905         struct intel_super *super;
906         struct mdinfo *sd, *best = NULL;
907         __u32 bestgen = 0;
908         __u32 gen;
909         char nm[20];
910         int dfd;
911         int rv;
912
913         /* check if this disk is a member of an active array */
914         sra = sysfs_read(fd, 0, GET_LEVEL|GET_VERSION|GET_DEVS|GET_STATE);
915         if (!sra)
916                 return 1;
917
918         if (sra->array.major_version != -1 ||
919             sra->array.minor_version != -2 ||
920             strcmp(sra->text_version, "imsm") != 0)
921                 return 1;
922
923         super = alloc_super(0);
924         if (!super)
925                 return 1;
926
927         /* find the most up to date disk in this array */
928         for (sd = sra->devs; sd; sd = sd->next) {
929                 sprintf(nm, "%d:%d", sd->disk.major, sd->disk.minor);
930                 dfd = dev_open(nm, keep_fd ? O_RDWR : O_RDONLY);
931                 if (!dfd) {
932                         free_imsm(super);
933                         return 2;
934                 }
935                 rv = load_imsm_mpb(dfd, super, NULL);
936                 if (!keep_fd)
937                         close(dfd);
938                 if (rv == 0) {
939                         gen = __le32_to_cpu(super->mpb->generation_num);
940                         if (!best || gen > bestgen) {
941                                 bestgen = gen;
942                                 best = sd;
943                         }
944                 } else {
945                         free_imsm(super);
946                         return 2;
947                 }
948         }
949
950         if (!best) {
951                 free_imsm(super);
952                 return 1;
953         }
954
955         /* load the most up to date anchor */
956         sprintf(nm, "%d:%d", best->disk.major, best->disk.minor);
957         dfd = dev_open(nm, O_RDONLY);
958         if (!dfd) {
959                 free_imsm(super);
960                 return 1;
961         }
962         rv = load_imsm_mpb(dfd, super, NULL);
963         close(dfd);
964         if (rv != 0) {
965                 free_imsm(super);
966                 return 2;
967         }
968
969         /* reset the disk list */
970         free_imsm_disks(super);
971
972         /* populate disk list */
973         for (sd = sra->devs ; sd ; sd = sd->next) {
974                 sprintf(nm, "%d:%d", sd->disk.major, sd->disk.minor);
975                 dfd = dev_open(nm, keep_fd? O_RDWR : O_RDONLY);
976                 if (!dfd) {
977                         free_imsm(super);
978                         return 2;
979                 }
980                 load_imsm_disk(dfd, super, NULL, keep_fd);
981                 if (!keep_fd)
982                         close(dfd);
983         }
984
985         if (st->subarray[0]) {
986                 /* FIXME */
987         }
988
989         *sbp = super;
990         if (st->ss == NULL) {
991                 st->ss = &super_imsm_container;
992                 st->minor_version = 0;
993                 st->max_devs = IMSM_MAX_DEVICES;
994                 st->container_dev = fd2devnum(fd);
995         }
996
997         return 0;
998 }
999 #endif
1000
1001 static int load_super_imsm(struct supertype *st, int fd, char *devname)
1002 {
1003         struct intel_super *super;
1004         int rv;
1005
1006 #ifndef MDASSEMBLE
1007         if (load_super_imsm_all(st, fd, &st->sb, devname, 1) == 0)
1008                 return 0;
1009 #endif
1010         if (st->subarray[0])
1011                 return 1; /* FIXME */
1012
1013         super = alloc_super(0);
1014         if (!super) {
1015                 fprintf(stderr,
1016                         Name ": malloc of %zu failed.\n",
1017                         sizeof(*super));
1018                 return 1;
1019         }
1020
1021         rv = load_imsm_mpb(fd, super, devname);
1022
1023         if (rv) {
1024                 if (devname)
1025                         fprintf(stderr,
1026                                 Name ": Failed to load all information "
1027                                 "sections on %s\n", devname);
1028                 free_imsm(super);
1029                 return rv;
1030         }
1031
1032         st->sb = super;
1033         if (st->ss == NULL) {
1034                 st->ss = &super_imsm;
1035                 st->minor_version = 0;
1036                 st->max_devs = IMSM_MAX_DEVICES;
1037         }
1038
1039         return 0;
1040 }
1041
1042 static int init_zero_imsm(struct supertype *st, mdu_array_info_t *info,
1043                           unsigned long long size, char *name,
1044                           char *homehost, int *uuid)
1045 {
1046         st->sb = NULL;
1047         return 0;
1048 }
1049
1050 static int init_super_imsm(struct supertype *st, mdu_array_info_t *info,
1051                            unsigned long long size, char *name,
1052                            char *homehost, int *uuid)
1053 {
1054         /* This is primarily called by Create when creating a new array.
1055          * We will then get add_to_super called for each component, and then
1056          * write_init_super called to write it out to each device.
1057          * For IMSM, Create can create on fresh devices or on a pre-existing
1058          * array.
1059          * To create on a pre-existing array a different method will be called.
1060          * This one is just for fresh drives.
1061          */
1062         struct intel_super *super;
1063         struct imsm_super *mpb;
1064         size_t mpb_size;
1065
1066         super = alloc_super(1);
1067         if (!super)
1068                 return 0;
1069         mpb_size = disks_to_mpb_size(info->nr_disks);
1070         mpb = malloc(mpb_size);
1071         if (!mpb) {
1072                 free(super);
1073                 return 0;
1074         }
1075         memset(mpb, 0, mpb_size); 
1076
1077         memcpy(mpb->sig, MPB_SIGNATURE, strlen(MPB_SIGNATURE));
1078         memcpy(mpb->sig + strlen(MPB_SIGNATURE), MPB_VERSION_RAID5,
1079                strlen(MPB_VERSION_RAID5)); 
1080         mpb->mpb_size = mpb_size;
1081
1082         super->mpb = mpb;
1083         st->sb = super;
1084         return 1;
1085 }
1086
1087 static int init_super_imsm_volume(struct supertype *st, mdu_array_info_t *info,
1088                                   unsigned long long size, char *name,
1089                                   char *homehost, int *uuid)
1090 {
1091         /* We are creating a volume inside a pre-existing container.
1092          * so st->sb is already set.
1093          */
1094         struct intel_super *super = st->sb;
1095         struct imsm_super *mpb = super->mpb;
1096         struct imsm_dev *dev;
1097         struct imsm_vol *vol;
1098         struct imsm_map *map;
1099         int idx = mpb->num_raid_devs;
1100         int i;
1101         unsigned long long array_blocks;
1102         unsigned long long sz;
1103         __u32 offset = 0;
1104
1105         if (mpb->num_raid_devs >= 2) {
1106                 fprintf(stderr, Name": This imsm-container already has the "
1107                         "maximum of 2 volumes\n");
1108                 return 0;
1109         }
1110
1111         super->creating_dev = idx;
1112         mpb->num_raid_devs++;
1113         dev = get_imsm_dev(mpb, idx);
1114         strncpy((char *) dev->volume, name, MAX_RAID_SERIAL_LEN);
1115         array_blocks = calc_array_size(info->level, info->raid_disks,
1116                                        info->layout, info->chunk_size,
1117                                        info->size*2);
1118         dev->size_low = __cpu_to_le32((__u32) array_blocks);
1119         dev->size_high = __cpu_to_le32((__u32) (array_blocks >> 32));
1120         dev->status = __cpu_to_le32(0);
1121         dev->reserved_blocks = __cpu_to_le32(0);
1122         vol = &dev->vol;
1123         vol->migr_state = 0;
1124         vol->migr_type = 0;
1125         vol->dirty = 0;
1126         for (i = 0; i < idx; i++) {
1127                 struct imsm_dev *prev = get_imsm_dev(mpb, i);
1128                 struct imsm_map *pmap = &prev->vol.map[0];
1129
1130                 offset += __le32_to_cpu(pmap->blocks_per_member);
1131                 offset += IMSM_RESERVED_SECTORS;
1132         }
1133         map = &vol->map[0];
1134         map->pba_of_lba0 = __cpu_to_le32(offset);
1135         sz = info->size * 2;
1136         map->blocks_per_member = __cpu_to_le32(sz);
1137         map->blocks_per_strip = __cpu_to_le16(info->chunk_size >> 9);
1138         map->num_data_stripes = __cpu_to_le32(sz / (info->chunk_size >> 9));
1139         map->map_state = info->level ? IMSM_T_STATE_UNINITIALIZED :
1140                                        IMSM_T_STATE_NORMAL;
1141         if (info->level == 10)
1142                 map->raid_level = 1;
1143         else
1144                 map->raid_level = info->level;
1145         map->num_members = info->raid_disks;
1146         for (i = 0; i < map->num_members; i++) {
1147                 /* initialized in add_to_super */
1148                 map->disk_ord_tbl[i] = __cpu_to_le32(0);
1149         }
1150
1151         return 1;
1152 }
1153
1154 static void add_to_super_imsm(struct supertype *st, mdu_disk_info_t *dk,
1155                               int fd, char *devname)
1156 {
1157         struct intel_super *super = st->sb;
1158         struct imsm_super *mpb = super->mpb;
1159         struct imsm_disk *disk;
1160         struct dl *dd;
1161         unsigned long long size;
1162         __u32 status, id;
1163         int rv;
1164         struct stat stb;
1165
1166         fstat(fd, &stb);
1167         dd = malloc(sizeof(*dd));
1168         if (!dd) {
1169                 fprintf(stderr,
1170                         Name ": malloc failed %s:%d.\n", __func__, __LINE__);
1171                 abort();
1172         }
1173         memset(dd, 0, sizeof(*dd));
1174         dd->major = major(stb.st_rdev);
1175         dd->minor = minor(stb.st_rdev);
1176         dd->index = dk->number;
1177         dd->devname = devname ? strdup(devname) : NULL;
1178         dd->next = super->disks;
1179         dd->fd = fd;
1180         rv = imsm_read_serial(fd, devname, dd->serial);
1181         if (rv) {
1182                 fprintf(stderr,
1183                         Name ": failed to retrieve scsi serial "
1184                         "using \'%s\' instead\n", devname);
1185                 strcpy((char *) dd->serial, devname);
1186         }
1187
1188         if (mpb->num_disks <= dk->number)
1189                 mpb->num_disks = dk->number + 1;
1190
1191         disk = get_imsm_disk(mpb, dk->number);
1192         get_dev_size(fd, NULL, &size);
1193         size /= 512;
1194         status = USABLE_DISK | SPARE_DISK;
1195         strcpy((char *) disk->serial, (char *) dd->serial);
1196         disk->total_blocks = __cpu_to_le32(size);
1197         disk->status = __cpu_to_le32(status);
1198         if (sysfs_disk_to_scsi_id(fd, &id) == 0)
1199                 disk->scsi_id = __cpu_to_le32(id);
1200         else
1201                 disk->scsi_id = __cpu_to_le32(0);
1202
1203         /* update the family number if we are creating a container */
1204         if (super->creating_imsm)
1205                 mpb->family_num = __cpu_to_le32(gen_imsm_checksum(mpb));
1206         
1207         super->disks = dd;
1208 }
1209
1210 static void add_to_super_imsm_volume(struct supertype *st, mdu_disk_info_t *dk,
1211                                      int fd, char *devname)
1212 {
1213         struct intel_super *super = st->sb;
1214         struct imsm_super *mpb = super->mpb;
1215         struct dl *dl;
1216         struct imsm_dev *dev;
1217         struct imsm_map *map;
1218         struct imsm_disk *disk;
1219         __u32 status;
1220
1221         if (super->creating_dev == -1) {
1222                 fprintf(stderr, Name ": no active raid device\n");
1223                 abort();
1224         }
1225
1226         dev = get_imsm_dev(mpb, super->creating_dev);
1227         map = &dev->vol.map[0];
1228
1229         for (dl = super->disks; dl ; dl = dl->next)
1230                 if (dl->major == dk->major &&
1231                     dl->minor == dk->minor)
1232                         break;
1233         if (!dl || ! (dk->state & (1<<MD_DISK_SYNC)))
1234                 return;
1235
1236         map->disk_ord_tbl[dk->number] = __cpu_to_le32(dl->index);
1237
1238         disk = get_imsm_disk(mpb, dl->index);
1239         status = CONFIGURED_DISK | USABLE_DISK;
1240         disk->status = __cpu_to_le32(status);
1241 }
1242
1243 static int store_imsm_mpb(int fd, struct intel_super *super);
1244
1245 static int write_super_imsm(struct intel_super *super, int doclose)
1246 {
1247         struct imsm_super *mpb = super->mpb;
1248         struct dl *d;
1249         __u32 generation;
1250         __u32 sum;
1251
1252         /* 'generation' is incremented everytime the metadata is written */
1253         generation = __le32_to_cpu(mpb->generation_num);
1254         generation++;
1255         mpb->generation_num = __cpu_to_le32(generation);
1256
1257         /* recalculate checksum */
1258         sum = gen_imsm_checksum(mpb);
1259         mpb->check_sum = __cpu_to_le32(sum);
1260
1261         for (d = super->disks; d ; d = d->next) {
1262                 if (store_imsm_mpb(d->fd, super)) {
1263                         fprintf(stderr, "%s: failed for device %d:%d %s\n",
1264                                 __func__, d->major, d->minor, strerror(errno));
1265                         return 0;
1266                 }
1267                 if (doclose) {
1268                         close(d->fd);
1269                         d->fd = -1;
1270                 }
1271         }
1272
1273         return 1;
1274 }
1275
1276 static int write_init_super_imsm(struct supertype *st)
1277 {
1278         return write_super_imsm(st->sb, 1);
1279 }
1280
1281 static int store_zero_imsm(struct supertype *st, int fd)
1282 {
1283         unsigned long long dsize;
1284         char buf[512];
1285
1286         get_dev_size(fd, NULL, &dsize);
1287
1288         /* first block is stored on second to last sector of the disk */
1289         if (lseek64(fd, dsize - (512 * 2), SEEK_SET) < 0)
1290                 return 1;
1291
1292         memset(buf, 0, sizeof(buf));
1293         if (write(fd, buf, sizeof(buf)) != sizeof(buf))
1294                 return 1;
1295         return 0;
1296 }
1297
1298 static int validate_geometry_imsm(struct supertype *st, int level, int layout,
1299                                   int raiddisks, int chunk, unsigned long long size,
1300                                   char *dev, unsigned long long *freesize)
1301 {
1302         int fd, cfd;
1303         struct mdinfo *sra;
1304
1305         /* if given unused devices create a container 
1306          * if given given devices in a container create a member volume
1307          */
1308         if (level == LEVEL_CONTAINER) {
1309                 st->ss = &super_imsm_container;
1310                 if (dev) {
1311                         /* validate the container, dev == NULL */
1312                         int rv = st->ss->validate_geometry(st, level, layout,
1313                                                            raiddisks, chunk,
1314                                                            size,
1315                                                            NULL, freesize);
1316                         if (rv)
1317                                 return rv;
1318                 }
1319                 return st->ss->validate_geometry(st, level, layout, raiddisks,
1320                                                  chunk, size, dev, freesize);
1321         }
1322         
1323         if (st->sb) {
1324                 /* creating in a given container */
1325                 st->ss = &super_imsm_volume;
1326                 if (dev) {
1327                         int rv = st->ss->validate_geometry(st, level, layout,
1328                                                            raiddisks, chunk,
1329                                                            size,
1330                                                            NULL, freesize);
1331                         if (rv)
1332                                 return rv;
1333                 }
1334                 return st->ss->validate_geometry(st, level, layout, raiddisks,
1335                                                  chunk, size, dev, freesize);
1336         }
1337
1338         /* limit creation to the following levels */
1339         if (!dev)
1340                 switch (level) {
1341                 case 0:
1342                 case 1:
1343                 case 10:
1344                 case 5:
1345                         break;
1346                 default:
1347                         return 1;
1348                 }
1349
1350         /* This device needs to be a device in an 'imsm' container */
1351         fd = open(dev, O_RDONLY|O_EXCL, 0);
1352         if (fd >= 0) {
1353                 fprintf(stderr,
1354                         Name ": Cannot create this array on device %s\n",
1355                         dev);
1356                 close(fd);
1357                 return 0;
1358         }
1359         if (errno != EBUSY || (fd = open(dev, O_RDONLY, 0)) < 0) {
1360                 fprintf(stderr, Name ": Cannot open %s: %s\n",
1361                         dev, strerror(errno));
1362                 return 0;
1363         }
1364         /* Well, it is in use by someone, maybe an 'imsm' container. */
1365         cfd = open_container(fd);
1366         if (cfd < 0) {
1367                 close(fd);
1368                 fprintf(stderr, Name ": Cannot use %s: It is busy\n",
1369                         dev);
1370                 return 0;
1371         }
1372         sra = sysfs_read(cfd, 0, GET_VERSION);
1373         close(fd);
1374         if (sra && sra->array.major_version == -1 &&
1375             strcmp(sra->text_version, "imsm") == 0) {
1376                 /* This is a member of a imsm container.  Load the container
1377                  * and try to create a volume
1378                  */
1379                 struct intel_super *super;
1380                 st->ss = &super_imsm_volume;
1381                 if (load_super_imsm_all(st, cfd, (void **) &super, NULL, 1) == 0) {
1382                         st->sb = super;
1383                         st->container_dev = fd2devnum(cfd);
1384                         close(cfd);
1385                         return st->ss->validate_geometry(st, level, layout,
1386                                                          raiddisks, chunk, size,
1387                                                          dev, freesize);
1388                 }
1389                 close(cfd);
1390         } else /* may belong to another container */
1391                 return 0;
1392
1393         return 1;
1394 }
1395
1396 static int validate_geometry_imsm_container(struct supertype *st, int level,
1397                                             int layout, int raiddisks, int chunk,
1398                                             unsigned long long size, char *dev,
1399                                             unsigned long long *freesize)
1400 {
1401         int fd;
1402         unsigned long long ldsize;
1403
1404         if (level != LEVEL_CONTAINER)
1405                 return 0;
1406         if (!dev)
1407                 return 1;
1408
1409         fd = open(dev, O_RDONLY|O_EXCL, 0);
1410         if (fd < 0) {
1411                 fprintf(stderr, Name ": Cannot open %s: %s\n",
1412                         dev, strerror(errno));
1413                 return 0;
1414         }
1415         if (!get_dev_size(fd, dev, &ldsize)) {
1416                 close(fd);
1417                 return 0;
1418         }
1419         close(fd);
1420
1421         *freesize = avail_size_imsm(st, ldsize >> 9);
1422
1423         return 1;
1424 }
1425
1426 /* validate_geometry_imsm_volume - lifted from validate_geometry_ddf_bvd 
1427  * FIX ME add ahci details
1428  */
1429 static int validate_geometry_imsm_volume(struct supertype *st, int level,
1430                                          int layout, int raiddisks, int chunk,
1431                                          unsigned long long size, char *dev,
1432                                          unsigned long long *freesize)
1433 {
1434         struct stat stb;
1435         struct intel_super *super = st->sb;
1436         struct dl *dl;
1437         unsigned long long pos = 0;
1438         unsigned long long maxsize;
1439         struct extent *e;
1440         int i;
1441
1442         if (level == LEVEL_CONTAINER)
1443                 return 0;
1444
1445         if (level == 1 && raiddisks > 2) {
1446                 fprintf(stderr, Name ": imsm does not support more than 2 "
1447                         "in a raid1 configuration\n");
1448                 return 0;
1449         }
1450
1451         /* We must have the container info already read in. */
1452         if (!super)
1453                 return 0;
1454
1455         if (!dev) {
1456                 /* General test:  make sure there is space for
1457                  * 'raiddisks' device extents of size 'size'.
1458                  */
1459                 unsigned long long minsize = size*2 /* convert to blocks */;
1460                 int dcnt = 0;
1461                 if (minsize == 0)
1462                         minsize = MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS;
1463                 for (dl = super->disks; dl ; dl = dl->next) {
1464                         int found = 0;
1465
1466                         i = 0;
1467                         e = get_extents(super, dl);
1468                         if (!e) continue;
1469                         do {
1470                                 unsigned long long esize;
1471                                 esize = e[i].start - pos;
1472                                 if (esize >= minsize)
1473                                         found = 1;
1474                                 pos = e[i].start + e[i].size;
1475                                 i++;
1476                         } while (e[i-1].size);
1477                         if (found)
1478                                 dcnt++;
1479                         free(e);
1480                 }
1481                 if (dcnt < raiddisks) {
1482                         fprintf(stderr, Name ": Not enough devices with space "
1483                                 "for this array (%d < %d)\n",
1484                                 dcnt, raiddisks);
1485                         return 0;
1486                 }
1487                 return 1;
1488         }
1489         /* This device must be a member of the set */
1490         if (stat(dev, &stb) < 0)
1491                 return 0;
1492         if ((S_IFMT & stb.st_mode) != S_IFBLK)
1493                 return 0;
1494         for (dl = super->disks ; dl ; dl = dl->next) {
1495                 if (dl->major == major(stb.st_rdev) &&
1496                     dl->minor == minor(stb.st_rdev))
1497                         break;
1498         }
1499         if (!dl) {
1500                 fprintf(stderr, Name ": %s is not in the same imsm set\n",
1501                         dev);
1502                 return 0;
1503         }
1504         e = get_extents(super, dl);
1505         maxsize = 0;
1506         i = 0;
1507         if (e) do {
1508                 unsigned long long esize;
1509                 esize = e[i].start - pos;
1510                 if (esize >= maxsize)
1511                         maxsize = esize;
1512                 pos = e[i].start + e[i].size;
1513                 i++;
1514         } while (e[i-1].size);
1515         *freesize = maxsize;
1516
1517         return 1;
1518 }
1519
1520 static struct mdinfo *container_content_imsm(struct supertype *st)
1521 {
1522         /* Given a container loaded by load_super_imsm_all,
1523          * extract information about all the arrays into
1524          * an mdinfo tree.
1525          *
1526          * For each imsm_dev create an mdinfo, fill it in,
1527          *  then look for matching devices in super->disks
1528          *  and create appropriate device mdinfo.
1529          */
1530         struct intel_super *super = st->sb;
1531         struct imsm_super *mpb = super->mpb;
1532         struct mdinfo *rest = NULL;
1533         int i;
1534
1535         for (i = 0; i < mpb->num_raid_devs; i++) {
1536                 struct imsm_dev *dev = get_imsm_dev(mpb, i);
1537                 struct imsm_vol *vol = &dev->vol;
1538                 struct imsm_map *map = vol->map;
1539                 struct mdinfo *this;
1540                 __u64 sz;
1541                 int slot;
1542
1543                 this = malloc(sizeof(*this));
1544                 memset(this, 0, sizeof(*this));
1545                 this->next = rest;
1546                 rest = this;
1547
1548                 this->array.level = get_imsm_raid_level(map);
1549                 this->array.raid_disks = map->num_members;
1550                 this->array.layout = imsm_level_to_layout(this->array.level);
1551                 this->array.md_minor = -1;
1552                 this->array.ctime = 0;
1553                 this->array.utime = 0;
1554                 this->array.chunk_size = __le16_to_cpu(map->blocks_per_strip) << 9;
1555                 this->array.state = !vol->dirty;
1556                 this->container_member = i;
1557                 if (map->map_state == IMSM_T_STATE_UNINITIALIZED || dev->vol.dirty)
1558                         this->resync_start = 0;
1559                 else
1560                         this->resync_start = ~0ULL;
1561
1562                 strncpy(this->name, (char *) dev->volume, MAX_RAID_SERIAL_LEN);
1563                 this->name[MAX_RAID_SERIAL_LEN] = 0;
1564
1565                 sprintf(this->text_version, "/%s/%d",
1566                         devnum2devname(st->container_dev),
1567                         this->container_member);
1568
1569                 memset(this->uuid, 0, sizeof(this->uuid));
1570
1571                 sz = __le32_to_cpu(dev->size_high);
1572                 sz <<= 32;
1573                 sz += __le32_to_cpu(dev->size_low);
1574                 this->component_size = sz;
1575                 this->array.size = this->component_size / 2;
1576
1577                 for (slot = 0 ; slot <  map->num_members; slot++) {
1578                         struct imsm_disk *disk;
1579                         struct mdinfo *info_d;
1580                         struct dl *d;
1581                         int idx;
1582                         __u32 s;
1583
1584                         idx = __le32_to_cpu(map->disk_ord_tbl[slot] & ~(0xff << 24));
1585                         for (d = super->disks; d ; d = d->next)
1586                                 if (d->index == idx)
1587                                         break;
1588
1589                         if (d == NULL)
1590                                 break; /* shouldn't this be continue ?? */
1591
1592                         info_d = malloc(sizeof(*info_d));
1593                         if (!info_d)
1594                                 break; /* ditto ?? */
1595                         memset(info_d, 0, sizeof(*info_d));
1596                         info_d->next = this->devs;
1597                         this->devs = info_d;
1598
1599                         disk = get_imsm_disk(mpb, idx);
1600                         s = __le32_to_cpu(disk->status);
1601
1602                         info_d->disk.number = d->index;
1603                         info_d->disk.major = d->major;
1604                         info_d->disk.minor = d->minor;
1605                         info_d->disk.raid_disk = slot;
1606                         info_d->disk.state  = s & CONFIGURED_DISK ? (1 << MD_DISK_ACTIVE) : 0;
1607                         info_d->disk.state |= s & FAILED_DISK ? (1 << MD_DISK_FAULTY) : 0;
1608                         info_d->disk.state |= s & USABLE_DISK ? (1 << MD_DISK_SYNC) : 0;
1609
1610                         this->array.working_disks++;
1611
1612                         info_d->events = __le32_to_cpu(mpb->generation_num);
1613                         info_d->data_offset = __le32_to_cpu(map->pba_of_lba0);
1614                         info_d->component_size = __le32_to_cpu(map->blocks_per_member);
1615                         if (d->devname)
1616                                 strcpy(info_d->name, d->devname);
1617                 }
1618         }
1619
1620         return rest;
1621 }
1622
1623
1624 static int imsm_open_new(struct supertype *c, struct active_array *a,
1625                          char *inst)
1626 {
1627         dprintf("imsm: open_new %s\n", inst);
1628         a->info.container_member = atoi(inst);
1629         return 0;
1630 }
1631
1632 static __u8 imsm_check_degraded(struct imsm_super *mpb, int n, int failed)
1633 {
1634         struct imsm_dev *dev = get_imsm_dev(mpb, n);
1635         struct imsm_map *map = dev->vol.map;
1636
1637         if (!failed)
1638                 return map->map_state;
1639
1640         switch (get_imsm_raid_level(map)) {
1641         case 0:
1642                 return IMSM_T_STATE_FAILED;
1643                 break;
1644         case 1:
1645                 if (failed < map->num_members)
1646                         return IMSM_T_STATE_DEGRADED;
1647                 else
1648                         return IMSM_T_STATE_FAILED;
1649                 break;
1650         case 10:
1651         {
1652                 /**
1653                  * check to see if any mirrors have failed,
1654                  * otherwise we are degraded
1655                  */
1656                 int device_per_mirror = 2; /* FIXME is this always the case?
1657                                             * and are they always adjacent?
1658                                             */
1659                 int failed = 0;
1660                 int i;
1661
1662                 for (i = 0; i < map->num_members; i++) {
1663                         int idx = get_imsm_disk_idx(map, i);
1664                         struct imsm_disk *disk = get_imsm_disk(mpb, idx);
1665
1666                         if (__le32_to_cpu(disk->status) & FAILED_DISK)
1667                                 failed++;
1668
1669                         if (failed >= device_per_mirror)
1670                                 return IMSM_T_STATE_FAILED;
1671
1672                         /* reset 'failed' for next mirror set */
1673                         if (!((i + 1) % device_per_mirror))
1674                                 failed = 0;
1675                 }
1676
1677                 return IMSM_T_STATE_DEGRADED;
1678         }
1679         case 5:
1680                 if (failed < 2)
1681                         return IMSM_T_STATE_DEGRADED;
1682                 else
1683                         return IMSM_T_STATE_FAILED;
1684                 break;
1685         default:
1686                 break;
1687         }
1688
1689         return map->map_state;
1690 }
1691
1692 static int imsm_count_failed(struct imsm_super *mpb, struct imsm_map *map)
1693 {
1694         int i;
1695         int failed = 0;
1696         struct imsm_disk *disk;
1697
1698         for (i = 0; i < map->num_members; i++) {
1699                 int idx = get_imsm_disk_idx(map, i);
1700
1701                 disk = get_imsm_disk(mpb, idx);
1702                 if (__le32_to_cpu(disk->status) & FAILED_DISK)
1703                         failed++;
1704         }
1705
1706         return failed;
1707 }
1708
1709 static void imsm_set_array_state(struct active_array *a, int consistent)
1710 {
1711         int inst = a->info.container_member;
1712         struct intel_super *super = a->container->sb;
1713         struct imsm_dev *dev = get_imsm_dev(super->mpb, inst);
1714         struct imsm_map *map = &dev->vol.map[0];
1715         int dirty = !consistent;
1716         int failed;
1717         __u8 map_state;
1718
1719         if (a->resync_start == ~0ULL) {
1720                 failed = imsm_count_failed(super->mpb, map);
1721                 map_state = imsm_check_degraded(super->mpb, inst, failed);
1722                 if (!failed)
1723                         map_state = IMSM_T_STATE_NORMAL;
1724                 if (map->map_state != map_state) {
1725                         dprintf("imsm: map_state %d: %d\n",
1726                                 inst, map_state);
1727                         map->map_state = map_state;
1728                         super->updates_pending++;
1729                 }
1730         }
1731
1732         if (dev->vol.dirty != dirty) {
1733                 dprintf("imsm: mark '%s' (%llu)\n",
1734                         dirty?"dirty":"clean", a->resync_start);
1735
1736                 dev->vol.dirty = dirty;
1737                 super->updates_pending++;
1738         }
1739 }
1740
1741 static void imsm_set_disk(struct active_array *a, int n, int state)
1742 {
1743         int inst = a->info.container_member;
1744         struct intel_super *super = a->container->sb;
1745         struct imsm_dev *dev = get_imsm_dev(super->mpb, inst);
1746         struct imsm_map *map = dev->vol.map;
1747         struct imsm_disk *disk;
1748         __u32 status;
1749         int failed = 0;
1750         int new_failure = 0;
1751
1752         if (n > map->num_members)
1753                 fprintf(stderr, "imsm: set_disk %d out of range 0..%d\n",
1754                         n, map->num_members - 1);
1755
1756         if (n < 0)
1757                 return;
1758
1759         dprintf("imsm: set_disk %d:%x\n", n, state);
1760
1761         disk = get_imsm_disk(super->mpb, get_imsm_disk_idx(map, n));
1762
1763         /* check if we have seen this failure before */
1764         status = __le32_to_cpu(disk->status);
1765         if ((state & DS_FAULTY) && !(status & FAILED_DISK)) {
1766                 status |= FAILED_DISK;
1767                 disk->status = __cpu_to_le32(status);
1768                 new_failure = 1;
1769         }
1770
1771         /**
1772          * the number of failures have changed, count up 'failed' to determine
1773          * degraded / failed status
1774          */
1775         if (new_failure && map->map_state != IMSM_T_STATE_FAILED)
1776                 failed = imsm_count_failed(super->mpb, map);
1777
1778         if (failed)
1779                 map->map_state = imsm_check_degraded(super->mpb, inst, failed);
1780
1781         if (new_failure)
1782                 super->updates_pending++;
1783 }
1784
1785 static int store_imsm_mpb(int fd, struct intel_super *super)
1786 {
1787         struct imsm_super *mpb = super->mpb;
1788         __u32 mpb_size = __le32_to_cpu(mpb->mpb_size);
1789         unsigned long long dsize;
1790         unsigned long long sectors;
1791
1792         get_dev_size(fd, NULL, &dsize);
1793
1794         if (mpb_size > 512) {
1795                 /* -1 to account for anchor */
1796                 sectors = mpb_sectors(mpb) - 1;
1797
1798                 /* write the extended mpb to the sectors preceeding the anchor */
1799                 if (lseek64(fd, dsize - (512 * (2 + sectors)), SEEK_SET) < 0)
1800                         return 1;
1801
1802                 if (write(fd, super->buf + 512, mpb_size - 512) != mpb_size - 512)
1803                         return 1;
1804         }
1805
1806         /* first block is stored on second to last sector of the disk */
1807         if (lseek64(fd, dsize - (512 * 2), SEEK_SET) < 0)
1808                 return 1;
1809
1810         if (write(fd, super->buf, 512) != 512)
1811                 return 1;
1812
1813         fsync(fd);
1814
1815         return 0;
1816 }
1817
1818 static void imsm_sync_metadata(struct supertype *container)
1819 {
1820         struct intel_super *super = container->sb;
1821
1822         if (!super->updates_pending)
1823                 return;
1824
1825         write_super_imsm(super, 0);
1826
1827         super->updates_pending = 0;
1828 }
1829
1830 struct superswitch super_imsm = {
1831 #ifndef MDASSEMBLE
1832         .examine_super  = examine_super_imsm,
1833         .brief_examine_super = brief_examine_super_imsm,
1834         .detail_super   = detail_super_imsm,
1835         .brief_detail_super = brief_detail_super_imsm,
1836 #endif
1837         .match_home     = match_home_imsm,
1838         .uuid_from_super= uuid_from_super_imsm,
1839         .getinfo_super  = getinfo_super_imsm,
1840         .update_super   = update_super_imsm,
1841
1842         .avail_size     = avail_size_imsm,
1843
1844         .compare_super  = compare_super_imsm,
1845
1846         .load_super     = load_super_imsm,
1847         .init_super     = init_zero_imsm,
1848         .store_super    = store_zero_imsm,
1849         .free_super     = free_super_imsm,
1850         .match_metadata_desc = match_metadata_desc_imsm,
1851
1852         .validate_geometry = validate_geometry_imsm,
1853         .external       = 1,
1854
1855 /* for mdmon */
1856         .open_new       = imsm_open_new,
1857         .load_super     = load_super_imsm,
1858         .set_array_state= imsm_set_array_state,
1859         .set_disk       = imsm_set_disk,
1860         .sync_metadata  = imsm_sync_metadata,
1861 };
1862
1863 /* super_imsm_container is set by validate_geometry_imsm when given a
1864  * device that is not part of any array
1865  */
1866 struct superswitch super_imsm_container = {
1867
1868         .validate_geometry = validate_geometry_imsm_container,
1869         .init_super     = init_super_imsm,
1870         .add_to_super   = add_to_super_imsm,
1871         .write_init_super = write_init_super_imsm,
1872         .getinfo_super  = getinfo_super_imsm,
1873         .load_super     = load_super_imsm,
1874
1875 #ifndef MDASSEMBLE
1876         .examine_super  = examine_super_imsm,
1877         .brief_examine_super = brief_examine_super_imsm,
1878         .detail_super   = detail_super_imsm,
1879         .brief_detail_super = brief_detail_super_imsm,
1880 #endif
1881
1882         .free_super     = free_super_imsm,
1883
1884         .container_content = container_content_imsm,
1885
1886         .external       = 1,
1887 };
1888
1889 static struct superswitch super_imsm_volume = {
1890         .update_super   = update_super_imsm,
1891         .init_super     = init_super_imsm_volume,
1892         .add_to_super   = add_to_super_imsm_volume,
1893         .getinfo_super  = getinfo_super_imsm_volume,
1894         .write_init_super = write_init_super_imsm,
1895
1896         .load_super     = load_super_imsm,
1897         .free_super     = free_super_imsm,
1898         .match_metadata_desc = match_metadata_desc_imsm_volume,
1899
1900
1901         .validate_geometry = validate_geometry_imsm_volume,
1902         .external       = 2,
1903 };