]> git.neil.brown.name Git - mdadm.git/blob - super-intel.c
20144fe78918724507b474e0f8f533bfa84389c6
[mdadm.git] / super-intel.c
1 /*
2  * mdadm - Intel(R) Matrix Storage Manager Support
3  *
4  * Copyright (C) 2002-2008 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 #define HAVE_STDINT_H 1
21 #include "mdadm.h"
22 #include "mdmon.h"
23 #include "sha1.h"
24 #include "platform-intel.h"
25 #include <values.h>
26 #include <scsi/sg.h>
27 #include <ctype.h>
28 #include <dirent.h>
29
30 /* MPB == Metadata Parameter Block */
31 #define MPB_SIGNATURE "Intel Raid ISM Cfg Sig. "
32 #define MPB_SIG_LEN (strlen(MPB_SIGNATURE))
33 #define MPB_VERSION_RAID0 "1.0.00"
34 #define MPB_VERSION_RAID1 "1.1.00"
35 #define MPB_VERSION_MANY_VOLUMES_PER_ARRAY "1.2.00"
36 #define MPB_VERSION_3OR4_DISK_ARRAY "1.2.01"
37 #define MPB_VERSION_RAID5 "1.2.02"
38 #define MPB_VERSION_5OR6_DISK_ARRAY "1.2.04"
39 #define MPB_VERSION_CNG "1.2.06"
40 #define MPB_VERSION_ATTRIBS "1.3.00"
41 #define MAX_SIGNATURE_LENGTH  32
42 #define MAX_RAID_SERIAL_LEN   16
43
44 /* supports RAID0 */
45 #define MPB_ATTRIB_RAID0                __cpu_to_le32(0x00000001)
46 /* supports RAID1 */
47 #define MPB_ATTRIB_RAID1                __cpu_to_le32(0x00000002)
48 /* supports RAID10 */
49 #define MPB_ATTRIB_RAID10               __cpu_to_le32(0x00000004)
50 /* supports RAID1E */
51 #define MPB_ATTRIB_RAID1E               __cpu_to_le32(0x00000008)
52 /* supports RAID5 */
53 #define MPB_ATTRIB_RAID5                __cpu_to_le32(0x00000010)
54 /* supports RAID CNG */
55 #define MPB_ATTRIB_RAIDCNG              __cpu_to_le32(0x00000020)
56 /* supports expanded stripe sizes of  256K, 512K and 1MB */
57 #define MPB_ATTRIB_EXP_STRIPE_SIZE      __cpu_to_le32(0x00000040)
58
59 /* The OROM Support RST Caching of Volumes */
60 #define MPB_ATTRIB_NVM                  __cpu_to_le32(0x02000000)
61 /* The OROM supports creating disks greater than 2TB */
62 #define MPB_ATTRIB_2TB_DISK             __cpu_to_le32(0x04000000)
63 /* The OROM supports Bad Block Management */
64 #define MPB_ATTRIB_BBM                  __cpu_to_le32(0x08000000)
65
66 /* THe OROM Supports NVM Caching of Volumes */
67 #define MPB_ATTRIB_NEVER_USE2           __cpu_to_le32(0x10000000)
68 /* The OROM supports creating volumes greater than 2TB */
69 #define MPB_ATTRIB_2TB                  __cpu_to_le32(0x20000000)
70 /* originally for PMP, now it's wasted b/c. Never use this bit! */
71 #define MPB_ATTRIB_NEVER_USE            __cpu_to_le32(0x40000000)
72 /* Verify MPB contents against checksum after reading MPB */
73 #define MPB_ATTRIB_CHECKSUM_VERIFY      __cpu_to_le32(0x80000000)
74
75 /* Define all supported attributes that have to be accepted by mdadm
76  */
77 #define MPB_ATTRIB_SUPPORTED           (MPB_ATTRIB_CHECKSUM_VERIFY | \
78                                         MPB_ATTRIB_2TB             | \
79                                         MPB_ATTRIB_2TB_DISK        | \
80                                         MPB_ATTRIB_RAID0           | \
81                                         MPB_ATTRIB_RAID1           | \
82                                         MPB_ATTRIB_RAID10          | \
83                                         MPB_ATTRIB_RAID5           | \
84                                         MPB_ATTRIB_EXP_STRIPE_SIZE | \
85                                         MPB_ATTRIB_BBM)
86
87 /* Define attributes that are unused but not harmful */
88 #define MPB_ATTRIB_IGNORED              (MPB_ATTRIB_NEVER_USE)
89
90 #define MPB_SECTOR_CNT 2210
91 #define IMSM_RESERVED_SECTORS 4096
92 #define NUM_BLOCKS_DIRTY_STRIPE_REGION 2056
93 #define SECT_PER_MB_SHIFT 11
94 #define MAX_SECTOR_SIZE 4096
95
96 /* Disk configuration info. */
97 #define IMSM_MAX_DEVICES 255
98 struct imsm_disk {
99         __u8 serial[MAX_RAID_SERIAL_LEN];/* 0xD8 - 0xE7 ascii serial number */
100         __u32 total_blocks_lo;           /* 0xE8 - 0xEB total blocks lo */
101         __u32 scsi_id;                   /* 0xEC - 0xEF scsi ID */
102 #define SPARE_DISK      __cpu_to_le32(0x01)  /* Spare */
103 #define CONFIGURED_DISK __cpu_to_le32(0x02)  /* Member of some RaidDev */
104 #define FAILED_DISK     __cpu_to_le32(0x04)  /* Permanent failure */
105         __u32 status;                    /* 0xF0 - 0xF3 */
106         __u32 owner_cfg_num; /* which config 0,1,2... owns this disk */
107         __u32 total_blocks_hi;           /* 0xF4 - 0xF5 total blocks hi */
108 #define IMSM_DISK_FILLERS       3
109         __u32 filler[IMSM_DISK_FILLERS]; /* 0xF5 - 0x107 MPB_DISK_FILLERS for future expansion */
110 };
111
112 /* map selector for map managment
113  */
114 #define MAP_0           0
115 #define MAP_1           1
116 #define MAP_X           -1
117
118 /* RAID map configuration infos. */
119 struct imsm_map {
120         __u32 pba_of_lba0_lo;   /* start address of partition */
121         __u32 blocks_per_member_lo;/* blocks per member */
122         __u32 num_data_stripes_lo;      /* number of data stripes */
123         __u16 blocks_per_strip;
124         __u8  map_state;        /* Normal, Uninitialized, Degraded, Failed */
125 #define IMSM_T_STATE_NORMAL 0
126 #define IMSM_T_STATE_UNINITIALIZED 1
127 #define IMSM_T_STATE_DEGRADED 2
128 #define IMSM_T_STATE_FAILED 3
129         __u8  raid_level;
130 #define IMSM_T_RAID0 0
131 #define IMSM_T_RAID1 1
132 #define IMSM_T_RAID5 5          /* since metadata version 1.2.02 ? */
133         __u8  num_members;      /* number of member disks */
134         __u8  num_domains;      /* number of parity domains */
135         __u8  failed_disk_num;  /* valid only when state is degraded */
136         __u8  ddf;
137         __u32 pba_of_lba0_hi;
138         __u32 blocks_per_member_hi;
139         __u32 num_data_stripes_hi;
140         __u32 filler[4];        /* expansion area */
141 #define IMSM_ORD_REBUILD (1 << 24)
142         __u32 disk_ord_tbl[1];  /* disk_ord_tbl[num_members],
143                                  * top byte contains some flags
144                                  */
145 } __attribute__ ((packed));
146
147 struct imsm_vol {
148         __u32 curr_migr_unit;
149         __u32 checkpoint_id;    /* id to access curr_migr_unit */
150         __u8  migr_state;       /* Normal or Migrating */
151 #define MIGR_INIT 0
152 #define MIGR_REBUILD 1
153 #define MIGR_VERIFY 2 /* analagous to echo check > sync_action */
154 #define MIGR_GEN_MIGR 3
155 #define MIGR_STATE_CHANGE 4
156 #define MIGR_REPAIR 5
157         __u8  migr_type;        /* Initializing, Rebuilding, ... */
158         __u8  dirty;
159         __u8  fs_state;         /* fast-sync state for CnG (0xff == disabled) */
160         __u16 verify_errors;    /* number of mismatches */
161         __u16 bad_blocks;       /* number of bad blocks during verify */
162         __u32 filler[4];
163         struct imsm_map map[1];
164         /* here comes another one if migr_state */
165 } __attribute__ ((packed));
166
167 struct imsm_dev {
168         __u8  volume[MAX_RAID_SERIAL_LEN];
169         __u32 size_low;
170         __u32 size_high;
171 #define DEV_BOOTABLE            __cpu_to_le32(0x01)
172 #define DEV_BOOT_DEVICE         __cpu_to_le32(0x02)
173 #define DEV_READ_COALESCING     __cpu_to_le32(0x04)
174 #define DEV_WRITE_COALESCING    __cpu_to_le32(0x08)
175 #define DEV_LAST_SHUTDOWN_DIRTY __cpu_to_le32(0x10)
176 #define DEV_HIDDEN_AT_BOOT      __cpu_to_le32(0x20)
177 #define DEV_CURRENTLY_HIDDEN    __cpu_to_le32(0x40)
178 #define DEV_VERIFY_AND_FIX      __cpu_to_le32(0x80)
179 #define DEV_MAP_STATE_UNINIT    __cpu_to_le32(0x100)
180 #define DEV_NO_AUTO_RECOVERY    __cpu_to_le32(0x200)
181 #define DEV_CLONE_N_GO          __cpu_to_le32(0x400)
182 #define DEV_CLONE_MAN_SYNC      __cpu_to_le32(0x800)
183 #define DEV_CNG_MASTER_DISK_NUM __cpu_to_le32(0x1000)
184         __u32 status;   /* Persistent RaidDev status */
185         __u32 reserved_blocks; /* Reserved blocks at beginning of volume */
186         __u8  migr_priority;
187         __u8  num_sub_vols;
188         __u8  tid;
189         __u8  cng_master_disk;
190         __u16 cache_policy;
191         __u8  cng_state;
192         __u8  cng_sub_state;
193 #define IMSM_DEV_FILLERS 10
194         __u32 filler[IMSM_DEV_FILLERS];
195         struct imsm_vol vol;
196 } __attribute__ ((packed));
197
198 struct imsm_super {
199         __u8 sig[MAX_SIGNATURE_LENGTH]; /* 0x00 - 0x1F */
200         __u32 check_sum;                /* 0x20 - 0x23 MPB Checksum */
201         __u32 mpb_size;                 /* 0x24 - 0x27 Size of MPB */
202         __u32 family_num;               /* 0x28 - 0x2B Checksum from first time this config was written */
203         __u32 generation_num;           /* 0x2C - 0x2F Incremented each time this array's MPB is written */
204         __u32 error_log_size;           /* 0x30 - 0x33 in bytes */
205         __u32 attributes;               /* 0x34 - 0x37 */
206         __u8 num_disks;                 /* 0x38 Number of configured disks */
207         __u8 num_raid_devs;             /* 0x39 Number of configured volumes */
208         __u8 error_log_pos;             /* 0x3A  */
209         __u8 fill[1];                   /* 0x3B */
210         __u32 cache_size;               /* 0x3c - 0x40 in mb */
211         __u32 orig_family_num;          /* 0x40 - 0x43 original family num */
212         __u32 pwr_cycle_count;          /* 0x44 - 0x47 simulated power cycle count for array */
213         __u32 bbm_log_size;             /* 0x48 - 0x4B - size of bad Block Mgmt Log in bytes */
214 #define IMSM_FILLERS 35
215         __u32 filler[IMSM_FILLERS];     /* 0x4C - 0xD7 RAID_MPB_FILLERS */
216         struct imsm_disk disk[1];       /* 0xD8 diskTbl[numDisks] */
217         /* here comes imsm_dev[num_raid_devs] */
218         /* here comes BBM logs */
219 } __attribute__ ((packed));
220
221 #define BBM_LOG_MAX_ENTRIES 254
222 #define BBM_LOG_MAX_LBA_ENTRY_VAL 256           /* Represents 256 LBAs */
223 #define BBM_LOG_SIGNATURE 0xabadb10c
224
225 struct bbm_log_block_addr {
226         __u16 w1;
227         __u32 dw1;
228 } __attribute__ ((__packed__));
229
230 struct bbm_log_entry {
231         __u8 marked_count;              /* Number of blocks marked - 1 */
232         __u8 disk_ordinal;              /* Disk entry within the imsm_super */
233         struct bbm_log_block_addr defective_block_start;
234 } __attribute__ ((__packed__));
235
236 struct bbm_log {
237         __u32 signature; /* 0xABADB10C */
238         __u32 entry_count;
239         struct bbm_log_entry marked_block_entries[BBM_LOG_MAX_ENTRIES];
240 } __attribute__ ((__packed__));
241
242 #ifndef MDASSEMBLE
243 static char *map_state_str[] = { "normal", "uninitialized", "degraded", "failed" };
244 #endif
245
246 #define RAID_DISK_RESERVED_BLOCKS_IMSM_HI 2209
247
248 #define GEN_MIGR_AREA_SIZE 2048 /* General Migration Copy Area size in blocks */
249
250 #define MIGR_REC_BUF_SECTORS 1 /* size of migr_record i/o buffer in sectors */
251 #define MIGR_REC_SECTOR_POSITION 1 /* migr_record position offset on disk,
252                                * MIGR_REC_BUF_SECTORS <= MIGR_REC_SECTOR_POS
253                                */
254
255 #define UNIT_SRC_NORMAL     0   /* Source data for curr_migr_unit must
256                                  *  be recovered using srcMap */
257 #define UNIT_SRC_IN_CP_AREA 1   /* Source data for curr_migr_unit has
258                                  *  already been migrated and must
259                                  *  be recovered from checkpoint area */
260 struct migr_record {
261         __u32 rec_status;           /* Status used to determine how to restart
262                                      * migration in case it aborts
263                                      * in some fashion */
264         __u32 curr_migr_unit;       /* 0..numMigrUnits-1 */
265         __u32 family_num;           /* Family number of MPB
266                                      * containing the RaidDev
267                                      * that is migrating */
268         __u32 ascending_migr;       /* True if migrating in increasing
269                                      * order of lbas */
270         __u32 blocks_per_unit;      /* Num disk blocks per unit of operation */
271         __u32 dest_depth_per_unit;  /* Num member blocks each destMap
272                                      * member disk
273                                      * advances per unit-of-operation */
274         __u32 ckpt_area_pba;        /* Pba of first block of ckpt copy area */
275         __u32 dest_1st_member_lba;  /* First member lba on first
276                                      * stripe of destination */
277         __u32 num_migr_units;       /* Total num migration units-of-op */
278         __u32 post_migr_vol_cap;    /* Size of volume after
279                                      * migration completes */
280         __u32 post_migr_vol_cap_hi; /* Expansion space for LBA64 */
281         __u32 ckpt_read_disk_num;   /* Which member disk in destSubMap[0] the
282                                      * migration ckpt record was read from
283                                      * (for recovered migrations) */
284 } __attribute__ ((__packed__));
285
286 struct md_list {
287         /* usage marker:
288          *  1: load metadata
289          *  2: metadata does not match
290          *  4: already checked
291          */
292         int   used;
293         char  *devname;
294         int   found;
295         int   container;
296         dev_t st_rdev;
297         struct md_list *next;
298 };
299
300 #define pr_vrb(fmt, arg...) (void) (verbose && pr_err(fmt, ##arg))
301
302 static __u8 migr_type(struct imsm_dev *dev)
303 {
304         if (dev->vol.migr_type == MIGR_VERIFY &&
305             dev->status & DEV_VERIFY_AND_FIX)
306                 return MIGR_REPAIR;
307         else
308                 return dev->vol.migr_type;
309 }
310
311 static void set_migr_type(struct imsm_dev *dev, __u8 migr_type)
312 {
313         /* for compatibility with older oroms convert MIGR_REPAIR, into
314          * MIGR_VERIFY w/ DEV_VERIFY_AND_FIX status
315          */
316         if (migr_type == MIGR_REPAIR) {
317                 dev->vol.migr_type = MIGR_VERIFY;
318                 dev->status |= DEV_VERIFY_AND_FIX;
319         } else {
320                 dev->vol.migr_type = migr_type;
321                 dev->status &= ~DEV_VERIFY_AND_FIX;
322         }
323 }
324
325 static unsigned int sector_count(__u32 bytes, unsigned int sector_size)
326 {
327         return ROUND_UP(bytes, sector_size) / sector_size;
328 }
329
330 static unsigned int mpb_sectors(struct imsm_super *mpb,
331                                         unsigned int sector_size)
332 {
333         return sector_count(__le32_to_cpu(mpb->mpb_size), sector_size);
334 }
335
336 struct intel_dev {
337         struct imsm_dev *dev;
338         struct intel_dev *next;
339         unsigned index;
340 };
341
342 struct intel_hba {
343         enum sys_dev_type type;
344         char *path;
345         char *pci_id;
346         struct intel_hba *next;
347 };
348
349 enum action {
350         DISK_REMOVE = 1,
351         DISK_ADD
352 };
353 /* internal representation of IMSM metadata */
354 struct intel_super {
355         union {
356                 void *buf; /* O_DIRECT buffer for reading/writing metadata */
357                 struct imsm_super *anchor; /* immovable parameters */
358         };
359         union {
360                 void *migr_rec_buf; /* buffer for I/O operations */
361                 struct migr_record *migr_rec; /* migration record */
362         };
363         int clean_migration_record_by_mdmon; /* when reshape is switched to next
364                 array, it indicates that mdmon is allowed to clean migration
365                 record */
366         size_t len; /* size of the 'buf' allocation */
367         size_t extra_space; /* extra space in 'buf' that is not used yet */
368         void *next_buf; /* for realloc'ing buf from the manager */
369         size_t next_len;
370         int updates_pending; /* count of pending updates for mdmon */
371         int current_vol; /* index of raid device undergoing creation */
372         unsigned long long create_offset; /* common start for 'current_vol' */
373         __u32 random; /* random data for seeding new family numbers */
374         struct intel_dev *devlist;
375         unsigned int sector_size; /* sector size of used member drives */
376         struct dl {
377                 struct dl *next;
378                 int index;
379                 __u8 serial[MAX_RAID_SERIAL_LEN];
380                 int major, minor;
381                 char *devname;
382                 struct imsm_disk disk;
383                 int fd;
384                 int extent_cnt;
385                 struct extent *e; /* for determining freespace @ create */
386                 int raiddisk; /* slot to fill in autolayout */
387                 enum action action;
388         } *disks, *current_disk;
389         struct dl *disk_mgmt_list; /* list of disks to add/remove while mdmon
390                                       active */
391         struct dl *missing; /* disks removed while we weren't looking */
392         struct bbm_log *bbm_log;
393         struct intel_hba *hba; /* device path of the raid controller for this metadata */
394         const struct imsm_orom *orom; /* platform firmware support */
395         struct intel_super *next; /* (temp) list for disambiguating family_num */
396 };
397
398 struct intel_disk {
399         struct imsm_disk disk;
400         #define IMSM_UNKNOWN_OWNER (-1)
401         int owner;
402         struct intel_disk *next;
403 };
404
405 struct extent {
406         unsigned long long start, size;
407 };
408
409 /* definitions of reshape process types */
410 enum imsm_reshape_type {
411         CH_TAKEOVER,
412         CH_MIGRATION,
413         CH_ARRAY_SIZE,
414 };
415
416 /* definition of messages passed to imsm_process_update */
417 enum imsm_update_type {
418         update_activate_spare,
419         update_create_array,
420         update_kill_array,
421         update_rename_array,
422         update_add_remove_disk,
423         update_reshape_container_disks,
424         update_reshape_migration,
425         update_takeover,
426         update_general_migration_checkpoint,
427         update_size_change,
428         update_prealloc_badblocks_mem,
429 };
430
431 struct imsm_update_activate_spare {
432         enum imsm_update_type type;
433         struct dl *dl;
434         int slot;
435         int array;
436         struct imsm_update_activate_spare *next;
437 };
438
439 struct geo_params {
440         char devnm[32];
441         char *dev_name;
442         unsigned long long size;
443         int level;
444         int layout;
445         int chunksize;
446         int raid_disks;
447 };
448
449 enum takeover_direction {
450         R10_TO_R0,
451         R0_TO_R10
452 };
453 struct imsm_update_takeover {
454         enum imsm_update_type type;
455         int subarray;
456         enum takeover_direction direction;
457 };
458
459 struct imsm_update_reshape {
460         enum imsm_update_type type;
461         int old_raid_disks;
462         int new_raid_disks;
463
464         int new_disks[1]; /* new_raid_disks - old_raid_disks makedev number */
465 };
466
467 struct imsm_update_reshape_migration {
468         enum imsm_update_type type;
469         int old_raid_disks;
470         int new_raid_disks;
471         /* fields for array migration changes
472          */
473         int subdev;
474         int new_level;
475         int new_layout;
476         int new_chunksize;
477
478         int new_disks[1]; /* new_raid_disks - old_raid_disks makedev number */
479 };
480
481 struct imsm_update_size_change {
482         enum imsm_update_type type;
483         int subdev;
484         long long new_size;
485 };
486
487 struct imsm_update_general_migration_checkpoint {
488         enum imsm_update_type type;
489         __u32 curr_migr_unit;
490 };
491
492 struct disk_info {
493         __u8 serial[MAX_RAID_SERIAL_LEN];
494 };
495
496 struct imsm_update_create_array {
497         enum imsm_update_type type;
498         int dev_idx;
499         struct imsm_dev dev;
500 };
501
502 struct imsm_update_kill_array {
503         enum imsm_update_type type;
504         int dev_idx;
505 };
506
507 struct imsm_update_rename_array {
508         enum imsm_update_type type;
509         __u8 name[MAX_RAID_SERIAL_LEN];
510         int dev_idx;
511 };
512
513 struct imsm_update_add_remove_disk {
514         enum imsm_update_type type;
515 };
516
517 struct imsm_update_prealloc_bb_mem {
518         enum imsm_update_type type;
519 };
520
521 static const char *_sys_dev_type[] = {
522         [SYS_DEV_UNKNOWN] = "Unknown",
523         [SYS_DEV_SAS] = "SAS",
524         [SYS_DEV_SATA] = "SATA",
525         [SYS_DEV_NVME] = "NVMe",
526         [SYS_DEV_VMD] = "VMD"
527 };
528
529 const char *get_sys_dev_type(enum sys_dev_type type)
530 {
531         if (type >= SYS_DEV_MAX)
532                 type = SYS_DEV_UNKNOWN;
533
534         return _sys_dev_type[type];
535 }
536
537 static struct intel_hba * alloc_intel_hba(struct sys_dev *device)
538 {
539         struct intel_hba *result = xmalloc(sizeof(*result));
540
541         result->type = device->type;
542         result->path = xstrdup(device->path);
543         result->next = NULL;
544         if (result->path && (result->pci_id = strrchr(result->path, '/')) != NULL)
545                 result->pci_id++;
546
547         return result;
548 }
549
550 static struct intel_hba * find_intel_hba(struct intel_hba *hba, struct sys_dev *device)
551 {
552         struct intel_hba *result;
553
554         for (result = hba; result; result = result->next) {
555                 if (result->type == device->type && strcmp(result->path, device->path) == 0)
556                         break;
557         }
558         return result;
559 }
560
561 static int attach_hba_to_super(struct intel_super *super, struct sys_dev *device)
562 {
563         struct intel_hba *hba;
564
565         /* check if disk attached to Intel HBA */
566         hba = find_intel_hba(super->hba, device);
567         if (hba != NULL)
568                 return 1;
569         /* Check if HBA is already attached to super */
570         if (super->hba == NULL) {
571                 super->hba = alloc_intel_hba(device);
572                 return 1;
573         }
574
575         hba = super->hba;
576         /* Intel metadata allows for all disks attached to the same type HBA.
577          * Do not support HBA types mixing
578          */
579         if (device->type != hba->type)
580                 return 2;
581
582         /* Multiple same type HBAs can be used if they share the same OROM */
583         const struct imsm_orom *device_orom = get_orom_by_device_id(device->dev_id);
584
585         if (device_orom != super->orom)
586                 return 2;
587
588         while (hba->next)
589                 hba = hba->next;
590
591         hba->next = alloc_intel_hba(device);
592         return 1;
593 }
594
595 static struct sys_dev* find_disk_attached_hba(int fd, const char *devname)
596 {
597         struct sys_dev *list, *elem;
598         char *disk_path;
599
600         if ((list = find_intel_devices()) == NULL)
601                 return 0;
602
603         if (fd < 0)
604                 disk_path  = (char *) devname;
605         else
606                 disk_path = diskfd_to_devpath(fd);
607
608         if (!disk_path)
609                 return 0;
610
611         for (elem = list; elem; elem = elem->next)
612                 if (path_attached_to_hba(disk_path, elem->path))
613                         return elem;
614
615         if (disk_path != devname)
616                 free(disk_path);
617
618         return NULL;
619 }
620
621 static int find_intel_hba_capability(int fd, struct intel_super *super,
622                                      char *devname);
623
624 static struct supertype *match_metadata_desc_imsm(char *arg)
625 {
626         struct supertype *st;
627
628         if (strcmp(arg, "imsm") != 0 &&
629             strcmp(arg, "default") != 0
630                 )
631                 return NULL;
632
633         st = xcalloc(1, sizeof(*st));
634         st->ss = &super_imsm;
635         st->max_devs = IMSM_MAX_DEVICES;
636         st->minor_version = 0;
637         st->sb = NULL;
638         return st;
639 }
640
641 #ifndef MDASSEMBLE
642 static __u8 *get_imsm_version(struct imsm_super *mpb)
643 {
644         return &mpb->sig[MPB_SIG_LEN];
645 }
646 #endif
647
648 /* retrieve a disk directly from the anchor when the anchor is known to be
649  * up-to-date, currently only at load time
650  */
651 static struct imsm_disk *__get_imsm_disk(struct imsm_super *mpb, __u8 index)
652 {
653         if (index >= mpb->num_disks)
654                 return NULL;
655         return &mpb->disk[index];
656 }
657
658 /* retrieve the disk description based on a index of the disk
659  * in the sub-array
660  */
661 static struct dl *get_imsm_dl_disk(struct intel_super *super, __u8 index)
662 {
663         struct dl *d;
664
665         for (d = super->disks; d; d = d->next)
666                 if (d->index == index)
667                         return d;
668
669         return NULL;
670 }
671 /* retrieve a disk from the parsed metadata */
672 static struct imsm_disk *get_imsm_disk(struct intel_super *super, __u8 index)
673 {
674         struct dl *dl;
675
676         dl = get_imsm_dl_disk(super, index);
677         if (dl)
678                 return &dl->disk;
679
680         return NULL;
681 }
682
683 /* generate a checksum directly from the anchor when the anchor is known to be
684  * up-to-date, currently only at load or write_super after coalescing
685  */
686 static __u32 __gen_imsm_checksum(struct imsm_super *mpb)
687 {
688         __u32 end = mpb->mpb_size / sizeof(end);
689         __u32 *p = (__u32 *) mpb;
690         __u32 sum = 0;
691
692         while (end--) {
693                 sum += __le32_to_cpu(*p);
694                 p++;
695         }
696
697         return sum - __le32_to_cpu(mpb->check_sum);
698 }
699
700 static size_t sizeof_imsm_map(struct imsm_map *map)
701 {
702         return sizeof(struct imsm_map) + sizeof(__u32) * (map->num_members - 1);
703 }
704
705 struct imsm_map *get_imsm_map(struct imsm_dev *dev, int second_map)
706 {
707         /* A device can have 2 maps if it is in the middle of a migration.
708          * If second_map is:
709          *    MAP_0 - we return the first map
710          *    MAP_1 - we return the second map if it exists, else NULL
711          *    MAP_X - we return the second map if it exists, else the first
712          */
713         struct imsm_map *map = &dev->vol.map[0];
714         struct imsm_map *map2 = NULL;
715
716         if (dev->vol.migr_state)
717                 map2 = (void *)map + sizeof_imsm_map(map);
718
719         switch (second_map) {
720         case MAP_0:
721                 break;
722         case MAP_1:
723                 map = map2;
724                 break;
725         case MAP_X:
726                 if (map2)
727                         map = map2;
728                 break;
729         default:
730                 map = NULL;
731         }
732         return map;
733
734 }
735
736 /* return the size of the device.
737  * migr_state increases the returned size if map[0] were to be duplicated
738  */
739 static size_t sizeof_imsm_dev(struct imsm_dev *dev, int migr_state)
740 {
741         size_t size = sizeof(*dev) - sizeof(struct imsm_map) +
742                       sizeof_imsm_map(get_imsm_map(dev, MAP_0));
743
744         /* migrating means an additional map */
745         if (dev->vol.migr_state)
746                 size += sizeof_imsm_map(get_imsm_map(dev, MAP_1));
747         else if (migr_state)
748                 size += sizeof_imsm_map(get_imsm_map(dev, MAP_0));
749
750         return size;
751 }
752
753 #ifndef MDASSEMBLE
754 /* retrieve disk serial number list from a metadata update */
755 static struct disk_info *get_disk_info(struct imsm_update_create_array *update)
756 {
757         void *u = update;
758         struct disk_info *inf;
759
760         inf = u + sizeof(*update) - sizeof(struct imsm_dev) +
761               sizeof_imsm_dev(&update->dev, 0);
762
763         return inf;
764 }
765 #endif
766
767 static struct imsm_dev *__get_imsm_dev(struct imsm_super *mpb, __u8 index)
768 {
769         int offset;
770         int i;
771         void *_mpb = mpb;
772
773         if (index >= mpb->num_raid_devs)
774                 return NULL;
775
776         /* devices start after all disks */
777         offset = ((void *) &mpb->disk[mpb->num_disks]) - _mpb;
778
779         for (i = 0; i <= index; i++)
780                 if (i == index)
781                         return _mpb + offset;
782                 else
783                         offset += sizeof_imsm_dev(_mpb + offset, 0);
784
785         return NULL;
786 }
787
788 static struct imsm_dev *get_imsm_dev(struct intel_super *super, __u8 index)
789 {
790         struct intel_dev *dv;
791
792         if (index >= super->anchor->num_raid_devs)
793                 return NULL;
794         for (dv = super->devlist; dv; dv = dv->next)
795                 if (dv->index == index)
796                         return dv->dev;
797         return NULL;
798 }
799
800 static inline unsigned long long __le48_to_cpu(const struct bbm_log_block_addr
801                                                *addr)
802 {
803         return ((((__u64)__le32_to_cpu(addr->dw1)) << 16) |
804                 __le16_to_cpu(addr->w1));
805 }
806
807 static inline struct bbm_log_block_addr __cpu_to_le48(unsigned long long sec)
808 {
809         struct bbm_log_block_addr addr;
810
811         addr.w1 =  __cpu_to_le16((__u16)(sec & 0xffff));
812         addr.dw1 = __cpu_to_le32((__u32)(sec >> 16) & 0xffffffff);
813         return addr;
814 }
815
816 #ifndef MDASSEMBLE
817 /* get size of the bbm log */
818 static __u32 get_imsm_bbm_log_size(struct bbm_log *log)
819 {
820         if (!log || log->entry_count == 0)
821                 return 0;
822
823         return sizeof(log->signature) +
824                 sizeof(log->entry_count) +
825                 log->entry_count * sizeof(struct bbm_log_entry);
826 }
827 #endif /* MDASSEMBLE */
828
829 /* allocate and load BBM log from metadata */
830 static int load_bbm_log(struct intel_super *super)
831 {
832         struct imsm_super *mpb = super->anchor;
833         __u32 bbm_log_size =  __le32_to_cpu(mpb->bbm_log_size);
834
835         super->bbm_log = xcalloc(1, sizeof(struct bbm_log));
836         if (!super->bbm_log)
837                 return 1;
838
839         if (bbm_log_size) {
840                 struct bbm_log *log = (void *)mpb +
841                         __le32_to_cpu(mpb->mpb_size) - bbm_log_size;
842
843                 __u32 entry_count;
844
845                 if (bbm_log_size < sizeof(log->signature) +
846                     sizeof(log->entry_count))
847                         return 2;
848
849                 entry_count = __le32_to_cpu(log->entry_count);
850                 if ((__le32_to_cpu(log->signature) != BBM_LOG_SIGNATURE) ||
851                     (entry_count > BBM_LOG_MAX_ENTRIES))
852                         return 3;
853
854                 if (bbm_log_size !=
855                     sizeof(log->signature) + sizeof(log->entry_count) +
856                     entry_count * sizeof(struct bbm_log_entry))
857                         return 4;
858
859                 memcpy(super->bbm_log, log, bbm_log_size);
860         } else {
861                 super->bbm_log->signature = __cpu_to_le32(BBM_LOG_SIGNATURE);
862                 super->bbm_log->entry_count = 0;
863         }
864
865         return 0;
866 }
867
868 /*
869  * for second_map:
870  *  == MAP_0 get first map
871  *  == MAP_1 get second map
872  *  == MAP_X than get map according to the current migr_state
873  */
874 static __u32 get_imsm_ord_tbl_ent(struct imsm_dev *dev,
875                                   int slot,
876                                   int second_map)
877 {
878         struct imsm_map *map;
879
880         map = get_imsm_map(dev, second_map);
881
882         /* top byte identifies disk under rebuild */
883         return __le32_to_cpu(map->disk_ord_tbl[slot]);
884 }
885
886 #define ord_to_idx(ord) (((ord) << 8) >> 8)
887 static __u32 get_imsm_disk_idx(struct imsm_dev *dev, int slot, int second_map)
888 {
889         __u32 ord = get_imsm_ord_tbl_ent(dev, slot, second_map);
890
891         return ord_to_idx(ord);
892 }
893
894 static void set_imsm_ord_tbl_ent(struct imsm_map *map, int slot, __u32 ord)
895 {
896         map->disk_ord_tbl[slot] = __cpu_to_le32(ord);
897 }
898
899 static int get_imsm_disk_slot(struct imsm_map *map, unsigned idx)
900 {
901         int slot;
902         __u32 ord;
903
904         for (slot = 0; slot < map->num_members; slot++) {
905                 ord = __le32_to_cpu(map->disk_ord_tbl[slot]);
906                 if (ord_to_idx(ord) == idx)
907                         return slot;
908         }
909
910         return -1;
911 }
912
913 static int get_imsm_raid_level(struct imsm_map *map)
914 {
915         if (map->raid_level == 1) {
916                 if (map->num_members == 2)
917                         return 1;
918                 else
919                         return 10;
920         }
921
922         return map->raid_level;
923 }
924
925 static int cmp_extent(const void *av, const void *bv)
926 {
927         const struct extent *a = av;
928         const struct extent *b = bv;
929         if (a->start < b->start)
930                 return -1;
931         if (a->start > b->start)
932                 return 1;
933         return 0;
934 }
935
936 static int count_memberships(struct dl *dl, struct intel_super *super)
937 {
938         int memberships = 0;
939         int i;
940
941         for (i = 0; i < super->anchor->num_raid_devs; i++) {
942                 struct imsm_dev *dev = get_imsm_dev(super, i);
943                 struct imsm_map *map = get_imsm_map(dev, MAP_0);
944
945                 if (get_imsm_disk_slot(map, dl->index) >= 0)
946                         memberships++;
947         }
948
949         return memberships;
950 }
951
952 static __u32 imsm_min_reserved_sectors(struct intel_super *super);
953
954 static int split_ull(unsigned long long n, __u32 *lo, __u32 *hi)
955 {
956         if (lo == 0 || hi == 0)
957                 return 1;
958         *lo = __le32_to_cpu((unsigned)n);
959         *hi = __le32_to_cpu((unsigned)(n >> 32));
960         return 0;
961 }
962
963 static unsigned long long join_u32(__u32 lo, __u32 hi)
964 {
965         return (unsigned long long)__le32_to_cpu(lo) |
966                (((unsigned long long)__le32_to_cpu(hi)) << 32);
967 }
968
969 static unsigned long long total_blocks(struct imsm_disk *disk)
970 {
971         if (disk == NULL)
972                 return 0;
973         return join_u32(disk->total_blocks_lo, disk->total_blocks_hi);
974 }
975
976 static unsigned long long pba_of_lba0(struct imsm_map *map)
977 {
978         if (map == NULL)
979                 return 0;
980         return join_u32(map->pba_of_lba0_lo, map->pba_of_lba0_hi);
981 }
982
983 static unsigned long long blocks_per_member(struct imsm_map *map)
984 {
985         if (map == NULL)
986                 return 0;
987         return join_u32(map->blocks_per_member_lo, map->blocks_per_member_hi);
988 }
989
990 static unsigned long long num_data_stripes(struct imsm_map *map)
991 {
992         if (map == NULL)
993                 return 0;
994         return join_u32(map->num_data_stripes_lo, map->num_data_stripes_hi);
995 }
996
997 static void set_total_blocks(struct imsm_disk *disk, unsigned long long n)
998 {
999         split_ull(n, &disk->total_blocks_lo, &disk->total_blocks_hi);
1000 }
1001
1002 static void set_pba_of_lba0(struct imsm_map *map, unsigned long long n)
1003 {
1004         split_ull(n, &map->pba_of_lba0_lo, &map->pba_of_lba0_hi);
1005 }
1006
1007 static void set_blocks_per_member(struct imsm_map *map, unsigned long long n)
1008 {
1009         split_ull(n, &map->blocks_per_member_lo, &map->blocks_per_member_hi);
1010 }
1011
1012 static void set_num_data_stripes(struct imsm_map *map, unsigned long long n)
1013 {
1014         split_ull(n, &map->num_data_stripes_lo, &map->num_data_stripes_hi);
1015 }
1016
1017 static struct extent *get_extents(struct intel_super *super, struct dl *dl)
1018 {
1019         /* find a list of used extents on the given physical device */
1020         struct extent *rv, *e;
1021         int i;
1022         int memberships = count_memberships(dl, super);
1023         __u32 reservation;
1024
1025         /* trim the reserved area for spares, so they can join any array
1026          * regardless of whether the OROM has assigned sectors from the
1027          * IMSM_RESERVED_SECTORS region
1028          */
1029         if (dl->index == -1)
1030                 reservation = imsm_min_reserved_sectors(super);
1031         else
1032                 reservation = MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS;
1033
1034         rv = xcalloc(sizeof(struct extent), (memberships + 1));
1035         e = rv;
1036
1037         for (i = 0; i < super->anchor->num_raid_devs; i++) {
1038                 struct imsm_dev *dev = get_imsm_dev(super, i);
1039                 struct imsm_map *map = get_imsm_map(dev, MAP_0);
1040
1041                 if (get_imsm_disk_slot(map, dl->index) >= 0) {
1042                         e->start = pba_of_lba0(map);
1043                         e->size = blocks_per_member(map);
1044                         e++;
1045                 }
1046         }
1047         qsort(rv, memberships, sizeof(*rv), cmp_extent);
1048
1049         /* determine the start of the metadata
1050          * when no raid devices are defined use the default
1051          * ...otherwise allow the metadata to truncate the value
1052          * as is the case with older versions of imsm
1053          */
1054         if (memberships) {
1055                 struct extent *last = &rv[memberships - 1];
1056                 unsigned long long remainder;
1057
1058                 remainder = total_blocks(&dl->disk) - (last->start + last->size);
1059                 /* round down to 1k block to satisfy precision of the kernel
1060                  * 'size' interface
1061                  */
1062                 remainder &= ~1UL;
1063                 /* make sure remainder is still sane */
1064                 if (remainder < (unsigned)ROUND_UP(super->len, 512) >> 9)
1065                         remainder = ROUND_UP(super->len, 512) >> 9;
1066                 if (reservation > remainder)
1067                         reservation = remainder;
1068         }
1069         e->start = total_blocks(&dl->disk) - reservation;
1070         e->size = 0;
1071         return rv;
1072 }
1073
1074 /* try to determine how much space is reserved for metadata from
1075  * the last get_extents() entry, otherwise fallback to the
1076  * default
1077  */
1078 static __u32 imsm_reserved_sectors(struct intel_super *super, struct dl *dl)
1079 {
1080         struct extent *e;
1081         int i;
1082         __u32 rv;
1083
1084         /* for spares just return a minimal reservation which will grow
1085          * once the spare is picked up by an array
1086          */
1087         if (dl->index == -1)
1088                 return MPB_SECTOR_CNT;
1089
1090         e = get_extents(super, dl);
1091         if (!e)
1092                 return MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS;
1093
1094         /* scroll to last entry */
1095         for (i = 0; e[i].size; i++)
1096                 continue;
1097
1098         rv = total_blocks(&dl->disk) - e[i].start;
1099
1100         free(e);
1101
1102         return rv;
1103 }
1104
1105 static int is_spare(struct imsm_disk *disk)
1106 {
1107         return (disk->status & SPARE_DISK) == SPARE_DISK;
1108 }
1109
1110 static int is_configured(struct imsm_disk *disk)
1111 {
1112         return (disk->status & CONFIGURED_DISK) == CONFIGURED_DISK;
1113 }
1114
1115 static int is_failed(struct imsm_disk *disk)
1116 {
1117         return (disk->status & FAILED_DISK) == FAILED_DISK;
1118 }
1119
1120 /* try to determine how much space is reserved for metadata from
1121  * the last get_extents() entry on the smallest active disk,
1122  * otherwise fallback to the default
1123  */
1124 static __u32 imsm_min_reserved_sectors(struct intel_super *super)
1125 {
1126         struct extent *e;
1127         int i;
1128         unsigned long long min_active;
1129         __u32 remainder;
1130         __u32 rv = MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS;
1131         struct dl *dl, *dl_min = NULL;
1132
1133         if (!super)
1134                 return rv;
1135
1136         min_active = 0;
1137         for (dl = super->disks; dl; dl = dl->next) {
1138                 if (dl->index < 0)
1139                         continue;
1140                 unsigned long long blocks = total_blocks(&dl->disk);
1141                 if (blocks < min_active || min_active == 0) {
1142                         dl_min = dl;
1143                         min_active = blocks;
1144                 }
1145         }
1146         if (!dl_min)
1147                 return rv;
1148
1149         /* find last lba used by subarrays on the smallest active disk */
1150         e = get_extents(super, dl_min);
1151         if (!e)
1152                 return rv;
1153         for (i = 0; e[i].size; i++)
1154                 continue;
1155
1156         remainder = min_active - e[i].start;
1157         free(e);
1158
1159         /* to give priority to recovery we should not require full
1160            IMSM_RESERVED_SECTORS from the spare */
1161         rv = MPB_SECTOR_CNT + NUM_BLOCKS_DIRTY_STRIPE_REGION;
1162
1163         /* if real reservation is smaller use that value */
1164         return  (remainder < rv) ? remainder : rv;
1165 }
1166
1167 /* Return minimum size of a spare that can be used in this array*/
1168 static unsigned long long min_acceptable_spare_size_imsm(struct supertype *st)
1169 {
1170         struct intel_super *super = st->sb;
1171         struct dl *dl;
1172         struct extent *e;
1173         int i;
1174         unsigned long long rv = 0;
1175
1176         if (!super)
1177                 return rv;
1178         /* find first active disk in array */
1179         dl = super->disks;
1180         while (dl && (is_failed(&dl->disk) || dl->index == -1))
1181                 dl = dl->next;
1182         if (!dl)
1183                 return rv;
1184         /* find last lba used by subarrays */
1185         e = get_extents(super, dl);
1186         if (!e)
1187                 return rv;
1188         for (i = 0; e[i].size; i++)
1189                 continue;
1190         if (i > 0)
1191                 rv = e[i-1].start + e[i-1].size;
1192         free(e);
1193
1194         /* add the amount of space needed for metadata */
1195         rv = rv + imsm_min_reserved_sectors(super);
1196
1197         return rv * 512;
1198 }
1199
1200 static int is_gen_migration(struct imsm_dev *dev);
1201
1202 #define IMSM_4K_DIV 8
1203
1204 #ifndef MDASSEMBLE
1205 static __u64 blocks_per_migr_unit(struct intel_super *super,
1206                                   struct imsm_dev *dev);
1207
1208 static void print_imsm_dev(struct intel_super *super,
1209                            struct imsm_dev *dev,
1210                            char *uuid,
1211                            int disk_idx)
1212 {
1213         __u64 sz;
1214         int slot, i;
1215         struct imsm_map *map = get_imsm_map(dev, MAP_0);
1216         struct imsm_map *map2 = get_imsm_map(dev, MAP_1);
1217         __u32 ord;
1218
1219         printf("\n");
1220         printf("[%.16s]:\n", dev->volume);
1221         printf("           UUID : %s\n", uuid);
1222         printf("     RAID Level : %d", get_imsm_raid_level(map));
1223         if (map2)
1224                 printf(" <-- %d", get_imsm_raid_level(map2));
1225         printf("\n");
1226         printf("        Members : %d", map->num_members);
1227         if (map2)
1228                 printf(" <-- %d", map2->num_members);
1229         printf("\n");
1230         printf("          Slots : [");
1231         for (i = 0; i < map->num_members; i++) {
1232                 ord = get_imsm_ord_tbl_ent(dev, i, MAP_0);
1233                 printf("%s", ord & IMSM_ORD_REBUILD ? "_" : "U");
1234         }
1235         printf("]");
1236         if (map2) {
1237                 printf(" <-- [");
1238                 for (i = 0; i < map2->num_members; i++) {
1239                         ord = get_imsm_ord_tbl_ent(dev, i, MAP_1);
1240                         printf("%s", ord & IMSM_ORD_REBUILD ? "_" : "U");
1241                 }
1242                 printf("]");
1243         }
1244         printf("\n");
1245         printf("    Failed disk : ");
1246         if (map->failed_disk_num == 0xff)
1247                 printf("none");
1248         else
1249                 printf("%i", map->failed_disk_num);
1250         printf("\n");
1251         slot = get_imsm_disk_slot(map, disk_idx);
1252         if (slot >= 0) {
1253                 ord = get_imsm_ord_tbl_ent(dev, slot, MAP_X);
1254                 printf("      This Slot : %d%s\n", slot,
1255                        ord & IMSM_ORD_REBUILD ? " (out-of-sync)" : "");
1256         } else
1257                 printf("      This Slot : ?\n");
1258         sz = __le32_to_cpu(dev->size_high);
1259         sz <<= 32;
1260         sz += __le32_to_cpu(dev->size_low);
1261         printf("     Array Size : %llu%s\n", (unsigned long long)sz,
1262                human_size(sz * 512));
1263         sz = blocks_per_member(map);
1264         printf("   Per Dev Size : %llu%s\n", (unsigned long long)sz,
1265                human_size(sz * 512));
1266         printf("  Sector Offset : %llu\n",
1267                 pba_of_lba0(map));
1268         printf("    Num Stripes : %llu\n",
1269                 num_data_stripes(map));
1270         printf("     Chunk Size : %u KiB",
1271                 __le16_to_cpu(map->blocks_per_strip) / 2);
1272         if (map2)
1273                 printf(" <-- %u KiB",
1274                         __le16_to_cpu(map2->blocks_per_strip) / 2);
1275         printf("\n");
1276         printf("       Reserved : %d\n", __le32_to_cpu(dev->reserved_blocks));
1277         printf("  Migrate State : ");
1278         if (dev->vol.migr_state) {
1279                 if (migr_type(dev) == MIGR_INIT)
1280                         printf("initialize\n");
1281                 else if (migr_type(dev) == MIGR_REBUILD)
1282                         printf("rebuild\n");
1283                 else if (migr_type(dev) == MIGR_VERIFY)
1284                         printf("check\n");
1285                 else if (migr_type(dev) == MIGR_GEN_MIGR)
1286                         printf("general migration\n");
1287                 else if (migr_type(dev) == MIGR_STATE_CHANGE)
1288                         printf("state change\n");
1289                 else if (migr_type(dev) == MIGR_REPAIR)
1290                         printf("repair\n");
1291                 else
1292                         printf("<unknown:%d>\n", migr_type(dev));
1293         } else
1294                 printf("idle\n");
1295         printf("      Map State : %s", map_state_str[map->map_state]);
1296         if (dev->vol.migr_state) {
1297                 struct imsm_map *map = get_imsm_map(dev, MAP_1);
1298
1299                 printf(" <-- %s", map_state_str[map->map_state]);
1300                 printf("\n     Checkpoint : %u ",
1301                            __le32_to_cpu(dev->vol.curr_migr_unit));
1302                 if (is_gen_migration(dev) && (slot > 1 || slot < 0))
1303                         printf("(N/A)");
1304                 else
1305                         printf("(%llu)", (unsigned long long)
1306                                    blocks_per_migr_unit(super, dev));
1307         }
1308         printf("\n");
1309         printf("    Dirty State : %s\n", dev->vol.dirty ? "dirty" : "clean");
1310 }
1311
1312 static void print_imsm_disk(struct imsm_disk *disk, int index, __u32 reserved)
1313 {
1314         char str[MAX_RAID_SERIAL_LEN + 1];
1315         __u64 sz;
1316
1317         if (index < -1 || !disk)
1318                 return;
1319
1320         printf("\n");
1321         snprintf(str, MAX_RAID_SERIAL_LEN + 1, "%s", disk->serial);
1322         if (index >= 0)
1323                 printf("  Disk%02d Serial : %s\n", index, str);
1324         else
1325                 printf("    Disk Serial : %s\n", str);
1326         printf("          State :%s%s%s\n", is_spare(disk) ? " spare" : "",
1327                                             is_configured(disk) ? " active" : "",
1328                                             is_failed(disk) ? " failed" : "");
1329         printf("             Id : %08x\n", __le32_to_cpu(disk->scsi_id));
1330         sz = total_blocks(disk) - reserved;
1331         printf("    Usable Size : %llu%s\n", (unsigned long long)sz,
1332                human_size(sz * 512));
1333 }
1334
1335 void convert_to_4k_imsm_migr_rec(struct intel_super *super)
1336 {
1337         struct migr_record *migr_rec = super->migr_rec;
1338
1339         migr_rec->blocks_per_unit /= IMSM_4K_DIV;
1340         migr_rec->ckpt_area_pba /= IMSM_4K_DIV;
1341         migr_rec->dest_1st_member_lba /= IMSM_4K_DIV;
1342         migr_rec->dest_depth_per_unit /= IMSM_4K_DIV;
1343         split_ull((join_u32(migr_rec->post_migr_vol_cap,
1344                  migr_rec->post_migr_vol_cap_hi) / IMSM_4K_DIV),
1345                  &migr_rec->post_migr_vol_cap, &migr_rec->post_migr_vol_cap_hi);
1346 }
1347
1348 void convert_to_4k_imsm_disk(struct imsm_disk *disk)
1349 {
1350         set_total_blocks(disk, (total_blocks(disk)/IMSM_4K_DIV));
1351 }
1352
1353 void convert_to_4k(struct intel_super *super)
1354 {
1355         struct imsm_super *mpb = super->anchor;
1356         struct imsm_disk *disk;
1357         int i;
1358
1359         for (i = 0; i < mpb->num_disks ; i++) {
1360                 disk = __get_imsm_disk(mpb, i);
1361                 /* disk */
1362                 convert_to_4k_imsm_disk(disk);
1363         }
1364         for (i = 0; i < mpb->num_raid_devs; i++) {
1365                 struct imsm_dev *dev = __get_imsm_dev(mpb, i);
1366                 struct imsm_map *map = get_imsm_map(dev, MAP_0);
1367                 /* dev */
1368                 split_ull((join_u32(dev->size_low, dev->size_high)/IMSM_4K_DIV),
1369                                  &dev->size_low, &dev->size_high);
1370                 dev->vol.curr_migr_unit /= IMSM_4K_DIV;
1371
1372                 /* map0 */
1373                 set_blocks_per_member(map, blocks_per_member(map)/IMSM_4K_DIV);
1374                 map->blocks_per_strip /= IMSM_4K_DIV;
1375                 set_pba_of_lba0(map, pba_of_lba0(map)/IMSM_4K_DIV);
1376
1377                 if (dev->vol.migr_state) {
1378                         /* map1 */
1379                         map = get_imsm_map(dev, MAP_1);
1380                         set_blocks_per_member(map,
1381                             blocks_per_member(map)/IMSM_4K_DIV);
1382                         map->blocks_per_strip /= IMSM_4K_DIV;
1383                         set_pba_of_lba0(map, pba_of_lba0(map)/IMSM_4K_DIV);
1384                 }
1385         }
1386
1387         mpb->check_sum = __gen_imsm_checksum(mpb);
1388 }
1389
1390 void examine_migr_rec_imsm(struct intel_super *super)
1391 {
1392         struct migr_record *migr_rec = super->migr_rec;
1393         struct imsm_super *mpb = super->anchor;
1394         int i;
1395
1396         for (i = 0; i < mpb->num_raid_devs; i++) {
1397                 struct imsm_dev *dev = __get_imsm_dev(mpb, i);
1398                 struct imsm_map *map;
1399                 int slot = -1;
1400
1401                 if (is_gen_migration(dev) == 0)
1402                                 continue;
1403
1404                 printf("\nMigration Record Information:");
1405
1406                 /* first map under migration */
1407                 map = get_imsm_map(dev, MAP_0);
1408                 if (map)
1409                         slot = get_imsm_disk_slot(map, super->disks->index);
1410                 if (map == NULL || slot > 1 || slot < 0) {
1411                         printf(" Empty\n                              ");
1412                         printf("Examine one of first two disks in array\n");
1413                         break;
1414                 }
1415                 printf("\n                     Status : ");
1416                 if (__le32_to_cpu(migr_rec->rec_status) == UNIT_SRC_NORMAL)
1417                         printf("Normal\n");
1418                 else
1419                         printf("Contains Data\n");
1420                 printf("               Current Unit : %u\n",
1421                        __le32_to_cpu(migr_rec->curr_migr_unit));
1422                 printf("                     Family : %u\n",
1423                        __le32_to_cpu(migr_rec->family_num));
1424                 printf("                  Ascending : %u\n",
1425                        __le32_to_cpu(migr_rec->ascending_migr));
1426                 printf("            Blocks Per Unit : %u\n",
1427                        __le32_to_cpu(migr_rec->blocks_per_unit));
1428                 printf("       Dest. Depth Per Unit : %u\n",
1429                        __le32_to_cpu(migr_rec->dest_depth_per_unit));
1430                 printf("        Checkpoint Area pba : %u\n",
1431                        __le32_to_cpu(migr_rec->ckpt_area_pba));
1432                 printf("           First member lba : %u\n",
1433                        __le32_to_cpu(migr_rec->dest_1st_member_lba));
1434                 printf("      Total Number of Units : %u\n",
1435                        __le32_to_cpu(migr_rec->num_migr_units));
1436                 printf("             Size of volume : %u\n",
1437                        __le32_to_cpu(migr_rec->post_migr_vol_cap));
1438                 printf("  Expansion space for LBA64 : %u\n",
1439                        __le32_to_cpu(migr_rec->post_migr_vol_cap_hi));
1440                 printf("       Record was read from : %u\n",
1441                        __le32_to_cpu(migr_rec->ckpt_read_disk_num));
1442
1443                 break;
1444         }
1445 }
1446 #endif /* MDASSEMBLE */
1447
1448 void convert_from_4k_imsm_migr_rec(struct intel_super *super)
1449 {
1450         struct migr_record *migr_rec = super->migr_rec;
1451
1452         migr_rec->blocks_per_unit *= IMSM_4K_DIV;
1453         migr_rec->ckpt_area_pba *= IMSM_4K_DIV;
1454         migr_rec->dest_1st_member_lba *= IMSM_4K_DIV;
1455         migr_rec->dest_depth_per_unit *= IMSM_4K_DIV;
1456         split_ull((join_u32(migr_rec->post_migr_vol_cap,
1457                  migr_rec->post_migr_vol_cap_hi) * IMSM_4K_DIV),
1458                  &migr_rec->post_migr_vol_cap,
1459                  &migr_rec->post_migr_vol_cap_hi);
1460 }
1461
1462 void convert_from_4k(struct intel_super *super)
1463 {
1464         struct imsm_super *mpb = super->anchor;
1465         struct imsm_disk *disk;
1466         int i;
1467
1468         for (i = 0; i < mpb->num_disks ; i++) {
1469                 disk = __get_imsm_disk(mpb, i);
1470                 /* disk */
1471                 set_total_blocks(disk, (total_blocks(disk)*IMSM_4K_DIV));
1472         }
1473
1474         for (i = 0; i < mpb->num_raid_devs; i++) {
1475                 struct imsm_dev *dev = __get_imsm_dev(mpb, i);
1476                 struct imsm_map *map = get_imsm_map(dev, MAP_0);
1477                 /* dev */
1478                 split_ull((join_u32(dev->size_low, dev->size_high)*IMSM_4K_DIV),
1479                                  &dev->size_low, &dev->size_high);
1480                 dev->vol.curr_migr_unit *= IMSM_4K_DIV;
1481
1482                 /* map0 */
1483                 set_blocks_per_member(map, blocks_per_member(map)*IMSM_4K_DIV);
1484                 map->blocks_per_strip *= IMSM_4K_DIV;
1485                 set_pba_of_lba0(map, pba_of_lba0(map)*IMSM_4K_DIV);
1486
1487                 if (dev->vol.migr_state) {
1488                         /* map1 */
1489                         map = get_imsm_map(dev, MAP_1);
1490                         set_blocks_per_member(map,
1491                             blocks_per_member(map)*IMSM_4K_DIV);
1492                         map->blocks_per_strip *= IMSM_4K_DIV;
1493                         set_pba_of_lba0(map, pba_of_lba0(map)*IMSM_4K_DIV);
1494                 }
1495         }
1496
1497         mpb->check_sum = __gen_imsm_checksum(mpb);
1498 }
1499
1500 /*******************************************************************************
1501  * function: imsm_check_attributes
1502  * Description: Function checks if features represented by attributes flags
1503  *              are supported by mdadm.
1504  * Parameters:
1505  *              attributes - Attributes read from metadata
1506  * Returns:
1507  *              0 - passed attributes contains unsupported features flags
1508  *              1 - all features are supported
1509  ******************************************************************************/
1510 static int imsm_check_attributes(__u32 attributes)
1511 {
1512         int ret_val = 1;
1513         __u32 not_supported = MPB_ATTRIB_SUPPORTED^0xffffffff;
1514
1515         not_supported &= ~MPB_ATTRIB_IGNORED;
1516
1517         not_supported &= attributes;
1518         if (not_supported) {
1519                 pr_err("(IMSM): Unsupported attributes : %x\n",
1520                         (unsigned)__le32_to_cpu(not_supported));
1521                 if (not_supported & MPB_ATTRIB_CHECKSUM_VERIFY) {
1522                         dprintf("\t\tMPB_ATTRIB_CHECKSUM_VERIFY \n");
1523                         not_supported ^= MPB_ATTRIB_CHECKSUM_VERIFY;
1524                 }
1525                 if (not_supported & MPB_ATTRIB_2TB) {
1526                         dprintf("\t\tMPB_ATTRIB_2TB\n");
1527                         not_supported ^= MPB_ATTRIB_2TB;
1528                 }
1529                 if (not_supported & MPB_ATTRIB_RAID0) {
1530                         dprintf("\t\tMPB_ATTRIB_RAID0\n");
1531                         not_supported ^= MPB_ATTRIB_RAID0;
1532                 }
1533                 if (not_supported & MPB_ATTRIB_RAID1) {
1534                         dprintf("\t\tMPB_ATTRIB_RAID1\n");
1535                         not_supported ^= MPB_ATTRIB_RAID1;
1536                 }
1537                 if (not_supported & MPB_ATTRIB_RAID10) {
1538                         dprintf("\t\tMPB_ATTRIB_RAID10\n");
1539                         not_supported ^= MPB_ATTRIB_RAID10;
1540                 }
1541                 if (not_supported & MPB_ATTRIB_RAID1E) {
1542                         dprintf("\t\tMPB_ATTRIB_RAID1E\n");
1543                         not_supported ^= MPB_ATTRIB_RAID1E;
1544                 }
1545                 if (not_supported & MPB_ATTRIB_RAID5) {
1546                 dprintf("\t\tMPB_ATTRIB_RAID5\n");
1547                         not_supported ^= MPB_ATTRIB_RAID5;
1548                 }
1549                 if (not_supported & MPB_ATTRIB_RAIDCNG) {
1550                         dprintf("\t\tMPB_ATTRIB_RAIDCNG\n");
1551                         not_supported ^= MPB_ATTRIB_RAIDCNG;
1552                 }
1553                 if (not_supported & MPB_ATTRIB_BBM) {
1554                         dprintf("\t\tMPB_ATTRIB_BBM\n");
1555                 not_supported ^= MPB_ATTRIB_BBM;
1556                 }
1557                 if (not_supported & MPB_ATTRIB_CHECKSUM_VERIFY) {
1558                         dprintf("\t\tMPB_ATTRIB_CHECKSUM_VERIFY (== MPB_ATTRIB_LEGACY)\n");
1559                         not_supported ^= MPB_ATTRIB_CHECKSUM_VERIFY;
1560                 }
1561                 if (not_supported & MPB_ATTRIB_EXP_STRIPE_SIZE) {
1562                         dprintf("\t\tMPB_ATTRIB_EXP_STRIP_SIZE\n");
1563                         not_supported ^= MPB_ATTRIB_EXP_STRIPE_SIZE;
1564                 }
1565                 if (not_supported & MPB_ATTRIB_2TB_DISK) {
1566                         dprintf("\t\tMPB_ATTRIB_2TB_DISK\n");
1567                         not_supported ^= MPB_ATTRIB_2TB_DISK;
1568                 }
1569                 if (not_supported & MPB_ATTRIB_NEVER_USE2) {
1570                         dprintf("\t\tMPB_ATTRIB_NEVER_USE2\n");
1571                         not_supported ^= MPB_ATTRIB_NEVER_USE2;
1572                 }
1573                 if (not_supported & MPB_ATTRIB_NEVER_USE) {
1574                         dprintf("\t\tMPB_ATTRIB_NEVER_USE\n");
1575                         not_supported ^= MPB_ATTRIB_NEVER_USE;
1576                 }
1577
1578                 if (not_supported)
1579                         dprintf("(IMSM): Unknown attributes : %x\n", not_supported);
1580
1581                 ret_val = 0;
1582         }
1583
1584         return ret_val;
1585 }
1586
1587 #ifndef MDASSEMBLE
1588 static void getinfo_super_imsm(struct supertype *st, struct mdinfo *info, char *map);
1589
1590 static void examine_super_imsm(struct supertype *st, char *homehost)
1591 {
1592         struct intel_super *super = st->sb;
1593         struct imsm_super *mpb = super->anchor;
1594         char str[MAX_SIGNATURE_LENGTH];
1595         int i;
1596         struct mdinfo info;
1597         char nbuf[64];
1598         __u32 sum;
1599         __u32 reserved = imsm_reserved_sectors(super, super->disks);
1600         struct dl *dl;
1601
1602         snprintf(str, MPB_SIG_LEN, "%s", mpb->sig);
1603         printf("          Magic : %s\n", str);
1604         snprintf(str, strlen(MPB_VERSION_RAID0), "%s", get_imsm_version(mpb));
1605         printf("        Version : %s\n", get_imsm_version(mpb));
1606         printf("    Orig Family : %08x\n", __le32_to_cpu(mpb->orig_family_num));
1607         printf("         Family : %08x\n", __le32_to_cpu(mpb->family_num));
1608         printf("     Generation : %08x\n", __le32_to_cpu(mpb->generation_num));
1609         printf("     Attributes : ");
1610         if (imsm_check_attributes(mpb->attributes))
1611                 printf("All supported\n");
1612         else
1613                 printf("not supported\n");
1614         getinfo_super_imsm(st, &info, NULL);
1615         fname_from_uuid(st, &info, nbuf, ':');
1616         printf("           UUID : %s\n", nbuf + 5);
1617         sum = __le32_to_cpu(mpb->check_sum);
1618         printf("       Checksum : %08x %s\n", sum,
1619                 __gen_imsm_checksum(mpb) == sum ? "correct" : "incorrect");
1620         printf("    MPB Sectors : %d\n", mpb_sectors(mpb, super->sector_size));
1621         printf("          Disks : %d\n", mpb->num_disks);
1622         printf("   RAID Devices : %d\n", mpb->num_raid_devs);
1623         print_imsm_disk(__get_imsm_disk(mpb, super->disks->index), super->disks->index, reserved);
1624         if (get_imsm_bbm_log_size(super->bbm_log)) {
1625                 struct bbm_log *log = super->bbm_log;
1626
1627                 printf("\n");
1628                 printf("Bad Block Management Log:\n");
1629                 printf("       Log Size : %d\n", __le32_to_cpu(mpb->bbm_log_size));
1630                 printf("      Signature : %x\n", __le32_to_cpu(log->signature));
1631                 printf("    Entry Count : %d\n", __le32_to_cpu(log->entry_count));
1632         }
1633         for (i = 0; i < mpb->num_raid_devs; i++) {
1634                 struct mdinfo info;
1635                 struct imsm_dev *dev = __get_imsm_dev(mpb, i);
1636
1637                 super->current_vol = i;
1638                 getinfo_super_imsm(st, &info, NULL);
1639                 fname_from_uuid(st, &info, nbuf, ':');
1640                 print_imsm_dev(super, dev, nbuf + 5, super->disks->index);
1641         }
1642         for (i = 0; i < mpb->num_disks; i++) {
1643                 if (i == super->disks->index)
1644                         continue;
1645                 print_imsm_disk(__get_imsm_disk(mpb, i), i, reserved);
1646         }
1647
1648         for (dl = super->disks; dl; dl = dl->next)
1649                 if (dl->index == -1)
1650                         print_imsm_disk(&dl->disk, -1, reserved);
1651
1652         examine_migr_rec_imsm(super);
1653 }
1654
1655 static void brief_examine_super_imsm(struct supertype *st, int verbose)
1656 {
1657         /* We just write a generic IMSM ARRAY entry */
1658         struct mdinfo info;
1659         char nbuf[64];
1660         struct intel_super *super = st->sb;
1661
1662         if (!super->anchor->num_raid_devs) {
1663                 printf("ARRAY metadata=imsm\n");
1664                 return;
1665         }
1666
1667         getinfo_super_imsm(st, &info, NULL);
1668         fname_from_uuid(st, &info, nbuf, ':');
1669         printf("ARRAY metadata=imsm UUID=%s\n", nbuf + 5);
1670 }
1671
1672 static void brief_examine_subarrays_imsm(struct supertype *st, int verbose)
1673 {
1674         /* We just write a generic IMSM ARRAY entry */
1675         struct mdinfo info;
1676         char nbuf[64];
1677         char nbuf1[64];
1678         struct intel_super *super = st->sb;
1679         int i;
1680
1681         if (!super->anchor->num_raid_devs)
1682                 return;
1683
1684         getinfo_super_imsm(st, &info, NULL);
1685         fname_from_uuid(st, &info, nbuf, ':');
1686         for (i = 0; i < super->anchor->num_raid_devs; i++) {
1687                 struct imsm_dev *dev = get_imsm_dev(super, i);
1688
1689                 super->current_vol = i;
1690                 getinfo_super_imsm(st, &info, NULL);
1691                 fname_from_uuid(st, &info, nbuf1, ':');
1692                 printf("ARRAY /dev/md/%.16s container=%s member=%d UUID=%s\n",
1693                        dev->volume, nbuf + 5, i, nbuf1 + 5);
1694         }
1695 }
1696
1697 static void export_examine_super_imsm(struct supertype *st)
1698 {
1699         struct intel_super *super = st->sb;
1700         struct imsm_super *mpb = super->anchor;
1701         struct mdinfo info;
1702         char nbuf[64];
1703
1704         getinfo_super_imsm(st, &info, NULL);
1705         fname_from_uuid(st, &info, nbuf, ':');
1706         printf("MD_METADATA=imsm\n");
1707         printf("MD_LEVEL=container\n");
1708         printf("MD_UUID=%s\n", nbuf+5);
1709         printf("MD_DEVICES=%u\n", mpb->num_disks);
1710 }
1711
1712 static int copy_metadata_imsm(struct supertype *st, int from, int to)
1713 {
1714         /* The second last sector of the device contains
1715          * the "struct imsm_super" metadata.
1716          * This contains mpb_size which is the size in bytes of the
1717          * extended metadata.  This is located immediately before
1718          * the imsm_super.
1719          * We want to read all that, plus the last sector which
1720          * may contain a migration record, and write it all
1721          * to the target.
1722          */
1723         void *buf;
1724         unsigned long long dsize, offset;
1725         int sectors;
1726         struct imsm_super *sb;
1727         struct intel_super *super = st->sb;
1728         unsigned int sector_size = super->sector_size;
1729         unsigned int written = 0;
1730
1731         if (posix_memalign(&buf, MAX_SECTOR_SIZE, MAX_SECTOR_SIZE) != 0)
1732                 return 1;
1733
1734         if (!get_dev_size(from, NULL, &dsize))
1735                 goto err;
1736
1737         if (lseek64(from, dsize-(2*sector_size), 0) < 0)
1738                 goto err;
1739         if (read(from, buf, sector_size) != sector_size)
1740                 goto err;
1741         sb = buf;
1742         if (strncmp((char*)sb->sig, MPB_SIGNATURE, MPB_SIG_LEN) != 0)
1743                 goto err;
1744
1745         sectors = mpb_sectors(sb, sector_size) + 2;
1746         offset = dsize - sectors * sector_size;
1747         if (lseek64(from, offset, 0) < 0 ||
1748             lseek64(to, offset, 0) < 0)
1749                 goto err;
1750         while (written < sectors * sector_size) {
1751                 int n = sectors*sector_size - written;
1752                 if (n > 4096)
1753                         n = 4096;
1754                 if (read(from, buf, n) != n)
1755                         goto err;
1756                 if (write(to, buf, n) != n)
1757                         goto err;
1758                 written += n;
1759         }
1760         free(buf);
1761         return 0;
1762 err:
1763         free(buf);
1764         return 1;
1765 }
1766
1767 static void detail_super_imsm(struct supertype *st, char *homehost)
1768 {
1769         struct mdinfo info;
1770         char nbuf[64];
1771
1772         getinfo_super_imsm(st, &info, NULL);
1773         fname_from_uuid(st, &info, nbuf, ':');
1774         printf("\n           UUID : %s\n", nbuf + 5);
1775 }
1776
1777 static void brief_detail_super_imsm(struct supertype *st)
1778 {
1779         struct mdinfo info;
1780         char nbuf[64];
1781         getinfo_super_imsm(st, &info, NULL);
1782         fname_from_uuid(st, &info, nbuf, ':');
1783         printf(" UUID=%s", nbuf + 5);
1784 }
1785
1786 static int imsm_read_serial(int fd, char *devname, __u8 *serial);
1787 static void fd2devname(int fd, char *name);
1788
1789 static int ahci_enumerate_ports(const char *hba_path, int port_count, int host_base, int verbose)
1790 {
1791         /* dump an unsorted list of devices attached to AHCI Intel storage
1792          * controller, as well as non-connected ports
1793          */
1794         int hba_len = strlen(hba_path) + 1;
1795         struct dirent *ent;
1796         DIR *dir;
1797         char *path = NULL;
1798         int err = 0;
1799         unsigned long port_mask = (1 << port_count) - 1;
1800
1801         if (port_count > (int)sizeof(port_mask) * 8) {
1802                 if (verbose > 0)
1803                         pr_err("port_count %d out of range\n", port_count);
1804                 return 2;
1805         }
1806
1807         /* scroll through /sys/dev/block looking for devices attached to
1808          * this hba
1809          */
1810         dir = opendir("/sys/dev/block");
1811         if (!dir)
1812                 return 1;
1813
1814         for (ent = readdir(dir); ent; ent = readdir(dir)) {
1815                 int fd;
1816                 char model[64];
1817                 char vendor[64];
1818                 char buf[1024];
1819                 int major, minor;
1820                 char *device;
1821                 char *c;
1822                 int port;
1823                 int type;
1824
1825                 if (sscanf(ent->d_name, "%d:%d", &major, &minor) != 2)
1826                         continue;
1827                 path = devt_to_devpath(makedev(major, minor));
1828                 if (!path)
1829                         continue;
1830                 if (!path_attached_to_hba(path, hba_path)) {
1831                         free(path);
1832                         path = NULL;
1833                         continue;
1834                 }
1835
1836                 /* retrieve the scsi device type */
1837                 if (asprintf(&device, "/sys/dev/block/%d:%d/device/xxxxxxx", major, minor) < 0) {
1838                         if (verbose > 0)
1839                                 pr_err("failed to allocate 'device'\n");
1840                         err = 2;
1841                         break;
1842                 }
1843                 sprintf(device, "/sys/dev/block/%d:%d/device/type", major, minor);
1844                 if (load_sys(device, buf, sizeof(buf)) != 0) {
1845                         if (verbose > 0)
1846                                 pr_err("failed to read device type for %s\n",
1847                                         path);
1848                         err = 2;
1849                         free(device);
1850                         break;
1851                 }
1852                 type = strtoul(buf, NULL, 10);
1853
1854                 /* if it's not a disk print the vendor and model */
1855                 if (!(type == 0 || type == 7 || type == 14)) {
1856                         vendor[0] = '\0';
1857                         model[0] = '\0';
1858                         sprintf(device, "/sys/dev/block/%d:%d/device/vendor", major, minor);
1859                         if (load_sys(device, buf, sizeof(buf)) == 0) {
1860                                 strncpy(vendor, buf, sizeof(vendor));
1861                                 vendor[sizeof(vendor) - 1] = '\0';
1862                                 c = (char *) &vendor[sizeof(vendor) - 1];
1863                                 while (isspace(*c) || *c == '\0')
1864                                         *c-- = '\0';
1865
1866                         }
1867                         sprintf(device, "/sys/dev/block/%d:%d/device/model", major, minor);
1868                         if (load_sys(device, buf, sizeof(buf)) == 0) {
1869                                 strncpy(model, buf, sizeof(model));
1870                                 model[sizeof(model) - 1] = '\0';
1871                                 c = (char *) &model[sizeof(model) - 1];
1872                                 while (isspace(*c) || *c == '\0')
1873                                         *c-- = '\0';
1874                         }
1875
1876                         if (vendor[0] && model[0])
1877                                 sprintf(buf, "%.64s %.64s", vendor, model);
1878                         else
1879                                 switch (type) { /* numbers from hald/linux/device.c */
1880                                 case 1: sprintf(buf, "tape"); break;
1881                                 case 2: sprintf(buf, "printer"); break;
1882                                 case 3: sprintf(buf, "processor"); break;
1883                                 case 4:
1884                                 case 5: sprintf(buf, "cdrom"); break;
1885                                 case 6: sprintf(buf, "scanner"); break;
1886                                 case 8: sprintf(buf, "media_changer"); break;
1887                                 case 9: sprintf(buf, "comm"); break;
1888                                 case 12: sprintf(buf, "raid"); break;
1889                                 default: sprintf(buf, "unknown");
1890                                 }
1891                 } else
1892                         buf[0] = '\0';
1893                 free(device);
1894
1895                 /* chop device path to 'host%d' and calculate the port number */
1896                 c = strchr(&path[hba_len], '/');
1897                 if (!c) {
1898                         if (verbose > 0)
1899                                 pr_err("%s - invalid path name\n", path + hba_len);
1900                         err = 2;
1901                         break;
1902                 }
1903                 *c = '\0';
1904                 if ((sscanf(&path[hba_len], "ata%d", &port) == 1) ||
1905                    ((sscanf(&path[hba_len], "host%d", &port) == 1)))
1906                         port -= host_base;
1907                 else {
1908                         if (verbose > 0) {
1909                                 *c = '/'; /* repair the full string */
1910                                 pr_err("failed to determine port number for %s\n",
1911                                         path);
1912                         }
1913                         err = 2;
1914                         break;
1915                 }
1916
1917                 /* mark this port as used */
1918                 port_mask &= ~(1 << port);
1919
1920                 /* print out the device information */
1921                 if (buf[0]) {
1922                         printf("          Port%d : - non-disk device (%s) -\n", port, buf);
1923                         continue;
1924                 }
1925
1926                 fd = dev_open(ent->d_name, O_RDONLY);
1927                 if (fd < 0)
1928                         printf("          Port%d : - disk info unavailable -\n", port);
1929                 else {
1930                         fd2devname(fd, buf);
1931                         printf("          Port%d : %s", port, buf);
1932                         if (imsm_read_serial(fd, NULL, (__u8 *) buf) == 0)
1933                                 printf(" (%.*s)\n", MAX_RAID_SERIAL_LEN, buf);
1934                         else
1935                                 printf(" ()\n");
1936                         close(fd);
1937                 }
1938                 free(path);
1939                 path = NULL;
1940         }
1941         if (path)
1942                 free(path);
1943         if (dir)
1944                 closedir(dir);
1945         if (err == 0) {
1946                 int i;
1947
1948                 for (i = 0; i < port_count; i++)
1949                         if (port_mask & (1 << i))
1950                                 printf("          Port%d : - no device attached -\n", i);
1951         }
1952
1953         return err;
1954 }
1955
1956 static int print_vmd_attached_devs(struct sys_dev *hba)
1957 {
1958         struct dirent *ent;
1959         DIR *dir;
1960         char path[292];
1961         char link[256];
1962         char *c, *rp;
1963
1964         if (hba->type != SYS_DEV_VMD)
1965                 return 1;
1966
1967         /* scroll through /sys/dev/block looking for devices attached to
1968          * this hba
1969          */
1970         dir = opendir("/sys/bus/pci/drivers/nvme");
1971         if (!dir)
1972                 return 1;
1973
1974         for (ent = readdir(dir); ent; ent = readdir(dir)) {
1975                 int n;
1976
1977                 /* is 'ent' a device? check that the 'subsystem' link exists and
1978                  * that its target matches 'bus'
1979                  */
1980                 sprintf(path, "/sys/bus/pci/drivers/nvme/%s/subsystem",
1981                         ent->d_name);
1982                 n = readlink(path, link, sizeof(link));
1983                 if (n < 0 || n >= (int)sizeof(link))
1984                         continue;
1985                 link[n] = '\0';
1986                 c = strrchr(link, '/');
1987                 if (!c)
1988                         continue;
1989                 if (strncmp("pci", c+1, strlen("pci")) != 0)
1990                         continue;
1991
1992                 sprintf(path, "/sys/bus/pci/drivers/nvme/%s", ent->d_name);
1993                 /* if not a intel NVMe - skip it*/
1994                 if (devpath_to_vendor(path) != 0x8086)
1995                         continue;
1996
1997                 rp = realpath(path, NULL);
1998                 if (!rp)
1999                         continue;
2000
2001                 if (path_attached_to_hba(rp, hba->path)) {
2002                         printf(" NVMe under VMD : %s\n", rp);
2003                 }
2004                 free(rp);
2005         }
2006
2007         closedir(dir);
2008         return 0;
2009 }
2010
2011 static void print_found_intel_controllers(struct sys_dev *elem)
2012 {
2013         for (; elem; elem = elem->next) {
2014                 pr_err("found Intel(R) ");
2015                 if (elem->type == SYS_DEV_SATA)
2016                         fprintf(stderr, "SATA ");
2017                 else if (elem->type == SYS_DEV_SAS)
2018                         fprintf(stderr, "SAS ");
2019                 else if (elem->type == SYS_DEV_NVME)
2020                         fprintf(stderr, "NVMe ");
2021
2022                 if (elem->type == SYS_DEV_VMD)
2023                         fprintf(stderr, "VMD domain");
2024                 else
2025                         fprintf(stderr, "RAID controller");
2026
2027                 if (elem->pci_id)
2028                         fprintf(stderr, " at %s", elem->pci_id);
2029                 fprintf(stderr, ".\n");
2030         }
2031         fflush(stderr);
2032 }
2033
2034 static int ahci_get_port_count(const char *hba_path, int *port_count)
2035 {
2036         struct dirent *ent;
2037         DIR *dir;
2038         int host_base = -1;
2039
2040         *port_count = 0;
2041         if ((dir = opendir(hba_path)) == NULL)
2042                 return -1;
2043
2044         for (ent = readdir(dir); ent; ent = readdir(dir)) {
2045                 int host;
2046
2047                 if ((sscanf(ent->d_name, "ata%d", &host) != 1) &&
2048                    ((sscanf(ent->d_name, "host%d", &host) != 1)))
2049                         continue;
2050                 if (*port_count == 0)
2051                         host_base = host;
2052                 else if (host < host_base)
2053                         host_base = host;
2054
2055                 if (host + 1 > *port_count + host_base)
2056                         *port_count = host + 1 - host_base;
2057         }
2058         closedir(dir);
2059         return host_base;
2060 }
2061
2062 static void print_imsm_capability(const struct imsm_orom *orom)
2063 {
2064         printf("       Platform : Intel(R) ");
2065         if (orom->capabilities == 0 && orom->driver_features == 0)
2066                 printf("Matrix Storage Manager\n");
2067         else
2068                 printf("Rapid Storage Technology%s\n",
2069                         imsm_orom_is_enterprise(orom) ? " enterprise" : "");
2070         if (orom->major_ver || orom->minor_ver || orom->hotfix_ver || orom->build)
2071                 printf("        Version : %d.%d.%d.%d\n", orom->major_ver,
2072                                 orom->minor_ver, orom->hotfix_ver, orom->build);
2073         printf("    RAID Levels :%s%s%s%s%s\n",
2074                imsm_orom_has_raid0(orom) ? " raid0" : "",
2075                imsm_orom_has_raid1(orom) ? " raid1" : "",
2076                imsm_orom_has_raid1e(orom) ? " raid1e" : "",
2077                imsm_orom_has_raid10(orom) ? " raid10" : "",
2078                imsm_orom_has_raid5(orom) ? " raid5" : "");
2079         printf("    Chunk Sizes :%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
2080                imsm_orom_has_chunk(orom, 2) ? " 2k" : "",
2081                imsm_orom_has_chunk(orom, 4) ? " 4k" : "",
2082                imsm_orom_has_chunk(orom, 8) ? " 8k" : "",
2083                imsm_orom_has_chunk(orom, 16) ? " 16k" : "",
2084                imsm_orom_has_chunk(orom, 32) ? " 32k" : "",
2085                imsm_orom_has_chunk(orom, 64) ? " 64k" : "",
2086                imsm_orom_has_chunk(orom, 128) ? " 128k" : "",
2087                imsm_orom_has_chunk(orom, 256) ? " 256k" : "",
2088                imsm_orom_has_chunk(orom, 512) ? " 512k" : "",
2089                imsm_orom_has_chunk(orom, 1024*1) ? " 1M" : "",
2090                imsm_orom_has_chunk(orom, 1024*2) ? " 2M" : "",
2091                imsm_orom_has_chunk(orom, 1024*4) ? " 4M" : "",
2092                imsm_orom_has_chunk(orom, 1024*8) ? " 8M" : "",
2093                imsm_orom_has_chunk(orom, 1024*16) ? " 16M" : "",
2094                imsm_orom_has_chunk(orom, 1024*32) ? " 32M" : "",
2095                imsm_orom_has_chunk(orom, 1024*64) ? " 64M" : "");
2096         printf("    2TB volumes :%s supported\n",
2097                (orom->attr & IMSM_OROM_ATTR_2TB)?"":" not");
2098         printf("      2TB disks :%s supported\n",
2099                (orom->attr & IMSM_OROM_ATTR_2TB_DISK)?"":" not");
2100         printf("      Max Disks : %d\n", orom->tds);
2101         printf("    Max Volumes : %d per array, %d per %s\n",
2102                orom->vpa, orom->vphba,
2103                imsm_orom_is_nvme(orom) ? "platform" : "controller");
2104         return;
2105 }
2106
2107 static void print_imsm_capability_export(const struct imsm_orom *orom)
2108 {
2109         printf("MD_FIRMWARE_TYPE=imsm\n");
2110         if (orom->major_ver || orom->minor_ver || orom->hotfix_ver || orom->build)
2111                 printf("IMSM_VERSION=%d.%d.%d.%d\n", orom->major_ver, orom->minor_ver,
2112                                 orom->hotfix_ver, orom->build);
2113         printf("IMSM_SUPPORTED_RAID_LEVELS=%s%s%s%s%s\n",
2114                         imsm_orom_has_raid0(orom) ? "raid0 " : "",
2115                         imsm_orom_has_raid1(orom) ? "raid1 " : "",
2116                         imsm_orom_has_raid1e(orom) ? "raid1e " : "",
2117                         imsm_orom_has_raid5(orom) ? "raid10 " : "",
2118                         imsm_orom_has_raid10(orom) ? "raid5 " : "");
2119         printf("IMSM_SUPPORTED_CHUNK_SIZES=%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
2120                         imsm_orom_has_chunk(orom, 2) ? "2k " : "",
2121                         imsm_orom_has_chunk(orom, 4) ? "4k " : "",
2122                         imsm_orom_has_chunk(orom, 8) ? "8k " : "",
2123                         imsm_orom_has_chunk(orom, 16) ? "16k " : "",
2124                         imsm_orom_has_chunk(orom, 32) ? "32k " : "",
2125                         imsm_orom_has_chunk(orom, 64) ? "64k " : "",
2126                         imsm_orom_has_chunk(orom, 128) ? "128k " : "",
2127                         imsm_orom_has_chunk(orom, 256) ? "256k " : "",
2128                         imsm_orom_has_chunk(orom, 512) ? "512k " : "",
2129                         imsm_orom_has_chunk(orom, 1024*1) ? "1M " : "",
2130                         imsm_orom_has_chunk(orom, 1024*2) ? "2M " : "",
2131                         imsm_orom_has_chunk(orom, 1024*4) ? "4M " : "",
2132                         imsm_orom_has_chunk(orom, 1024*8) ? "8M " : "",
2133                         imsm_orom_has_chunk(orom, 1024*16) ? "16M " : "",
2134                         imsm_orom_has_chunk(orom, 1024*32) ? "32M " : "",
2135                         imsm_orom_has_chunk(orom, 1024*64) ? "64M " : "");
2136         printf("IMSM_2TB_VOLUMES=%s\n",(orom->attr & IMSM_OROM_ATTR_2TB) ? "yes" : "no");
2137         printf("IMSM_2TB_DISKS=%s\n",(orom->attr & IMSM_OROM_ATTR_2TB_DISK) ? "yes" : "no");
2138         printf("IMSM_MAX_DISKS=%d\n",orom->tds);
2139         printf("IMSM_MAX_VOLUMES_PER_ARRAY=%d\n",orom->vpa);
2140         printf("IMSM_MAX_VOLUMES_PER_CONTROLLER=%d\n",orom->vphba);
2141 }
2142
2143 static int detail_platform_imsm(int verbose, int enumerate_only, char *controller_path)
2144 {
2145         /* There are two components to imsm platform support, the ahci SATA
2146          * controller and the option-rom.  To find the SATA controller we
2147          * simply look in /sys/bus/pci/drivers/ahci to see if an ahci
2148          * controller with the Intel vendor id is present.  This approach
2149          * allows mdadm to leverage the kernel's ahci detection logic, with the
2150          * caveat that if ahci.ko is not loaded mdadm will not be able to
2151          * detect platform raid capabilities.  The option-rom resides in a
2152          * platform "Adapter ROM".  We scan for its signature to retrieve the
2153          * platform capabilities.  If raid support is disabled in the BIOS the
2154          * option-rom capability structure will not be available.
2155          */
2156         struct sys_dev *list, *hba;
2157         int host_base = 0;
2158         int port_count = 0;
2159         int result=1;
2160
2161         if (enumerate_only) {
2162                 if (check_env("IMSM_NO_PLATFORM"))
2163                         return 0;
2164                 list = find_intel_devices();
2165                 if (!list)
2166                         return 2;
2167                 for (hba = list; hba; hba = hba->next) {
2168                         if (find_imsm_capability(hba)) {
2169                                 result = 0;
2170                                 break;
2171                         }
2172                         else
2173                                 result = 2;
2174                 }
2175                 return result;
2176         }
2177
2178         list = find_intel_devices();
2179         if (!list) {
2180                 if (verbose > 0)
2181                         pr_err("no active Intel(R) RAID controller found.\n");
2182                 return 2;
2183         } else if (verbose > 0)
2184                 print_found_intel_controllers(list);
2185
2186         for (hba = list; hba; hba = hba->next) {
2187                 if (controller_path && (compare_paths(hba->path, controller_path) != 0))
2188                         continue;
2189                 if (!find_imsm_capability(hba)) {
2190                         char buf[PATH_MAX];
2191                         pr_err("imsm capabilities not found for controller: %s (type %s)\n",
2192                                   hba->type == SYS_DEV_VMD ? vmd_domain_to_controller(hba, buf) : hba->path,
2193                                   get_sys_dev_type(hba->type));
2194                         continue;
2195                 }
2196                 result = 0;
2197         }
2198
2199         if (controller_path && result == 1) {
2200                 pr_err("no active Intel(R) RAID controller found under %s\n",
2201                                 controller_path);
2202                 return result;
2203         }
2204
2205         const struct orom_entry *entry;
2206
2207         for (entry = orom_entries; entry; entry = entry->next) {
2208                 if (entry->type == SYS_DEV_VMD) {
2209                         print_imsm_capability(&entry->orom);
2210                         for (hba = list; hba; hba = hba->next) {
2211                                 if (hba->type == SYS_DEV_VMD) {
2212                                         char buf[PATH_MAX];
2213                                         printf(" I/O Controller : %s (%s)\n",
2214                                                 vmd_domain_to_controller(hba, buf), get_sys_dev_type(hba->type));
2215                                         if (print_vmd_attached_devs(hba)) {
2216                                                 if (verbose > 0)
2217                                                         pr_err("failed to get devices attached to VMD domain.\n");
2218                                                 result |= 2;
2219                                         }
2220                                 }
2221                         }
2222                         printf("\n");
2223                         continue;
2224                 }
2225
2226                 print_imsm_capability(&entry->orom);
2227                 if (entry->type == SYS_DEV_NVME) {
2228                         for (hba = list; hba; hba = hba->next) {
2229                                 if (hba->type == SYS_DEV_NVME)
2230                                         printf("    NVMe Device : %s\n", hba->path);
2231                         }
2232                         printf("\n");
2233                         continue;
2234                 }
2235
2236                 struct devid_list *devid;
2237                 for (devid = entry->devid_list; devid; devid = devid->next) {
2238                         hba = device_by_id(devid->devid);
2239                         if (!hba)
2240                                 continue;
2241
2242                         printf(" I/O Controller : %s (%s)\n",
2243                                 hba->path, get_sys_dev_type(hba->type));
2244                         if (hba->type == SYS_DEV_SATA) {
2245                                 host_base = ahci_get_port_count(hba->path, &port_count);
2246                                 if (ahci_enumerate_ports(hba->path, port_count, host_base, verbose)) {
2247                                         if (verbose > 0)
2248                                                 pr_err("failed to enumerate ports on SATA controller at %s.\n", hba->pci_id);
2249                                         result |= 2;
2250                                 }
2251                         }
2252                 }
2253                 printf("\n");
2254         }
2255
2256         return result;
2257 }
2258
2259 static int export_detail_platform_imsm(int verbose, char *controller_path)
2260 {
2261         struct sys_dev *list, *hba;
2262         int result=1;
2263
2264         list = find_intel_devices();
2265         if (!list) {
2266                 if (verbose > 0)
2267                         pr_err("IMSM_DETAIL_PLATFORM_ERROR=NO_INTEL_DEVICES\n");
2268                 result = 2;
2269                 return result;
2270         }
2271
2272         for (hba = list; hba; hba = hba->next) {
2273                 if (controller_path && (compare_paths(hba->path,controller_path) != 0))
2274                         continue;
2275                 if (!find_imsm_capability(hba) && verbose > 0) {
2276                         char buf[PATH_MAX];
2277                         pr_err("IMSM_DETAIL_PLATFORM_ERROR=NO_IMSM_CAPABLE_DEVICE_UNDER_%s\n",
2278                         hba->type == SYS_DEV_VMD ? vmd_domain_to_controller(hba, buf) : hba->path);
2279                 }
2280                 else
2281                         result = 0;
2282         }
2283
2284         const struct orom_entry *entry;
2285
2286         for (entry = orom_entries; entry; entry = entry->next) {
2287                 if (entry->type == SYS_DEV_VMD) {
2288                         for (hba = list; hba; hba = hba->next)
2289                                 print_imsm_capability_export(&entry->orom);
2290                         continue;
2291                 }
2292                 print_imsm_capability_export(&entry->orom);
2293         }
2294
2295         return result;
2296 }
2297
2298 #endif
2299
2300 static int match_home_imsm(struct supertype *st, char *homehost)
2301 {
2302         /* the imsm metadata format does not specify any host
2303          * identification information.  We return -1 since we can never
2304          * confirm nor deny whether a given array is "meant" for this
2305          * host.  We rely on compare_super and the 'family_num' fields to
2306          * exclude member disks that do not belong, and we rely on
2307          * mdadm.conf to specify the arrays that should be assembled.
2308          * Auto-assembly may still pick up "foreign" arrays.
2309          */
2310
2311         return -1;
2312 }
2313
2314 static void uuid_from_super_imsm(struct supertype *st, int uuid[4])
2315 {
2316         /* The uuid returned here is used for:
2317          *  uuid to put into bitmap file (Create, Grow)
2318          *  uuid for backup header when saving critical section (Grow)
2319          *  comparing uuids when re-adding a device into an array
2320          *    In these cases the uuid required is that of the data-array,
2321          *    not the device-set.
2322          *  uuid to recognise same set when adding a missing device back
2323          *    to an array.   This is a uuid for the device-set.
2324          *
2325          * For each of these we can make do with a truncated
2326          * or hashed uuid rather than the original, as long as
2327          * everyone agrees.
2328          * In each case the uuid required is that of the data-array,
2329          * not the device-set.
2330          */
2331         /* imsm does not track uuid's so we synthesis one using sha1 on
2332          * - The signature (Which is constant for all imsm array, but no matter)
2333          * - the orig_family_num of the container
2334          * - the index number of the volume
2335          * - the 'serial' number of the volume.
2336          * Hopefully these are all constant.
2337          */
2338         struct intel_super *super = st->sb;
2339
2340         char buf[20];
2341         struct sha1_ctx ctx;
2342         struct imsm_dev *dev = NULL;
2343         __u32 family_num;
2344
2345         /* some mdadm versions failed to set ->orig_family_num, in which
2346          * case fall back to ->family_num.  orig_family_num will be
2347          * fixed up with the first metadata update.
2348          */
2349         family_num = super->anchor->orig_family_num;
2350         if (family_num == 0)
2351                 family_num = super->anchor->family_num;
2352         sha1_init_ctx(&ctx);
2353         sha1_process_bytes(super->anchor->sig, MPB_SIG_LEN, &ctx);
2354         sha1_process_bytes(&family_num, sizeof(__u32), &ctx);
2355         if (super->current_vol >= 0)
2356                 dev = get_imsm_dev(super, super->current_vol);
2357         if (dev) {
2358                 __u32 vol = super->current_vol;
2359                 sha1_process_bytes(&vol, sizeof(vol), &ctx);
2360                 sha1_process_bytes(dev->volume, MAX_RAID_SERIAL_LEN, &ctx);
2361         }
2362         sha1_finish_ctx(&ctx, buf);
2363         memcpy(uuid, buf, 4*4);
2364 }
2365
2366 #if 0
2367 static void
2368 get_imsm_numerical_version(struct imsm_super *mpb, int *m, int *p)
2369 {
2370         __u8 *v = get_imsm_version(mpb);
2371         __u8 *end = mpb->sig + MAX_SIGNATURE_LENGTH;
2372         char major[] = { 0, 0, 0 };
2373         char minor[] = { 0 ,0, 0 };
2374         char patch[] = { 0, 0, 0 };
2375         char *ver_parse[] = { major, minor, patch };
2376         int i, j;
2377
2378         i = j = 0;
2379         while (*v != '\0' && v < end) {
2380                 if (*v != '.' && j < 2)
2381                         ver_parse[i][j++] = *v;
2382                 else {
2383                         i++;
2384                         j = 0;
2385                 }
2386                 v++;
2387         }
2388
2389         *m = strtol(minor, NULL, 0);
2390         *p = strtol(patch, NULL, 0);
2391 }
2392 #endif
2393
2394 static __u32 migr_strip_blocks_resync(struct imsm_dev *dev)
2395 {
2396         /* migr_strip_size when repairing or initializing parity */
2397         struct imsm_map *map = get_imsm_map(dev, MAP_0);
2398         __u32 chunk = __le32_to_cpu(map->blocks_per_strip);
2399
2400         switch (get_imsm_raid_level(map)) {
2401         case 5:
2402         case 10:
2403                 return chunk;
2404         default:
2405                 return 128*1024 >> 9;
2406         }
2407 }
2408
2409 static __u32 migr_strip_blocks_rebuild(struct imsm_dev *dev)
2410 {
2411         /* migr_strip_size when rebuilding a degraded disk, no idea why
2412          * this is different than migr_strip_size_resync(), but it's good
2413          * to be compatible
2414          */
2415         struct imsm_map *map = get_imsm_map(dev, MAP_1);
2416         __u32 chunk = __le32_to_cpu(map->blocks_per_strip);
2417
2418         switch (get_imsm_raid_level(map)) {
2419         case 1:
2420         case 10:
2421                 if (map->num_members % map->num_domains == 0)
2422                         return 128*1024 >> 9;
2423                 else
2424                         return chunk;
2425         case 5:
2426                 return max((__u32) 64*1024 >> 9, chunk);
2427         default:
2428                 return 128*1024 >> 9;
2429         }
2430 }
2431
2432 static __u32 num_stripes_per_unit_resync(struct imsm_dev *dev)
2433 {
2434         struct imsm_map *lo = get_imsm_map(dev, MAP_0);
2435         struct imsm_map *hi = get_imsm_map(dev, MAP_1);
2436         __u32 lo_chunk = __le32_to_cpu(lo->blocks_per_strip);
2437         __u32 hi_chunk = __le32_to_cpu(hi->blocks_per_strip);
2438
2439         return max((__u32) 1, hi_chunk / lo_chunk);
2440 }
2441
2442 static __u32 num_stripes_per_unit_rebuild(struct imsm_dev *dev)
2443 {
2444         struct imsm_map *lo = get_imsm_map(dev, MAP_0);
2445         int level = get_imsm_raid_level(lo);
2446
2447         if (level == 1 || level == 10) {
2448                 struct imsm_map *hi = get_imsm_map(dev, MAP_1);
2449
2450                 return hi->num_domains;
2451         } else
2452                 return num_stripes_per_unit_resync(dev);
2453 }
2454
2455 static __u8 imsm_num_data_members(struct imsm_dev *dev, int second_map)
2456 {
2457         /* named 'imsm_' because raid0, raid1 and raid10
2458          * counter-intuitively have the same number of data disks
2459          */
2460         struct imsm_map *map = get_imsm_map(dev, second_map);
2461
2462         switch (get_imsm_raid_level(map)) {
2463         case 0:
2464                 return map->num_members;
2465                 break;
2466         case 1:
2467         case 10:
2468                 return map->num_members/2;
2469         case 5:
2470                 return map->num_members - 1;
2471         default:
2472                 dprintf("unsupported raid level\n");
2473                 return 0;
2474         }
2475 }
2476
2477 static __u32 parity_segment_depth(struct imsm_dev *dev)
2478 {
2479         struct imsm_map *map = get_imsm_map(dev, MAP_0);
2480         __u32 chunk =  __le32_to_cpu(map->blocks_per_strip);
2481
2482         switch(get_imsm_raid_level(map)) {
2483         case 1:
2484         case 10:
2485                 return chunk * map->num_domains;
2486         case 5:
2487                 return chunk * map->num_members;
2488         default:
2489                 return chunk;
2490         }
2491 }
2492
2493 static __u32 map_migr_block(struct imsm_dev *dev, __u32 block)
2494 {
2495         struct imsm_map *map = get_imsm_map(dev, MAP_1);
2496         __u32 chunk = __le32_to_cpu(map->blocks_per_strip);
2497         __u32 strip = block / chunk;
2498
2499         switch (get_imsm_raid_level(map)) {
2500         case 1:
2501         case 10: {
2502                 __u32 vol_strip = (strip * map->num_domains) + 1;
2503                 __u32 vol_stripe = vol_strip / map->num_members;
2504
2505                 return vol_stripe * chunk + block % chunk;
2506         } case 5: {
2507                 __u32 stripe = strip / (map->num_members - 1);
2508
2509                 return stripe * chunk + block % chunk;
2510         }
2511         default:
2512                 return 0;
2513         }
2514 }
2515
2516 static __u64 blocks_per_migr_unit(struct intel_super *super,
2517                                   struct imsm_dev *dev)
2518 {
2519         /* calculate the conversion factor between per member 'blocks'
2520          * (md/{resync,rebuild}_start) and imsm migration units, return
2521          * 0 for the 'not migrating' and 'unsupported migration' cases
2522          */
2523         if (!dev->vol.migr_state)
2524                 return 0;
2525
2526         switch (migr_type(dev)) {
2527         case MIGR_GEN_MIGR: {
2528                 struct migr_record *migr_rec = super->migr_rec;
2529                 return __le32_to_cpu(migr_rec->blocks_per_unit);
2530         }
2531         case MIGR_VERIFY:
2532         case MIGR_REPAIR:
2533         case MIGR_INIT: {
2534                 struct imsm_map *map = get_imsm_map(dev, MAP_0);
2535                 __u32 stripes_per_unit;
2536                 __u32 blocks_per_unit;
2537                 __u32 parity_depth;
2538                 __u32 migr_chunk;
2539                 __u32 block_map;
2540                 __u32 block_rel;
2541                 __u32 segment;
2542                 __u32 stripe;
2543                 __u8  disks;
2544
2545                 /* yes, this is really the translation of migr_units to
2546                  * per-member blocks in the 'resync' case
2547                  */
2548                 stripes_per_unit = num_stripes_per_unit_resync(dev);
2549                 migr_chunk = migr_strip_blocks_resync(dev);
2550                 disks = imsm_num_data_members(dev, MAP_0);
2551                 blocks_per_unit = stripes_per_unit * migr_chunk * disks;
2552                 stripe = __le16_to_cpu(map->blocks_per_strip) * disks;
2553                 segment = blocks_per_unit / stripe;
2554                 block_rel = blocks_per_unit - segment * stripe;
2555                 parity_depth = parity_segment_depth(dev);
2556                 block_map = map_migr_block(dev, block_rel);
2557                 return block_map + parity_depth * segment;
2558         }
2559         case MIGR_REBUILD: {
2560                 __u32 stripes_per_unit;
2561                 __u32 migr_chunk;
2562
2563                 stripes_per_unit = num_stripes_per_unit_rebuild(dev);
2564                 migr_chunk = migr_strip_blocks_rebuild(dev);
2565                 return migr_chunk * stripes_per_unit;
2566         }
2567         case MIGR_STATE_CHANGE:
2568         default:
2569                 return 0;
2570         }
2571 }
2572
2573 static int imsm_level_to_layout(int level)
2574 {
2575         switch (level) {
2576         case 0:
2577         case 1:
2578                 return 0;
2579         case 5:
2580         case 6:
2581                 return ALGORITHM_LEFT_ASYMMETRIC;
2582         case 10:
2583                 return 0x102;
2584         }
2585         return UnSet;
2586 }
2587
2588 /*******************************************************************************
2589  * Function:    read_imsm_migr_rec
2590  * Description: Function reads imsm migration record from last sector of disk
2591  * Parameters:
2592  *      fd      : disk descriptor
2593  *      super   : metadata info
2594  * Returns:
2595  *       0 : success,
2596  *      -1 : fail
2597  ******************************************************************************/
2598 static int read_imsm_migr_rec(int fd, struct intel_super *super)
2599 {
2600         int ret_val = -1;
2601         unsigned int sector_size = super->sector_size;
2602         unsigned long long dsize;
2603
2604         get_dev_size(fd, NULL, &dsize);
2605         if (lseek64(fd, dsize - (sector_size*MIGR_REC_SECTOR_POSITION),
2606                    SEEK_SET) < 0) {
2607                 pr_err("Cannot seek to anchor block: %s\n",
2608                        strerror(errno));
2609                 goto out;
2610         }
2611         if (read(fd, super->migr_rec_buf,
2612             MIGR_REC_BUF_SECTORS*sector_size) !=
2613             MIGR_REC_BUF_SECTORS*sector_size) {
2614                 pr_err("Cannot read migr record block: %s\n",
2615                        strerror(errno));
2616                 goto out;
2617         }
2618         ret_val = 0;
2619         if (sector_size == 4096)
2620                 convert_from_4k_imsm_migr_rec(super);
2621
2622 out:
2623         return ret_val;
2624 }
2625
2626 static struct imsm_dev *imsm_get_device_during_migration(
2627         struct intel_super *super)
2628 {
2629
2630         struct intel_dev *dv;
2631
2632         for (dv = super->devlist; dv; dv = dv->next) {
2633                 if (is_gen_migration(dv->dev))
2634                         return dv->dev;
2635         }
2636         return NULL;
2637 }
2638
2639 /*******************************************************************************
2640  * Function:    load_imsm_migr_rec
2641  * Description: Function reads imsm migration record (it is stored at the last
2642  *              sector of disk)
2643  * Parameters:
2644  *      super   : imsm internal array info
2645  *      info    : general array info
2646  * Returns:
2647  *       0 : success
2648  *      -1 : fail
2649  *      -2 : no migration in progress
2650  ******************************************************************************/
2651 static int load_imsm_migr_rec(struct intel_super *super, struct mdinfo *info)
2652 {
2653         struct mdinfo *sd;
2654         struct dl *dl;
2655         char nm[30];
2656         int retval = -1;
2657         int fd = -1;
2658         struct imsm_dev *dev;
2659         struct imsm_map *map;
2660         int slot = -1;
2661
2662         /* find map under migration */
2663         dev = imsm_get_device_during_migration(super);
2664         /* nothing to load,no migration in progress?
2665         */
2666         if (dev == NULL)
2667                 return -2;
2668
2669         if (info) {
2670                 for (sd = info->devs ; sd ; sd = sd->next) {
2671                         /* read only from one of the first two slots */
2672                         if ((sd->disk.raid_disk < 0) ||
2673                             (sd->disk.raid_disk > 1))
2674                                 continue;
2675
2676                         sprintf(nm, "%d:%d", sd->disk.major, sd->disk.minor);
2677                         fd = dev_open(nm, O_RDONLY);
2678                         if (fd >= 0)
2679                                 break;
2680                 }
2681         }
2682         if (fd < 0) {
2683                 map = get_imsm_map(dev, MAP_0);
2684                 for (dl = super->disks; dl; dl = dl->next) {
2685                         /* skip spare and failed disks
2686                         */
2687                         if (dl->index < 0)
2688                                 continue;
2689                         /* read only from one of the first two slots */
2690                         if (map)
2691                                 slot = get_imsm_disk_slot(map, dl->index);
2692                         if (map == NULL || slot > 1 || slot < 0)
2693                                 continue;
2694                         sprintf(nm, "%d:%d", dl->major, dl->minor);
2695                         fd = dev_open(nm, O_RDONLY);
2696                         if (fd >= 0)
2697                                 break;
2698                 }
2699         }
2700         if (fd < 0)
2701                 goto out;
2702         retval = read_imsm_migr_rec(fd, super);
2703
2704 out:
2705         if (fd >= 0)
2706                 close(fd);
2707         return retval;
2708 }
2709
2710 #ifndef MDASSEMBLE
2711 /*******************************************************************************
2712  * function: imsm_create_metadata_checkpoint_update
2713  * Description: It creates update for checkpoint change.
2714  * Parameters:
2715  *      super   : imsm internal array info
2716  *      u       : pointer to prepared update
2717  * Returns:
2718  *      Uptate length.
2719  *      If length is equal to 0, input pointer u contains no update
2720  ******************************************************************************/
2721 static int imsm_create_metadata_checkpoint_update(
2722         struct intel_super *super,
2723         struct imsm_update_general_migration_checkpoint **u)
2724 {
2725
2726         int update_memory_size = 0;
2727
2728         dprintf("(enter)\n");
2729
2730         if (u == NULL)
2731                 return 0;
2732         *u = NULL;
2733
2734         /* size of all update data without anchor */
2735         update_memory_size =
2736                 sizeof(struct imsm_update_general_migration_checkpoint);
2737
2738         *u = xcalloc(1, update_memory_size);
2739         if (*u == NULL) {
2740                 dprintf("error: cannot get memory\n");
2741                 return 0;
2742         }
2743         (*u)->type = update_general_migration_checkpoint;
2744         (*u)->curr_migr_unit = __le32_to_cpu(super->migr_rec->curr_migr_unit);
2745         dprintf("prepared for %u\n", (*u)->curr_migr_unit);
2746
2747         return update_memory_size;
2748 }
2749
2750 static void imsm_update_metadata_locally(struct supertype *st,
2751                                          void *buf, int len);
2752
2753 /*******************************************************************************
2754  * Function:    write_imsm_migr_rec
2755  * Description: Function writes imsm migration record
2756  *              (at the last sector of disk)
2757  * Parameters:
2758  *      super   : imsm internal array info
2759  * Returns:
2760  *       0 : success
2761  *      -1 : if fail
2762  ******************************************************************************/
2763 static int write_imsm_migr_rec(struct supertype *st)
2764 {
2765         struct intel_super *super = st->sb;
2766         unsigned int sector_size = super->sector_size;
2767         unsigned long long dsize;
2768         char nm[30];
2769         int fd = -1;
2770         int retval = -1;
2771         struct dl *sd;
2772         int len;
2773         struct imsm_update_general_migration_checkpoint *u;
2774         struct imsm_dev *dev;
2775         struct imsm_map *map;
2776
2777         /* find map under migration */
2778         dev = imsm_get_device_during_migration(super);
2779         /* if no migration, write buffer anyway to clear migr_record
2780          * on disk based on first available device
2781         */
2782         if (dev == NULL)
2783                 dev = get_imsm_dev(super, super->current_vol < 0 ? 0 :
2784                                           super->current_vol);
2785
2786         map = get_imsm_map(dev, MAP_0);
2787
2788         if (sector_size == 4096)
2789                 convert_to_4k_imsm_migr_rec(super);
2790         for (sd = super->disks ; sd ; sd = sd->next) {
2791                 int slot = -1;
2792
2793                 /* skip failed and spare devices */
2794                 if (sd->index < 0)
2795                         continue;
2796                 /* write to 2 first slots only */
2797                 if (map)
2798                         slot = get_imsm_disk_slot(map, sd->index);
2799                 if (map == NULL || slot > 1 || slot < 0)
2800                         continue;
2801
2802                 sprintf(nm, "%d:%d", sd->major, sd->minor);
2803                 fd = dev_open(nm, O_RDWR);
2804                 if (fd < 0)
2805                         continue;
2806                 get_dev_size(fd, NULL, &dsize);
2807                 if (lseek64(fd, dsize - (MIGR_REC_SECTOR_POSITION*sector_size),
2808                     SEEK_SET) < 0) {
2809                         pr_err("Cannot seek to anchor block: %s\n",
2810                                strerror(errno));
2811                         goto out;
2812                 }
2813                 if (write(fd, super->migr_rec_buf,
2814                     MIGR_REC_BUF_SECTORS*sector_size) !=
2815                     MIGR_REC_BUF_SECTORS*sector_size) {
2816                         pr_err("Cannot write migr record block: %s\n",
2817                                strerror(errno));
2818                         goto out;
2819                 }
2820                 close(fd);
2821                 fd = -1;
2822         }
2823         if (sector_size == 4096)
2824                 convert_from_4k_imsm_migr_rec(super);
2825         /* update checkpoint information in metadata */
2826         len = imsm_create_metadata_checkpoint_update(super, &u);
2827         if (len <= 0) {
2828                 dprintf("imsm: Cannot prepare update\n");
2829                 goto out;
2830         }
2831         /* update metadata locally */
2832         imsm_update_metadata_locally(st, u, len);
2833         /* and possibly remotely */
2834         if (st->update_tail) {
2835                 append_metadata_update(st, u, len);
2836                 /* during reshape we do all work inside metadata handler
2837                  * manage_reshape(), so metadata update has to be triggered
2838                  * insida it
2839                  */
2840                 flush_metadata_updates(st);
2841                 st->update_tail = &st->updates;
2842         } else
2843                 free(u);
2844
2845         retval = 0;
2846  out:
2847         if (fd >= 0)
2848                 close(fd);
2849         return retval;
2850 }
2851 #endif /* MDASSEMBLE */
2852
2853 /* spare/missing disks activations are not allowe when
2854  * array/container performs reshape operation, because
2855  * all arrays in container works on the same disks set
2856  */
2857 int imsm_reshape_blocks_arrays_changes(struct intel_super *super)
2858 {
2859         int rv = 0;
2860         struct intel_dev *i_dev;
2861         struct imsm_dev *dev;
2862
2863         /* check whole container
2864          */
2865         for (i_dev = super->devlist; i_dev; i_dev = i_dev->next) {
2866                 dev = i_dev->dev;
2867                 if (is_gen_migration(dev)) {
2868                         /* No repair during any migration in container
2869                          */
2870                         rv = 1;
2871                         break;
2872                 }
2873         }
2874         return rv;
2875 }
2876 static unsigned long long imsm_component_size_aligment_check(int level,
2877                                               int chunk_size,
2878                                               unsigned int sector_size,
2879                                               unsigned long long component_size)
2880 {
2881         unsigned int component_size_alligment;
2882
2883         /* check component size aligment
2884         */
2885         component_size_alligment = component_size % (chunk_size/sector_size);
2886
2887         dprintf("(Level: %i, chunk_size = %i, component_size = %llu), component_size_alligment = %u\n",
2888                 level, chunk_size, component_size,
2889                 component_size_alligment);
2890
2891         if (component_size_alligment && (level != 1) && (level != UnSet)) {
2892                 dprintf("imsm: reported component size alligned from %llu ",
2893                         component_size);
2894                 component_size -= component_size_alligment;
2895                 dprintf_cont("to %llu (%i).\n",
2896                         component_size, component_size_alligment);
2897         }
2898
2899         return component_size;
2900 }
2901
2902 static void getinfo_super_imsm_volume(struct supertype *st, struct mdinfo *info, char *dmap)
2903 {
2904         struct intel_super *super = st->sb;
2905         struct migr_record *migr_rec = super->migr_rec;
2906         struct imsm_dev *dev = get_imsm_dev(super, super->current_vol);
2907         struct imsm_map *map = get_imsm_map(dev, MAP_0);
2908         struct imsm_map *prev_map = get_imsm_map(dev, MAP_1);
2909         struct imsm_map *map_to_analyse = map;
2910         struct dl *dl;
2911         int map_disks = info->array.raid_disks;
2912
2913         memset(info, 0, sizeof(*info));
2914         if (prev_map)
2915                 map_to_analyse = prev_map;
2916
2917         dl = super->current_disk;
2918
2919         info->container_member    = super->current_vol;
2920         info->array.raid_disks    = map->num_members;
2921         info->array.level         = get_imsm_raid_level(map_to_analyse);
2922         info->array.layout        = imsm_level_to_layout(info->array.level);
2923         info->array.md_minor      = -1;
2924         info->array.ctime         = 0;
2925         info->array.utime         = 0;
2926         info->array.chunk_size    =
2927                 __le16_to_cpu(map_to_analyse->blocks_per_strip) << 9;
2928         info->array.state         = !dev->vol.dirty;
2929         info->custom_array_size   = __le32_to_cpu(dev->size_high);
2930         info->custom_array_size   <<= 32;
2931         info->custom_array_size   |= __le32_to_cpu(dev->size_low);
2932         info->recovery_blocked = imsm_reshape_blocks_arrays_changes(st->sb);
2933
2934         if (is_gen_migration(dev)) {
2935                 info->reshape_active = 1;
2936                 info->new_level = get_imsm_raid_level(map);
2937                 info->new_layout = imsm_level_to_layout(info->new_level);
2938                 info->new_chunk = __le16_to_cpu(map->blocks_per_strip) << 9;
2939                 info->delta_disks = map->num_members - prev_map->num_members;
2940                 if (info->delta_disks) {
2941                         /* this needs to be applied to every array
2942                          * in the container.
2943                          */
2944                         info->reshape_active = CONTAINER_RESHAPE;
2945                 }
2946                 /* We shape information that we give to md might have to be
2947                  * modify to cope with md's requirement for reshaping arrays.
2948                  * For example, when reshaping a RAID0, md requires it to be
2949                  * presented as a degraded RAID4.
2950                  * Also if a RAID0 is migrating to a RAID5 we need to specify
2951                  * the array as already being RAID5, but the 'before' layout
2952                  * is a RAID4-like layout.
2953                  */
2954                 switch (info->array.level) {
2955                 case 0:
2956                         switch(info->new_level) {
2957                         case 0:
2958                                 /* conversion is happening as RAID4 */
2959                                 info->array.level = 4;
2960                                 info->array.raid_disks += 1;
2961                                 break;
2962                         case 5:
2963                                 /* conversion is happening as RAID5 */
2964                                 info->array.level = 5;
2965                                 info->array.layout = ALGORITHM_PARITY_N;
2966                                 info->delta_disks -= 1;
2967                                 break;
2968                         default:
2969                                 /* FIXME error message */
2970                                 info->array.level = UnSet;
2971                                 break;
2972                         }
2973                         break;
2974                 }
2975         } else {
2976                 info->new_level = UnSet;
2977                 info->new_layout = UnSet;
2978                 info->new_chunk = info->array.chunk_size;
2979                 info->delta_disks = 0;
2980         }
2981
2982         if (dl) {
2983                 info->disk.major = dl->major;
2984                 info->disk.minor = dl->minor;
2985                 info->disk.number = dl->index;
2986                 info->disk.raid_disk = get_imsm_disk_slot(map_to_analyse,
2987                                                           dl->index);
2988         }
2989
2990         info->data_offset         = pba_of_lba0(map_to_analyse);
2991
2992         if (info->array.level == 5) {
2993                 info->component_size = num_data_stripes(map_to_analyse) *
2994                                        map_to_analyse->blocks_per_strip;
2995         } else {
2996                 info->component_size = blocks_per_member(map_to_analyse);
2997         }
2998
2999         info->component_size = imsm_component_size_aligment_check(
3000                                                         info->array.level,
3001                                                         info->array.chunk_size,
3002                                                         super->sector_size,
3003                                                         info->component_size);
3004
3005         memset(info->uuid, 0, sizeof(info->uuid));
3006         info->recovery_start = MaxSector;
3007
3008         info->reshape_progress = 0;
3009         info->resync_start = MaxSector;
3010         if ((map_to_analyse->map_state == IMSM_T_STATE_UNINITIALIZED ||
3011             dev->vol.dirty) &&
3012             imsm_reshape_blocks_arrays_changes(super) == 0) {
3013                 info->resync_start = 0;
3014         }
3015         if (dev->vol.migr_state) {
3016                 switch (migr_type(dev)) {
3017                 case MIGR_REPAIR:
3018                 case MIGR_INIT: {
3019                         __u64 blocks_per_unit = blocks_per_migr_unit(super,
3020                                                                      dev);
3021                         __u64 units = __le32_to_cpu(dev->vol.curr_migr_unit);
3022
3023                         info->resync_start = blocks_per_unit * units;
3024                         break;
3025                 }
3026                 case MIGR_GEN_MIGR: {
3027                         __u64 blocks_per_unit = blocks_per_migr_unit(super,
3028                                                                      dev);
3029                         __u64 units = __le32_to_cpu(migr_rec->curr_migr_unit);
3030                         unsigned long long array_blocks;
3031                         int used_disks;
3032
3033                         if (__le32_to_cpu(migr_rec->ascending_migr) &&
3034                             (units <
3035                                 (__le32_to_cpu(migr_rec->num_migr_units)-1)) &&
3036                             (super->migr_rec->rec_status ==
3037                                         __cpu_to_le32(UNIT_SRC_IN_CP_AREA)))
3038                                 units++;
3039
3040                         info->reshape_progress = blocks_per_unit * units;
3041
3042                         dprintf("IMSM: General Migration checkpoint : %llu (%llu) -> read reshape progress : %llu\n",
3043                                 (unsigned long long)units,
3044                                 (unsigned long long)blocks_per_unit,
3045                                 info->reshape_progress);
3046
3047                         used_disks = imsm_num_data_members(dev, MAP_1);
3048                         if (used_disks > 0) {
3049                                 array_blocks = blocks_per_member(map) *
3050                                         used_disks;
3051                                 /* round array size down to closest MB
3052                                  */
3053                                 info->custom_array_size = (array_blocks
3054                                                 >> SECT_PER_MB_SHIFT)
3055                                                 << SECT_PER_MB_SHIFT;
3056                         }
3057                 }
3058                 case MIGR_VERIFY:
3059                         /* we could emulate the checkpointing of
3060                          * 'sync_action=check' migrations, but for now
3061                          * we just immediately complete them
3062                          */
3063                 case MIGR_REBUILD:
3064                         /* this is handled by container_content_imsm() */
3065                 case MIGR_STATE_CHANGE:
3066                         /* FIXME handle other migrations */
3067                 default:
3068                         /* we are not dirty, so... */
3069                         info->resync_start = MaxSector;
3070                 }
3071         }
3072
3073         strncpy(info->name, (char *) dev->volume, MAX_RAID_SERIAL_LEN);
3074         info->name[MAX_RAID_SERIAL_LEN] = 0;
3075
3076         info->array.major_version = -1;
3077         info->array.minor_version = -2;
3078         sprintf(info->text_version, "/%s/%d", st->container_devnm, info->container_member);
3079         info->safe_mode_delay = 4000;  /* 4 secs like the Matrix driver */
3080         uuid_from_super_imsm(st, info->uuid);
3081
3082         if (dmap) {
3083                 int i, j;
3084                 for (i=0; i<map_disks; i++) {
3085                         dmap[i] = 0;
3086                         if (i < info->array.raid_disks) {
3087                                 struct imsm_disk *dsk;
3088                                 j = get_imsm_disk_idx(dev, i, MAP_X);
3089                                 dsk = get_imsm_disk(super, j);
3090                                 if (dsk && (dsk->status & CONFIGURED_DISK))
3091                                         dmap[i] = 1;
3092                         }
3093                 }
3094         }
3095 }
3096
3097 static __u8 imsm_check_degraded(struct intel_super *super, struct imsm_dev *dev,
3098                                 int failed, int look_in_map);
3099
3100 static int imsm_count_failed(struct intel_super *super, struct imsm_dev *dev,
3101                              int look_in_map);
3102
3103 #ifndef MDASSEMBLE
3104 static void manage_second_map(struct intel_super *super, struct imsm_dev *dev)
3105 {
3106         if (is_gen_migration(dev)) {
3107                 int failed;
3108                 __u8 map_state;
3109                 struct imsm_map *map2 = get_imsm_map(dev, MAP_1);
3110
3111                 failed = imsm_count_failed(super, dev, MAP_1);
3112                 map_state = imsm_check_degraded(super, dev, failed, MAP_1);
3113                 if (map2->map_state != map_state) {
3114                         map2->map_state = map_state;
3115                         super->updates_pending++;
3116                 }
3117         }
3118 }
3119 #endif
3120
3121 static struct imsm_disk *get_imsm_missing(struct intel_super *super, __u8 index)
3122 {
3123         struct dl *d;
3124
3125         for (d = super->missing; d; d = d->next)
3126                 if (d->index == index)
3127                         return &d->disk;
3128         return NULL;
3129 }
3130
3131 static void getinfo_super_imsm(struct supertype *st, struct mdinfo *info, char *map)
3132 {
3133         struct intel_super *super = st->sb;
3134         struct imsm_disk *disk;
3135         int map_disks = info->array.raid_disks;
3136         int max_enough = -1;
3137         int i;
3138         struct imsm_super *mpb;
3139
3140         if (super->current_vol >= 0) {
3141                 getinfo_super_imsm_volume(st, info, map);
3142                 return;
3143         }
3144         memset(info, 0, sizeof(*info));
3145
3146         /* Set raid_disks to zero so that Assemble will always pull in valid
3147          * spares
3148          */
3149         info->array.raid_disks    = 0;
3150         info->array.level         = LEVEL_CONTAINER;
3151         info->array.layout        = 0;
3152         info->array.md_minor      = -1;
3153         info->array.ctime         = 0; /* N/A for imsm */
3154         info->array.utime         = 0;
3155         info->array.chunk_size    = 0;
3156
3157         info->disk.major = 0;
3158         info->disk.minor = 0;
3159         info->disk.raid_disk = -1;
3160         info->reshape_active = 0;
3161         info->array.major_version = -1;
3162         info->array.minor_version = -2;
3163         strcpy(info->text_version, "imsm");
3164         info->safe_mode_delay = 0;
3165         info->disk.number = -1;
3166         info->disk.state = 0;
3167         info->name[0] = 0;
3168         info->recovery_start = MaxSector;
3169         info->recovery_blocked = imsm_reshape_blocks_arrays_changes(st->sb);
3170
3171         /* do we have the all the insync disks that we expect? */
3172         mpb = super->anchor;
3173
3174         for (i = 0; i < mpb->num_raid_devs; i++) {
3175                 struct imsm_dev *dev = get_imsm_dev(super, i);
3176                 int failed, enough, j, missing = 0;
3177                 struct imsm_map *map;
3178                 __u8 state;
3179
3180                 failed = imsm_count_failed(super, dev, MAP_0);
3181                 state = imsm_check_degraded(super, dev, failed, MAP_0);
3182                 map = get_imsm_map(dev, MAP_0);
3183
3184                 /* any newly missing disks?
3185                  * (catches single-degraded vs double-degraded)
3186                  */
3187                 for (j = 0; j < map->num_members; j++) {
3188                         __u32 ord = get_imsm_ord_tbl_ent(dev, j, MAP_0);
3189                         __u32 idx = ord_to_idx(ord);
3190
3191                         if (!(ord & IMSM_ORD_REBUILD) &&
3192                             get_imsm_missing(super, idx)) {
3193                                 missing = 1;
3194                                 break;
3195                         }
3196                 }
3197
3198                 if (state == IMSM_T_STATE_FAILED)
3199                         enough = -1;
3200                 else if (state == IMSM_T_STATE_DEGRADED &&
3201                          (state != map->map_state || missing))
3202                         enough = 0;
3203                 else /* we're normal, or already degraded */
3204                         enough = 1;
3205                 if (is_gen_migration(dev) && missing) {
3206                         /* during general migration we need all disks
3207                          * that process is running on.
3208                          * No new missing disk is allowed.
3209                          */
3210                         max_enough = -1;
3211                         enough = -1;
3212                         /* no more checks necessary
3213                          */
3214                         break;
3215                 }
3216                 /* in the missing/failed disk case check to see
3217                  * if at least one array is runnable
3218                  */
3219                 max_enough = max(max_enough, enough);
3220         }
3221         dprintf("enough: %d\n", max_enough);
3222         info->container_enough = max_enough;
3223
3224         if (super->disks) {
3225                 __u32 reserved = imsm_reserved_sectors(super, super->disks);
3226
3227                 disk = &super->disks->disk;
3228                 info->data_offset = total_blocks(&super->disks->disk) - reserved;
3229                 info->component_size = reserved;
3230                 info->disk.state  = is_configured(disk) ? (1 << MD_DISK_ACTIVE) : 0;
3231                 /* we don't change info->disk.raid_disk here because
3232                  * this state will be finalized in mdmon after we have
3233                  * found the 'most fresh' version of the metadata
3234                  */
3235                 info->disk.state |= is_failed(disk) ? (1 << MD_DISK_FAULTY) : 0;
3236                 info->disk.state |= is_spare(disk) ? 0 : (1 << MD_DISK_SYNC);
3237         }
3238
3239         /* only call uuid_from_super_imsm when this disk is part of a populated container,
3240          * ->compare_super may have updated the 'num_raid_devs' field for spares
3241          */
3242         if (info->disk.state & (1 << MD_DISK_SYNC) || super->anchor->num_raid_devs)
3243                 uuid_from_super_imsm(st, info->uuid);
3244         else
3245                 memcpy(info->uuid, uuid_zero, sizeof(uuid_zero));
3246
3247         /* I don't know how to compute 'map' on imsm, so use safe default */
3248         if (map) {
3249                 int i;
3250                 for (i = 0; i < map_disks; i++)
3251                         map[i] = 1;
3252         }
3253
3254 }
3255
3256 /* allocates memory and fills disk in mdinfo structure
3257  * for each disk in array */
3258 struct mdinfo *getinfo_super_disks_imsm(struct supertype *st)
3259 {
3260         struct mdinfo *mddev;
3261         struct intel_super *super = st->sb;
3262         struct imsm_disk *disk;
3263         int count = 0;
3264         struct dl *dl;
3265         if (!super || !super->disks)
3266                 return NULL;
3267         dl = super->disks;
3268         mddev = xcalloc(1, sizeof(*mddev));
3269         while (dl) {
3270                 struct mdinfo *tmp;
3271                 disk = &dl->disk;
3272                 tmp = xcalloc(1, sizeof(*tmp));
3273                 if (mddev->devs)
3274                         tmp->next = mddev->devs;
3275                 mddev->devs = tmp;
3276                 tmp->disk.number = count++;
3277                 tmp->disk.major = dl->major;
3278                 tmp->disk.minor = dl->minor;
3279                 tmp->disk.state = is_configured(disk) ?
3280                                   (1 << MD_DISK_ACTIVE) : 0;
3281                 tmp->disk.state |= is_failed(disk) ? (1 << MD_DISK_FAULTY) : 0;
3282                 tmp->disk.state |= is_spare(disk) ? 0 : (1 << MD_DISK_SYNC);
3283                 tmp->disk.raid_disk = -1;
3284                 dl = dl->next;
3285         }
3286         return mddev;
3287 }
3288
3289 static int update_super_imsm(struct supertype *st, struct mdinfo *info,
3290                              char *update, char *devname, int verbose,
3291                              int uuid_set, char *homehost)
3292 {
3293         /* For 'assemble' and 'force' we need to return non-zero if any
3294          * change was made.  For others, the return value is ignored.
3295          * Update options are:
3296          *  force-one : This device looks a bit old but needs to be included,
3297          *        update age info appropriately.
3298          *  assemble: clear any 'faulty' flag to allow this device to
3299          *              be assembled.
3300          *  force-array: Array is degraded but being forced, mark it clean
3301          *         if that will be needed to assemble it.
3302          *
3303          *  newdev:  not used ????
3304          *  grow:  Array has gained a new device - this is currently for
3305          *              linear only
3306          *  resync: mark as dirty so a resync will happen.
3307          *  name:  update the name - preserving the homehost
3308          *  uuid:  Change the uuid of the array to match watch is given
3309          *
3310          * Following are not relevant for this imsm:
3311          *  sparc2.2 : update from old dodgey metadata
3312          *  super-minor: change the preferred_minor number
3313          *  summaries:  update redundant counters.
3314          *  homehost:  update the recorded homehost
3315          *  _reshape_progress: record new reshape_progress position.
3316          */
3317         int rv = 1;
3318         struct intel_super *super = st->sb;
3319         struct imsm_super *mpb;
3320
3321         /* we can only update container info */
3322         if (!super || super->current_vol >= 0 || !super->anchor)
3323                 return 1;
3324
3325         mpb = super->anchor;
3326
3327         if (strcmp(update, "uuid") == 0) {
3328                 /* We take this to mean that the family_num should be updated.
3329                  * However that is much smaller than the uuid so we cannot really
3330                  * allow an explicit uuid to be given.  And it is hard to reliably
3331                  * know if one was.
3332                  * So if !uuid_set we know the current uuid is random and just used
3333                  * the first 'int' and copy it to the other 3 positions.
3334                  * Otherwise we require the 4 'int's to be the same as would be the
3335                  * case if we are using a random uuid.  So an explicit uuid will be
3336                  * accepted as long as all for ints are the same... which shouldn't hurt
3337                  */
3338                 if (!uuid_set) {
3339                         info->uuid[1] = info->uuid[2] = info->uuid[3] = info->uuid[0];
3340                         rv = 0;
3341                 } else {
3342                         if (info->uuid[0] != info->uuid[1] ||
3343                             info->uuid[1] != info->uuid[2] ||
3344                             info->uuid[2] != info->uuid[3])
3345                                 rv = -1;
3346                         else
3347                                 rv = 0;
3348                 }
3349                 if (rv == 0)
3350                         mpb->orig_family_num = info->uuid[0];
3351         } else if (strcmp(update, "assemble") == 0)
3352                 rv = 0;
3353         else
3354                 rv = -1;
3355
3356         /* successful update? recompute checksum */
3357         if (rv == 0)
3358                 mpb->check_sum = __le32_to_cpu(__gen_imsm_checksum(mpb));
3359
3360         return rv;
3361 }
3362
3363 static size_t disks_to_mpb_size(int disks)
3364 {
3365         size_t size;
3366
3367         size = sizeof(struct imsm_super);
3368         size += (disks - 1) * sizeof(struct imsm_disk);
3369         size += 2 * sizeof(struct imsm_dev);
3370         /* up to 2 maps per raid device (-2 for imsm_maps in imsm_dev */
3371         size += (4 - 2) * sizeof(struct imsm_map);
3372         /* 4 possible disk_ord_tbl's */
3373         size += 4 * (disks - 1) * sizeof(__u32);
3374         /* maximum bbm log */
3375         size += sizeof(struct bbm_log);
3376
3377         return size;
3378 }
3379
3380 static __u64 avail_size_imsm(struct supertype *st, __u64 devsize,
3381                              unsigned long long data_offset)
3382 {
3383         if (devsize < (MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS))
3384                 return 0;
3385
3386         return devsize - (MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS);
3387 }
3388
3389 static void free_devlist(struct intel_super *super)
3390 {
3391         struct intel_dev *dv;
3392
3393         while (super->devlist) {
3394                 dv = super->devlist->next;
3395                 free(super->devlist->dev);
3396                 free(super->devlist);
3397                 super->devlist = dv;
3398         }
3399 }
3400
3401 static void imsm_copy_dev(struct imsm_dev *dest, struct imsm_dev *src)
3402 {
3403         memcpy(dest, src, sizeof_imsm_dev(src, 0));
3404 }
3405
3406 static int compare_super_imsm(struct supertype *st, struct supertype *tst)
3407 {
3408         /*
3409          * return:
3410          *  0 same, or first was empty, and second was copied
3411          *  1 second had wrong number
3412          *  2 wrong uuid
3413          *  3 wrong other info
3414          */
3415         struct intel_super *first = st->sb;
3416         struct intel_super *sec = tst->sb;
3417
3418         if (!first) {
3419                 st->sb = tst->sb;
3420                 tst->sb = NULL;
3421                 return 0;
3422         }
3423         /* in platform dependent environment test if the disks
3424          * use the same Intel hba
3425          * If not on Intel hba at all, allow anything.
3426          */
3427         if (!check_env("IMSM_NO_PLATFORM") && first->hba && sec->hba) {
3428                 if (first->hba->type != sec->hba->type) {
3429                         fprintf(stderr,
3430                                 "HBAs of devices do not match %s != %s\n",
3431                                 get_sys_dev_type(first->hba->type),
3432                                 get_sys_dev_type(sec->hba->type));
3433                         return 3;
3434                 }
3435                 if (first->orom != sec->orom) {
3436                         fprintf(stderr,
3437                                 "HBAs of devices do not match %s != %s\n",
3438                                 first->hba->pci_id, sec->hba->pci_id);
3439                         return 3;
3440                 }
3441         }
3442
3443         /* if an anchor does not have num_raid_devs set then it is a free
3444          * floating spare
3445          */
3446         if (first->anchor->num_raid_devs > 0 &&
3447             sec->anchor->num_raid_devs > 0) {
3448                 /* Determine if these disks might ever have been
3449                  * related.  Further disambiguation can only take place
3450                  * in load_super_imsm_all
3451                  */
3452                 __u32 first_family = first->anchor->orig_family_num;
3453                 __u32 sec_family = sec->anchor->orig_family_num;
3454
3455                 if (memcmp(first->anchor->sig, sec->anchor->sig,
3456                            MAX_SIGNATURE_LENGTH) != 0)
3457                         return 3;
3458
3459                 if (first_family == 0)
3460                         first_family = first->anchor->family_num;
3461                 if (sec_family == 0)
3462                         sec_family = sec->anchor->family_num;
3463
3464                 if (first_family != sec_family)
3465                         return 3;
3466
3467         }
3468
3469         /* if 'first' is a spare promote it to a populated mpb with sec's
3470          * family number
3471          */
3472         if (first->anchor->num_raid_devs == 0 &&
3473             sec->anchor->num_raid_devs > 0) {
3474                 int i;
3475                 struct intel_dev *dv;
3476                 struct imsm_dev *dev;
3477
3478                 /* we need to copy raid device info from sec if an allocation
3479                  * fails here we don't associate the spare
3480                  */
3481                 for (i = 0; i < sec->anchor->num_raid_devs; i++) {
3482                         dv = xmalloc(sizeof(*dv));
3483                         dev = xmalloc(sizeof_imsm_dev(get_imsm_dev(sec, i), 1));
3484                         dv->dev = dev;
3485                         dv->index = i;
3486                         dv->next = first->devlist;
3487                         first->devlist = dv;
3488                 }
3489                 if (i < sec->anchor->num_raid_devs) {
3490                         /* allocation failure */
3491                         free_devlist(first);
3492                         pr_err("imsm: failed to associate spare\n");
3493                         return 3;
3494                 }
3495                 first->anchor->num_raid_devs = sec->anchor->num_raid_devs;
3496                 first->anchor->orig_family_num = sec->anchor->orig_family_num;
3497                 first->anchor->family_num = sec->anchor->family_num;
3498                 memcpy(first->anchor->sig, sec->anchor->sig, MAX_SIGNATURE_LENGTH);
3499                 for (i = 0; i < sec->anchor->num_raid_devs; i++)
3500                         imsm_copy_dev(get_imsm_dev(first, i), get_imsm_dev(sec, i));
3501         }
3502
3503         return 0;
3504 }
3505
3506 static void fd2devname(int fd, char *name)
3507 {
3508         struct stat st;
3509         char path[256];
3510         char dname[PATH_MAX];
3511         char *nm;
3512         int rv;
3513
3514         name[0] = '\0';
3515         if (fstat(fd, &st) != 0)
3516                 return;
3517         sprintf(path, "/sys/dev/block/%d:%d",
3518                 major(st.st_rdev), minor(st.st_rdev));
3519
3520         rv = readlink(path, dname, sizeof(dname)-1);
3521         if (rv <= 0)
3522                 return;
3523
3524         dname[rv] = '\0';
3525         nm = strrchr(dname, '/');
3526         if (nm) {
3527                 nm++;
3528                 snprintf(name, MAX_RAID_SERIAL_LEN, "/dev/%s", nm);
3529         }
3530 }
3531
3532 static int nvme_get_serial(int fd, void *buf, size_t buf_len)
3533 {
3534         char path[60];
3535         char *name = fd2kname(fd);
3536
3537         if (!name)
3538                 return 1;
3539
3540         if (strncmp(name, "nvme", 4) != 0)
3541                 return 1;
3542
3543         snprintf(path, sizeof(path) - 1, "/sys/block/%s/device/serial", name);
3544
3545         return load_sys(path, buf, buf_len);
3546 }
3547
3548 extern int scsi_get_serial(int fd, void *buf, size_t buf_len);
3549
3550 static int imsm_read_serial(int fd, char *devname,
3551                             __u8 serial[MAX_RAID_SERIAL_LEN])
3552 {
3553         char buf[50];
3554         int rv;
3555         int len;
3556         char *dest;
3557         char *src;
3558         unsigned int i;
3559
3560         memset(buf, 0, sizeof(buf));
3561
3562         rv = nvme_get_serial(fd, buf, sizeof(buf));
3563
3564         if (rv)
3565                 rv = scsi_get_serial(fd, buf, sizeof(buf));
3566
3567         if (rv && check_env("IMSM_DEVNAME_AS_SERIAL")) {
3568                 memset(serial, 0, MAX_RAID_SERIAL_LEN);
3569                 fd2devname(fd, (char *) serial);
3570                 return 0;
3571         }
3572
3573         if (rv != 0) {
3574                 if (devname)
3575                         pr_err("Failed to retrieve serial for %s\n",
3576                                devname);
3577                 return rv;
3578         }
3579
3580         /* trim all whitespace and non-printable characters and convert
3581          * ':' to ';'
3582          */
3583         for (i = 0, dest = buf; i < sizeof(buf) && buf[i]; i++) {
3584                 src = &buf[i];
3585                 if (*src > 0x20) {
3586                         /* ':' is reserved for use in placeholder serial
3587                          * numbers for missing disks
3588                          */
3589                         if (*src == ':')
3590                                 *dest++ = ';';
3591                         else
3592                                 *dest++ = *src;
3593                 }
3594         }
3595         len = dest - buf;
3596         dest = buf;
3597
3598         /* truncate leading characters */
3599         if (len > MAX_RAID_SERIAL_LEN) {
3600                 dest += len - MAX_RAID_SERIAL_LEN;
3601                 len = MAX_RAID_SERIAL_LEN;
3602         }
3603
3604         memset(serial, 0, MAX_RAID_SERIAL_LEN);
3605         memcpy(serial, dest, len);
3606
3607         return 0;
3608 }
3609
3610 static int serialcmp(__u8 *s1, __u8 *s2)
3611 {
3612         return strncmp((char *) s1, (char *) s2, MAX_RAID_SERIAL_LEN);
3613 }
3614
3615 static void serialcpy(__u8 *dest, __u8 *src)
3616 {
3617         strncpy((char *) dest, (char *) src, MAX_RAID_SERIAL_LEN);
3618 }
3619
3620 static struct dl *serial_to_dl(__u8 *serial, struct intel_super *super)
3621 {
3622         struct dl *dl;
3623
3624         for (dl = super->disks; dl; dl = dl->next)
3625                 if (serialcmp(dl->serial, serial) == 0)
3626                         break;
3627
3628         return dl;
3629 }
3630
3631 static struct imsm_disk *
3632 __serial_to_disk(__u8 *serial, struct imsm_super *mpb, int *idx)
3633 {
3634         int i;
3635
3636         for (i = 0; i < mpb->num_disks; i++) {
3637                 struct imsm_disk *disk = __get_imsm_disk(mpb, i);
3638
3639                 if (serialcmp(disk->serial, serial) == 0) {
3640                         if (idx)
3641                                 *idx = i;
3642                         return disk;
3643                 }
3644         }
3645
3646         return NULL;
3647 }
3648
3649 static int
3650 load_imsm_disk(int fd, struct intel_super *super, char *devname, int keep_fd)
3651 {
3652         struct imsm_disk *disk;
3653         struct dl *dl;
3654         struct stat stb;
3655         int rv;
3656         char name[40];
3657         __u8 serial[MAX_RAID_SERIAL_LEN];
3658
3659         rv = imsm_read_serial(fd, devname, serial);
3660
3661         if (rv != 0)
3662                 return 2;
3663
3664         dl = xcalloc(1, sizeof(*dl));
3665
3666         fstat(fd, &stb);
3667         dl->major = major(stb.st_rdev);
3668         dl->minor = minor(stb.st_rdev);
3669         dl->next = super->disks;
3670         dl->fd = keep_fd ? fd : -1;
3671         assert(super->disks == NULL);
3672         super->disks = dl;
3673         serialcpy(dl->serial, serial);
3674         dl->index = -2;
3675         dl->e = NULL;
3676         fd2devname(fd, name);
3677         if (devname)
3678                 dl->devname = xstrdup(devname);
3679         else
3680                 dl->devname = xstrdup(name);
3681
3682         /* look up this disk's index in the current anchor */
3683         disk = __serial_to_disk(dl->serial, super->anchor, &dl->index);
3684         if (disk) {
3685                 dl->disk = *disk;
3686                 /* only set index on disks that are a member of a
3687                  * populated contianer, i.e. one with raid_devs
3688                  */
3689                 if (is_failed(&dl->disk))
3690                         dl->index = -2;
3691                 else if (is_spare(&dl->disk))
3692                         dl->index = -1;
3693         }
3694
3695         return 0;
3696 }
3697
3698 #ifndef MDASSEMBLE
3699 /* When migrating map0 contains the 'destination' state while map1
3700  * contains the current state.  When not migrating map0 contains the
3701  * current state.  This routine assumes that map[0].map_state is set to
3702  * the current array state before being called.
3703  *
3704  * Migration is indicated by one of the following states
3705  * 1/ Idle (migr_state=0 map0state=normal||unitialized||degraded||failed)
3706  * 2/ Initialize (migr_state=1 migr_type=MIGR_INIT map0state=normal
3707  *    map1state=unitialized)
3708  * 3/ Repair (Resync) (migr_state=1 migr_type=MIGR_REPAIR  map0state=normal
3709  *    map1state=normal)
3710  * 4/ Rebuild (migr_state=1 migr_type=MIGR_REBUILD map0state=normal
3711  *    map1state=degraded)
3712  * 5/ Migration (mig_state=1 migr_type=MIGR_GEN_MIGR map0state=normal
3713  *    map1state=normal)
3714  */
3715 static void migrate(struct imsm_dev *dev, struct intel_super *super,
3716                     __u8 to_state, int migr_type)
3717 {
3718         struct imsm_map *dest;
3719         struct imsm_map *src = get_imsm_map(dev, MAP_0);
3720
3721         dev->vol.migr_state = 1;
3722         set_migr_type(dev, migr_type);
3723         dev->vol.curr_migr_unit = 0;
3724         dest = get_imsm_map(dev, MAP_1);
3725
3726         /* duplicate and then set the target end state in map[0] */
3727         memcpy(dest, src, sizeof_imsm_map(src));
3728         if (migr_type == MIGR_REBUILD || migr_type ==  MIGR_GEN_MIGR) {
3729                 __u32 ord;
3730                 int i;
3731
3732                 for (i = 0; i < src->num_members; i++) {
3733                         ord = __le32_to_cpu(src->disk_ord_tbl[i]);
3734                         set_imsm_ord_tbl_ent(src, i, ord_to_idx(ord));
3735                 }
3736         }
3737
3738         if (migr_type == MIGR_GEN_MIGR)
3739                 /* Clear migration record */
3740                 memset(super->migr_rec, 0, sizeof(struct migr_record));
3741
3742         src->map_state = to_state;
3743 }
3744
3745 static void end_migration(struct imsm_dev *dev, struct intel_super *super,
3746                           __u8 map_state)
3747 {
3748         struct imsm_map *map = get_imsm_map(dev, MAP_0);
3749         struct imsm_map *prev = get_imsm_map(dev, dev->vol.migr_state == 0 ?
3750                                                     MAP_0 : MAP_1);
3751         int i, j;
3752
3753         /* merge any IMSM_ORD_REBUILD bits that were not successfully
3754          * completed in the last migration.
3755          *
3756          * FIXME add support for raid-level-migration
3757          */
3758         if (map_state != map->map_state && (is_gen_migration(dev) == 0) &&
3759             prev->map_state != IMSM_T_STATE_UNINITIALIZED) {
3760                 /* when final map state is other than expected
3761                  * merge maps (not for migration)
3762                  */
3763                 int failed;
3764
3765                 for (i = 0; i < prev->num_members; i++)
3766                         for (j = 0; j < map->num_members; j++)
3767                                 /* during online capacity expansion
3768                                  * disks position can be changed
3769                                  * if takeover is used
3770                                  */
3771                                 if (ord_to_idx(map->disk_ord_tbl[j]) ==
3772                                     ord_to_idx(prev->disk_ord_tbl[i])) {
3773                                         map->disk_ord_tbl[j] |=
3774                                                 prev->disk_ord_tbl[i];
3775                                         break;
3776                                 }
3777                 failed = imsm_count_failed(super, dev, MAP_0);
3778                 map_state = imsm_check_degraded(super, dev, failed, MAP_0);
3779         }
3780
3781         dev->vol.migr_state = 0;
3782         set_migr_type(dev, 0);
3783         dev->vol.curr_migr_unit = 0;
3784         map->map_state = map_state;
3785 }
3786 #endif
3787
3788 static int parse_raid_devices(struct intel_super *super)
3789 {
3790         int i;
3791         struct imsm_dev *dev_new;
3792         size_t len, len_migr;
3793         size_t max_len = 0;
3794         size_t space_needed = 0;
3795         struct imsm_super *mpb = super->anchor;
3796
3797         for (i = 0; i < super->anchor->num_raid_devs; i++) {
3798                 struct imsm_dev *dev_iter = __get_imsm_dev(super->anchor, i);
3799                 struct intel_dev *dv;
3800
3801                 len = sizeof_imsm_dev(dev_iter, 0);
3802                 len_migr = sizeof_imsm_dev(dev_iter, 1);
3803                 if (len_migr > len)
3804                         space_needed += len_migr - len;
3805
3806                 dv = xmalloc(sizeof(*dv));
3807                 if (max_len < len_migr)
3808                         max_len = len_migr;
3809                 if (max_len > len_migr)
3810                         space_needed += max_len - len_migr;
3811                 dev_new = xmalloc(max_len);
3812                 imsm_copy_dev(dev_new, dev_iter);
3813                 dv->dev = dev_new;
3814                 dv->index = i;
3815                 dv->next = super->devlist;
3816                 super->devlist = dv;
3817         }
3818
3819         /* ensure that super->buf is large enough when all raid devices
3820          * are migrating
3821          */
3822         if (__le32_to_cpu(mpb->mpb_size) + space_needed > super->len) {
3823                 void *buf;
3824
3825                 len = ROUND_UP(__le32_to_cpu(mpb->mpb_size) + space_needed,
3826                               super->sector_size);
3827                 if (posix_memalign(&buf, MAX_SECTOR_SIZE, len) != 0)
3828                         return 1;
3829
3830                 memcpy(buf, super->buf, super->len);
3831                 memset(buf + super->len, 0, len - super->len);
3832                 free(super->buf);
3833                 super->buf = buf;
3834                 super->len = len;
3835         }
3836
3837         super->extra_space += space_needed;
3838
3839         return 0;
3840 }
3841
3842 /*******************************************************************************
3843  * Function:    check_mpb_migr_compatibility
3844  * Description: Function checks for unsupported migration features:
3845  *              - migration optimization area (pba_of_lba0)
3846  *              - descending reshape (ascending_migr)
3847  * Parameters:
3848  *      super   : imsm metadata information
3849  * Returns:
3850  *       0 : migration is compatible
3851  *      -1 : migration is not compatible
3852  ******************************************************************************/
3853 int check_mpb_migr_compatibility(struct intel_super *super)
3854 {
3855         struct imsm_map *map0, *map1;
3856         struct migr_record *migr_rec = super->migr_rec;
3857         int i;
3858
3859         for (i = 0; i < super->anchor->num_raid_devs; i++) {
3860                 struct imsm_dev *dev_iter = __get_imsm_dev(super->anchor, i);
3861
3862                 if (dev_iter &&
3863                     dev_iter->vol.migr_state == 1 &&
3864                     dev_iter->vol.migr_type == MIGR_GEN_MIGR) {
3865                         /* This device is migrating */
3866                         map0 = get_imsm_map(dev_iter, MAP_0);
3867                         map1 = get_imsm_map(dev_iter, MAP_1);
3868                         if (pba_of_lba0(map0) != pba_of_lba0(map1))
3869                                 /* migration optimization area was used */
3870                                 return -1;
3871                         if (migr_rec->ascending_migr == 0
3872                                 && migr_rec->dest_depth_per_unit > 0)
3873                                 /* descending reshape not supported yet */
3874                                 return -1;
3875                 }
3876         }
3877         return 0;
3878 }
3879
3880 static void __free_imsm(struct intel_super *super, int free_disks);
3881
3882 /* load_imsm_mpb - read matrix metadata
3883  * allocates super->mpb to be freed by free_imsm
3884  */
3885 static int load_imsm_mpb(int fd, struct intel_super *super, char *devname)
3886 {
3887         unsigned long long dsize;
3888         unsigned long long sectors;
3889         unsigned int sector_size = super->sector_size;
3890         struct stat;
3891         struct imsm_super *anchor;
3892         __u32 check_sum;
3893
3894         get_dev_size(fd, NULL, &dsize);
3895         if (dsize < 2*sector_size) {
3896                 if (devname)
3897                         pr_err("%s: device to small for imsm\n",
3898                                devname);
3899                 return 1;
3900         }
3901
3902         if (lseek64(fd, dsize - (sector_size * 2), SEEK_SET) < 0) {
3903                 if (devname)
3904                         pr_err("Cannot seek to anchor block on %s: %s\n",
3905                                devname, strerror(errno));
3906                 return 1;
3907         }
3908
3909         if (posix_memalign((void **)&anchor, sector_size, sector_size) != 0) {
3910                 if (devname)
3911                         pr_err("Failed to allocate imsm anchor buffer on %s\n", devname);
3912                 return 1;
3913         }
3914         if (read(fd, anchor, sector_size) != sector_size) {
3915                 if (devname)
3916                         pr_err("Cannot read anchor block on %s: %s\n",
3917                                devname, strerror(errno));
3918                 free(anchor);
3919                 return 1;
3920         }
3921
3922         if (strncmp((char *) anchor->sig, MPB_SIGNATURE, MPB_SIG_LEN) != 0) {
3923                 if (devname)
3924                         pr_err("no IMSM anchor on %s\n", devname);
3925                 free(anchor);
3926                 return 2;
3927         }
3928
3929         __free_imsm(super, 0);
3930         /*  reload capability and hba */
3931
3932         /* capability and hba must be updated with new super allocation */
3933         find_intel_hba_capability(fd, super, devname);
3934         super->len = ROUND_UP(anchor->mpb_size, sector_size);
3935         if (posix_memalign(&super->buf, MAX_SECTOR_SIZE, super->len) != 0) {
3936                 if (devname)
3937                         pr_err("unable to allocate %zu byte mpb buffer\n",
3938                                super->len);
3939                 free(anchor);
3940                 return 2;
3941         }
3942         memcpy(super->buf, anchor, sector_size);
3943
3944         sectors = mpb_sectors(anchor, sector_size) - 1;
3945         free(anchor);
3946
3947         if (posix_memalign(&super->migr_rec_buf, sector_size,
3948             MIGR_REC_BUF_SECTORS*sector_size) != 0) {
3949                 pr_err("could not allocate migr_rec buffer\n");
3950                 free(super->buf);
3951                 return 2;
3952         }
3953         super->clean_migration_record_by_mdmon = 0;
3954
3955         if (!sectors) {
3956                 check_sum = __gen_imsm_checksum(super->anchor);
3957                 if (check_sum != __le32_to_cpu(super->anchor->check_sum)) {
3958                         if (devname)
3959                                 pr_err("IMSM checksum %x != %x on %s\n",
3960                                        check_sum,
3961                                        __le32_to_cpu(super->anchor->check_sum),
3962                                        devname);
3963                         return 2;
3964                 }
3965
3966                 return 0;
3967         }
3968
3969         /* read the extended mpb */
3970         if (lseek64(fd, dsize - (sector_size * (2 + sectors)), SEEK_SET) < 0) {
3971                 if (devname)
3972                         pr_err("Cannot seek to extended mpb on %s: %s\n",
3973                                devname, strerror(errno));
3974                 return 1;
3975         }
3976
3977         if ((unsigned int)read(fd, super->buf + sector_size,
3978                     super->len - sector_size) != super->len - sector_size) {
3979                 if (devname)
3980                         pr_err("Cannot read extended mpb on %s: %s\n",
3981                                devname, strerror(errno));
3982                 return 2;
3983         }
3984
3985         check_sum = __gen_imsm_checksum(super->anchor);
3986         if (check_sum != __le32_to_cpu(super->anchor->check_sum)) {
3987                 if (devname)
3988                         pr_err("IMSM checksum %x != %x on %s\n",
3989                                check_sum, __le32_to_cpu(super->anchor->check_sum),
3990                                devname);
3991                 return 3;
3992         }
3993
3994         return 0;
3995 }
3996
3997 static int read_imsm_migr_rec(int fd, struct intel_super *super);
3998
3999 /* clears hi bits in metadata if MPB_ATTRIB_2TB_DISK not set */
4000 static void clear_hi(struct intel_super *super)
4001 {
4002         struct imsm_super *mpb = super->anchor;
4003         int i, n;
4004         if (mpb->attributes & MPB_ATTRIB_2TB_DISK)
4005                 return;
4006         for (i = 0; i < mpb->num_disks; ++i) {
4007                 struct imsm_disk *disk = &mpb->disk[i];
4008                 disk->total_blocks_hi = 0;
4009         }
4010         for (i = 0; i < mpb->num_raid_devs; ++i) {
4011                 struct imsm_dev *dev = get_imsm_dev(super, i);
4012                 if (!dev)
4013                         return;
4014                 for (n = 0; n < 2; ++n) {
4015                         struct imsm_map *map = get_imsm_map(dev, n);
4016                         if (!map)
4017                                 continue;
4018                         map->pba_of_lba0_hi = 0;
4019                         map->blocks_per_member_hi = 0;
4020                         map->num_data_stripes_hi = 0;
4021                 }
4022         }
4023 }
4024
4025 static int
4026 load_and_parse_mpb(int fd, struct intel_super *super, char *devname, int keep_fd)
4027 {
4028         int err;
4029
4030         err = load_imsm_mpb(fd, super, devname);
4031         if (err)
4032                 return err;
4033         if (super->sector_size == 4096)
4034                 convert_from_4k(super);
4035         err = load_imsm_disk(fd, super, devname, keep_fd);
4036         if (err)
4037                 return err;
4038         err = parse_raid_devices(super);
4039         if (err)
4040                 return err;
4041         err = load_bbm_log(super);
4042         clear_hi(super);
4043         return err;
4044 }
4045
4046 static void __free_imsm_disk(struct dl *d)
4047 {
4048         if (d->fd >= 0)
4049                 close(d->fd);
4050         if (d->devname)
4051                 free(d->devname);
4052         if (d->e)
4053                 free(d->e);
4054         free(d);
4055
4056 }
4057
4058 static void free_imsm_disks(struct intel_super *super)
4059 {
4060         struct dl *d;
4061
4062         while (super->disks) {
4063                 d = super->disks;
4064                 super->disks = d->next;
4065                 __free_imsm_disk(d);
4066         }
4067         while (super->disk_mgmt_list) {
4068                 d = super->disk_mgmt_list;
4069                 super->disk_mgmt_list = d->next;
4070                 __free_imsm_disk(d);
4071         }
4072         while (super->missing) {
4073                 d = super->missing;
4074                 super->missing = d->next;
4075                 __free_imsm_disk(d);
4076         }
4077
4078 }
4079
4080 /* free all the pieces hanging off of a super pointer */
4081 static void __free_imsm(struct intel_super *super, int free_disks)
4082 {
4083         struct intel_hba *elem, *next;
4084
4085         if (super->buf) {
4086                 free(super->buf);
4087                 super->buf = NULL;
4088         }
4089         /* unlink capability description */
4090         super->orom = NULL;
4091         if (super->migr_rec_buf) {
4092                 free(super->migr_rec_buf);
4093                 super->migr_rec_buf = NULL;
4094         }
4095         if (free_disks)
4096                 free_imsm_disks(super);
4097         free_devlist(super);
4098         elem = super->hba;
4099         while (elem) {
4100                 if (elem->path)
4101                         free((void *)elem->path);
4102                 next = elem->next;
4103                 free(elem);
4104                 elem = next;
4105         }
4106         if (super->bbm_log)
4107                 free(super->bbm_log);
4108         super->hba = NULL;
4109 }
4110
4111 static void free_imsm(struct intel_super *super)
4112 {
4113         __free_imsm(super, 1);
4114         free(super);
4115 }
4116
4117 static void free_super_imsm(struct supertype *st)
4118 {
4119         struct intel_super *super = st->sb;
4120
4121         if (!super)
4122                 return;
4123
4124         free_imsm(super);
4125         st->sb = NULL;
4126 }
4127
4128 static struct intel_super *alloc_super(void)
4129 {
4130         struct intel_super *super = xcalloc(1, sizeof(*super));
4131
4132         super->current_vol = -1;
4133         super->create_offset = ~((unsigned long long) 0);
4134         return super;
4135 }
4136
4137 /*
4138  * find and allocate hba and OROM/EFI based on valid fd of RAID component device
4139  */
4140 static int find_intel_hba_capability(int fd, struct intel_super *super, char *devname)
4141 {
4142         struct sys_dev *hba_name;
4143         int rv = 0;
4144
4145         if (fd < 0 || check_env("IMSM_NO_PLATFORM")) {
4146                 super->orom = NULL;
4147                 super->hba = NULL;
4148                 return 0;
4149         }
4150         hba_name = find_disk_attached_hba(fd, NULL);
4151         if (!hba_name) {
4152                 if (devname)
4153                         pr_err("%s is not attached to Intel(R) RAID controller.\n",
4154                                devname);
4155                 return 1;
4156         }
4157         rv = attach_hba_to_super(super, hba_name);
4158         if (rv == 2) {
4159                 if (devname) {
4160                         struct intel_hba *hba = super->hba;
4161
4162                         pr_err("%s is attached to Intel(R) %s %s (%s),\n"
4163                                 "    but the container is assigned to Intel(R) %s %s (",
4164                                 devname,
4165                                 get_sys_dev_type(hba_name->type),
4166                                 hba_name->type == SYS_DEV_VMD ? "domain" : "RAID controller",
4167                                 hba_name->pci_id ? : "Err!",
4168                                 get_sys_dev_type(super->hba->type),
4169                                 hba->type == SYS_DEV_VMD ? "domain" : "RAID controller");
4170
4171                         while (hba) {
4172                                 fprintf(stderr, "%s", hba->pci_id ? : "Err!");
4173                                 if (hba->next)
4174                                         fprintf(stderr, ", ");
4175                                 hba = hba->next;
4176                         }
4177                         fprintf(stderr, ").\n"
4178                                 "    Mixing devices attached to different %s is not allowed.\n",
4179                                 hba_name->type == SYS_DEV_VMD ? "VMD domains" : "controllers");
4180                 }
4181                 return 2;
4182         }
4183         super->orom = find_imsm_capability(hba_name);
4184         if (!super->orom)
4185                 return 3;
4186
4187         return 0;
4188 }
4189
4190 /* find_missing - helper routine for load_super_imsm_all that identifies
4191  * disks that have disappeared from the system.  This routine relies on
4192  * the mpb being uptodate, which it is at load time.
4193  */
4194 static int find_missing(struct intel_super *super)
4195 {
4196         int i;
4197         struct imsm_super *mpb = super->anchor;
4198         struct dl *dl;
4199         struct imsm_disk *disk;
4200
4201         for (i = 0; i < mpb->num_disks; i++) {
4202                 disk = __get_imsm_disk(mpb, i);
4203                 dl = serial_to_dl(disk->serial, super);
4204                 if (dl)
4205                         continue;
4206
4207                 dl = xmalloc(sizeof(*dl));
4208                 dl->major = 0;
4209                 dl->minor = 0;
4210                 dl->fd = -1;
4211                 dl->devname = xstrdup("missing");
4212                 dl->index = i;
4213                 serialcpy(dl->serial, disk->serial);
4214                 dl->disk = *disk;
4215                 dl->e = NULL;
4216                 dl->next = super->missing;
4217                 super->missing = dl;
4218         }
4219
4220         return 0;
4221 }
4222
4223 #ifndef MDASSEMBLE
4224 static struct intel_disk *disk_list_get(__u8 *serial, struct intel_disk *disk_list)
4225 {
4226         struct intel_disk *idisk = disk_list;
4227
4228         while (idisk) {
4229                 if (serialcmp(idisk->disk.serial, serial) == 0)
4230                         break;
4231                 idisk = idisk->next;
4232         }
4233
4234         return idisk;
4235 }
4236
4237 static int __prep_thunderdome(struct intel_super **table, int tbl_size,
4238                               struct intel_super *super,
4239                               struct intel_disk **disk_list)
4240 {
4241         struct imsm_disk *d = &super->disks->disk;
4242         struct imsm_super *mpb = super->anchor;
4243         int i, j;
4244
4245         for (i = 0; i < tbl_size; i++) {
4246                 struct imsm_super *tbl_mpb = table[i]->anchor;
4247                 struct imsm_disk *tbl_d = &table[i]->disks->disk;
4248
4249                 if (tbl_mpb->family_num == mpb->family_num) {
4250                         if (tbl_mpb->check_sum == mpb->check_sum) {
4251                                 dprintf("mpb from %d:%d matches %d:%d\n",
4252                                         super->disks->major,
4253                                         super->disks->minor,
4254                                         table[i]->disks->major,
4255                                         table[i]->disks->minor);
4256                                 break;
4257                         }
4258
4259                         if (((is_configured(d) && !is_configured(tbl_d)) ||
4260                              is_configured(d) == is_configured(tbl_d)) &&
4261                             tbl_mpb->generation_num < mpb->generation_num) {
4262                                 /* current version of the mpb is a
4263                                  * better candidate than the one in
4264                                  * super_table, but copy over "cross
4265                                  * generational" status
4266                                  */
4267                                 struct intel_disk *idisk;
4268
4269                                 dprintf("mpb from %d:%d replaces %d:%d\n",
4270                                         super->disks->major,
4271                                         super->disks->minor,
4272                                         table[i]->disks->major,
4273                                         table[i]->disks->minor);
4274
4275                                 idisk = disk_list_get(tbl_d->serial, *disk_list);
4276                                 if (idisk && is_failed(&idisk->disk))
4277                                         tbl_d->status |= FAILED_DISK;
4278                                 break;
4279                         } else {
4280                                 struct intel_disk *idisk;
4281                                 struct imsm_disk *disk;
4282
4283                                 /* tbl_mpb is more up to date, but copy
4284                                  * over cross generational status before
4285                                  * returning
4286                                  */
4287                                 disk = __serial_to_disk(d->serial, mpb, NULL);
4288                                 if (disk && is_failed(disk))
4289                                         d->status |= FAILED_DISK;
4290
4291                                 idisk = disk_list_get(d->serial, *disk_list);
4292                                 if (idisk) {
4293                                         idisk->owner = i;
4294                                         if (disk && is_configured(disk))
4295                                                 idisk->disk.status |= CONFIGURED_DISK;
4296                                 }
4297
4298                                 dprintf("mpb from %d:%d prefer %d:%d\n",
4299                                         super->disks->major,
4300                                         super->disks->minor,
4301                                         table[i]->disks->major,
4302                                         table[i]->disks->minor);
4303
4304                                 return tbl_size;
4305                         }
4306                 }
4307         }
4308
4309         if (i >= tbl_size)
4310                 table[tbl_size++] = super;
4311         else
4312                 table[i] = super;
4313
4314         /* update/extend the merged list of imsm_disk records */
4315         for (j = 0; j < mpb->num_disks; j++) {
4316                 struct imsm_disk *disk = __get_imsm_disk(mpb, j);
4317                 struct intel_disk *idisk;
4318
4319                 idisk = disk_list_get(disk->serial, *disk_list);
4320                 if (idisk) {
4321                         idisk->disk.status |= disk->status;
4322                         if (is_configured(&idisk->disk) ||
4323                             is_failed(&idisk->disk))
4324                                 idisk->disk.status &= ~(SPARE_DISK);
4325                 } else {
4326                         idisk = xcalloc(1, sizeof(*idisk));
4327                         idisk->owner = IMSM_UNKNOWN_OWNER;
4328                         idisk->disk = *disk;
4329                         idisk->next = *disk_list;
4330                         *disk_list = idisk;
4331                 }
4332
4333                 if (serialcmp(idisk->disk.serial, d->serial) == 0)
4334                         idisk->owner = i;
4335         }
4336
4337         return tbl_size;
4338 }
4339
4340 static struct intel_super *
4341 validate_members(struct intel_super *super, struct intel_disk *disk_list,
4342                  const int owner)
4343 {
4344         struct imsm_super *mpb = super->anchor;
4345         int ok_count = 0;
4346         int i;
4347
4348         for (i = 0; i < mpb->num_disks; i++) {
4349                 struct imsm_disk *disk = __get_imsm_disk(mpb, i);
4350                 struct intel_disk *idisk;
4351
4352                 idisk = disk_list_get(disk->serial, disk_list);
4353                 if (idisk) {
4354                         if (idisk->owner == owner ||
4355                             idisk->owner == IMSM_UNKNOWN_OWNER)
4356                                 ok_count++;
4357                         else
4358                                 dprintf("'%.16s' owner %d != %d\n",
4359                                         disk->serial, idisk->owner,
4360                                         owner);
4361                 } else {
4362                         dprintf("unknown disk %x [%d]: %.16s\n",
4363                                 __le32_to_cpu(mpb->family_num), i,
4364                                 disk->serial);
4365                         break;
4366                 }
4367         }
4368
4369         if (ok_count == mpb->num_disks)
4370                 return super;
4371         return NULL;
4372 }
4373
4374 static void show_conflicts(__u32 family_num, struct intel_super *super_list)
4375 {
4376         struct intel_super *s;
4377
4378         for (s = super_list; s; s = s->next) {
4379                 if (family_num != s->anchor->family_num)
4380                         continue;
4381                 pr_err("Conflict, offlining family %#x on '%s'\n",
4382                         __le32_to_cpu(family_num), s->disks->devname);
4383         }
4384 }
4385
4386 static struct intel_super *
4387 imsm_thunderdome(struct intel_super **super_list, int len)
4388 {
4389         struct intel_super *super_table[len];
4390         struct intel_disk *disk_list = NULL;
4391         struct intel_super *champion, *spare;
4392         struct intel_super *s, **del;
4393         int tbl_size = 0;
4394         int conflict;
4395         int i;
4396
4397         memset(super_table, 0, sizeof(super_table));
4398         for (s = *super_list; s; s = s->next)
4399                 tbl_size = __prep_thunderdome(super_table, tbl_size, s, &disk_list);
4400
4401         for (i = 0; i < tbl_size; i++) {
4402                 struct imsm_disk *d;
4403                 struct intel_disk *idisk;
4404                 struct imsm_super *mpb = super_table[i]->anchor;
4405
4406                 s = super_table[i];
4407                 d = &s->disks->disk;
4408
4409                 /* 'd' must appear in merged disk list for its
4410                  * configuration to be valid
4411                  */
4412                 idisk = disk_list_get(d->serial, disk_list);
4413                 if (idisk && idisk->owner == i)
4414                         s = validate_members(s, disk_list, i);
4415                 else
4416                         s = NULL;
4417
4418                 if (!s)
4419                         dprintf("marking family: %#x from %d:%d offline\n",
4420                                 mpb->family_num,
4421                                 super_table[i]->disks->major,
4422                                 super_table[i]->disks->minor);
4423                 super_table[i] = s;
4424         }
4425
4426         /* This is where the mdadm implementation differs from the Windows
4427          * driver which has no strict concept of a container.  We can only
4428          * assemble one family from a container, so when returning a prodigal
4429          * array member to this system the code will not be able to disambiguate
4430          * the container contents that should be assembled ("foreign" versus
4431          * "local").  It requires user intervention to set the orig_family_num
4432          * to a new value to establish a new container.  The Windows driver in
4433          * this situation fixes up the volume name in place and manages the
4434          * foreign array as an independent entity.
4435          */
4436         s = NULL;
4437         spare = NULL;
4438         conflict = 0;
4439         for (i = 0; i < tbl_size; i++) {
4440                 struct intel_super *tbl_ent = super_table[i];
4441                 int is_spare = 0;
4442
4443                 if (!tbl_ent)
4444                         continue;
4445
4446                 if (tbl_ent->anchor->num_raid_devs == 0) {
4447                         spare = tbl_ent;
4448                         is_spare = 1;
4449                 }
4450
4451                 if (s && !is_spare) {
4452                         show_conflicts(tbl_ent->anchor->family_num, *super_list);
4453                         conflict++;
4454                 } else if (!s && !is_spare)
4455                         s = tbl_ent;
4456         }
4457
4458         if (!s)
4459                 s = spare;
4460         if (!s) {
4461                 champion = NULL;
4462                 goto out;
4463         }
4464         champion = s;
4465
4466         if (conflict)
4467                 pr_err("Chose family %#x on '%s', assemble conflicts to new container with '--update=uuid'\n",
4468                         __le32_to_cpu(s->anchor->family_num), s->disks->devname);
4469
4470         /* collect all dl's onto 'champion', and update them to
4471          * champion's version of the status
4472          */
4473         for (s = *super_list; s; s = s->next) {
4474                 struct imsm_super *mpb = champion->anchor;
4475                 struct dl *dl = s->disks;
4476
4477                 if (s == champion)
4478                         continue;
4479
4480                 mpb->attributes |= s->anchor->attributes & MPB_ATTRIB_2TB_DISK;
4481
4482                 for (i = 0; i < mpb->num_disks; i++) {
4483                         struct imsm_disk *disk;
4484
4485                         disk = __serial_to_disk(dl->serial, mpb, &dl->index);
4486                         if (disk) {
4487                                 dl->disk = *disk;
4488                                 /* only set index on disks that are a member of
4489                                  * a populated contianer, i.e. one with
4490                                  * raid_devs
4491                                  */
4492                                 if (is_failed(&dl->disk))
4493                                         dl->index = -2;
4494                                 else if (is_spare(&dl->disk))
4495                                         dl->index = -1;
4496                                 break;
4497                         }
4498                 }
4499
4500                 if (i >= mpb->num_disks) {
4501                         struct intel_disk *idisk;
4502
4503                         idisk = disk_list_get(dl->serial, disk_list);
4504                         if (idisk && is_spare(&idisk->disk) &&
4505                             !is_failed(&idisk->disk) && !is_configured(&idisk->disk))
4506                                 dl->index = -1;
4507                         else {
4508                                 dl->index = -2;
4509                                 continue;
4510                         }
4511                 }
4512
4513                 dl->next = champion->disks;
4514                 champion->disks = dl;
4515                 s->disks = NULL;
4516         }
4517
4518         /* delete 'champion' from super_list */
4519         for (del = super_list; *del; ) {
4520                 if (*del == champion) {
4521                         *del = (*del)->next;
4522                         break;
4523                 } else
4524                         del = &(*del)->next;
4525         }
4526         champion->next = NULL;
4527
4528  out:
4529         while (disk_list) {
4530                 struct intel_disk *idisk = disk_list;
4531
4532                 disk_list = disk_list->next;
4533                 free(idisk);
4534         }
4535
4536         return champion;
4537 }
4538
4539 static int
4540 get_sra_super_block(int fd, struct intel_super **super_list, char *devname, int *max, int keep_fd);
4541 static int get_super_block(struct intel_super **super_list, char *devnm, char *devname,
4542                            int major, int minor, int keep_fd);
4543 static int
4544 get_devlist_super_block(struct md_list *devlist, struct intel_super **super_list,
4545                         int *max, int keep_fd);
4546
4547 static int load_super_imsm_all(struct supertype *st, int fd, void **sbp,
4548                                char *devname, struct md_list *devlist,
4549                                int keep_fd)
4550 {
4551         struct intel_super *super_list = NULL;
4552         struct intel_super *super = NULL;
4553         int err = 0;
4554         int i = 0;
4555
4556         if (fd >= 0)
4557                 /* 'fd' is an opened container */
4558                 err = get_sra_super_block(fd, &super_list, devname, &i, keep_fd);
4559         else
4560                 /* get super block from devlist devices */
4561                 err = get_devlist_super_block(devlist, &super_list, &i, keep_fd);
4562         if (err)
4563                 goto error;
4564         /* all mpbs enter, maybe one leaves */
4565         super = imsm_thunderdome(&super_list, i);
4566         if (!super) {
4567                 err = 1;
4568                 goto error;
4569         }
4570
4571         if (find_missing(super) != 0) {
4572                 free_imsm(super);
4573                 err = 2;
4574                 goto error;
4575         }
4576
4577         /* load migration record */
4578         err = load_imsm_migr_rec(super, NULL);
4579         if (err == -1) {
4580                 /* migration is in progress,
4581                  * but migr_rec cannot be loaded,
4582                  */
4583                 err = 4;
4584                 goto error;
4585         }
4586
4587         /* Check migration compatibility */
4588         if (err == 0 && check_mpb_migr_compatibility(super) != 0) {
4589                 pr_err("Unsupported migration detected");
4590                 if (devname)
4591                         fprintf(stderr, " on %s\n", devname);
4592                 else
4593                         fprintf(stderr, " (IMSM).\n");
4594
4595                 err = 5;
4596                 goto error;
4597         }
4598
4599         err = 0;
4600
4601  error:
4602         while (super_list) {
4603                 struct intel_super *s = super_list;
4604
4605                 super_list = super_list->next;
4606                 free_imsm(s);
4607         }
4608
4609         if (err)
4610                 return err;
4611
4612         *sbp = super;
4613         if (fd >= 0)
4614                 strcpy(st->container_devnm, fd2devnm(fd));
4615         else
4616                 st->container_devnm[0] = 0;
4617         if (err == 0 && st->ss == NULL) {
4618                 st->ss = &super_imsm;
4619                 st->minor_version = 0;
4620                 st->max_devs = IMSM_MAX_DEVICES;
4621         }
4622         return 0;
4623 }
4624
4625 static int
4626 get_devlist_super_block(struct md_list *devlist, struct intel_super **super_list,
4627                         int *max, int keep_fd)
4628 {
4629         struct md_list *tmpdev;
4630         int err = 0;
4631         int i = 0;
4632
4633         for (i = 0, tmpdev = devlist; tmpdev; tmpdev = tmpdev->next) {
4634                 if (tmpdev->used != 1)
4635                         continue;
4636                 if (tmpdev->container == 1) {
4637                         int lmax = 0;
4638                         int fd = dev_open(tmpdev->devname, O_RDONLY|O_EXCL);
4639                         if (fd < 0) {
4640                                 pr_err("cannot open device %s: %s\n",
4641                                         tmpdev->devname, strerror(errno));
4642                                 err = 8;
4643                                 goto error;
4644                         }
4645                         err = get_sra_super_block(fd, super_list,
4646                                                   tmpdev->devname, &lmax,
4647                                                   keep_fd);
4648                         i += lmax;
4649                         close(fd);
4650                         if (err) {
4651                                 err = 7;
4652                                 goto error;
4653                         }
4654                 } else {
4655                         int major = major(tmpdev->st_rdev);
4656                         int minor = minor(tmpdev->st_rdev);
4657                         err = get_super_block(super_list,
4658                                               NULL,
4659                                               tmpdev->devname,
4660                                               major, minor,
4661                                               keep_fd);
4662                         i++;
4663                         if (err) {
4664                                 err = 6;
4665                                 goto error;
4666                         }
4667                 }
4668         }
4669  error:
4670         *max = i;
4671         return err;
4672 }
4673
4674 static int get_super_block(struct intel_super **super_list, char *devnm, char *devname,
4675                            int major, int minor, int keep_fd)
4676 {
4677         struct intel_super *s;
4678         char nm[32];
4679         int dfd = -1;
4680         int err = 0;
4681         int retry;
4682
4683         s = alloc_super();
4684         if (!s) {
4685                 err = 1;
4686                 goto error;
4687         }
4688
4689         sprintf(nm, "%d:%d", major, minor);
4690         dfd = dev_open(nm, O_RDWR);
4691         if (dfd < 0) {
4692                 err = 2;
4693                 goto error;
4694         }
4695
4696         get_dev_sector_size(dfd, NULL, &s->sector_size);
4697         find_intel_hba_capability(dfd, s, devname);
4698         err = load_and_parse_mpb(dfd, s, NULL, keep_fd);
4699
4700         /* retry the load if we might have raced against mdmon */
4701         if (err == 3 && devnm && mdmon_running(devnm))
4702                 for (retry = 0; retry < 3; retry++) {
4703                         usleep(3000);
4704                         err = load_and_parse_mpb(dfd, s, NULL, keep_fd);
4705                         if (err != 3)
4706                                 break;
4707                 }
4708  error:
4709         if (!err) {
4710                 s->next = *super_list;
4711                 *super_list = s;
4712         } else {
4713                 if (s)
4714                         free_imsm(s);
4715                 if (dfd >= 0)
4716                         close(dfd);
4717         }
4718         if (dfd >= 0 && !keep_fd)
4719                 close(dfd);
4720         return err;
4721
4722 }
4723
4724 static int
4725 get_sra_super_block(int fd, struct intel_super **super_list, char *devname, int *max, int keep_fd)
4726 {
4727         struct mdinfo *sra;
4728         char *devnm;
4729         struct mdinfo *sd;
4730         int err = 0;
4731         int i = 0;
4732         sra = sysfs_read(fd, NULL, GET_LEVEL|GET_VERSION|GET_DEVS|GET_STATE);
4733         if (!sra)
4734                 return 1;
4735
4736         if (sra->array.major_version != -1 ||
4737             sra->array.minor_version != -2 ||
4738             strcmp(sra->text_version, "imsm") != 0) {
4739                 err = 1;
4740                 goto error;
4741         }
4742         /* load all mpbs */
4743         devnm = fd2devnm(fd);
4744         for (sd = sra->devs, i = 0; sd; sd = sd->next, i++) {
4745                 if (get_super_block(super_list, devnm, devname,
4746                                     sd->disk.major, sd->disk.minor, keep_fd) != 0) {
4747                         err = 7;
4748                         goto error;
4749                 }
4750         }
4751  error:
4752         sysfs_free(sra);
4753         *max = i;
4754         return err;
4755 }
4756
4757 static int load_container_imsm(struct supertype *st, int fd, char *devname)
4758 {
4759         return load_super_imsm_all(st, fd, &st->sb, devname, NULL, 1);
4760 }
4761 #endif
4762
4763 static int load_super_imsm(struct supertype *st, int fd, char *devname)
4764 {
4765         struct intel_super *super;
4766         int rv;
4767         int retry;
4768
4769         if (test_partition(fd))
4770                 /* IMSM not allowed on partitions */
4771                 return 1;
4772
4773         free_super_imsm(st);
4774
4775         super = alloc_super();
4776         get_dev_sector_size(fd, NULL, &super->sector_size);
4777         if (!super)
4778                 return 1;
4779         /* Load hba and capabilities if they exist.
4780          * But do not preclude loading metadata in case capabilities or hba are
4781          * non-compliant and ignore_hw_compat is set.
4782          */
4783         rv = find_intel_hba_capability(fd, super, devname);
4784         /* no orom/efi or non-intel hba of the disk */
4785         if (rv != 0 && st->ignore_hw_compat == 0) {
4786                 if (devname)
4787                         pr_err("No OROM/EFI properties for %s\n", devname);
4788                 free_imsm(super);
4789                 return 2;
4790         }
4791         rv = load_and_parse_mpb(fd, super, devname, 0);
4792
4793         /* retry the load if we might have raced against mdmon */
4794         if (rv == 3) {
4795                 struct mdstat_ent *mdstat = NULL;
4796                 char *name = fd2kname(fd);
4797
4798                 if (name)
4799                         mdstat = mdstat_by_component(name);
4800
4801                 if (mdstat && mdmon_running(mdstat->devnm) && getpid() != mdmon_pid(mdstat->devnm)) {
4802                         for (retry = 0; retry < 3; retry++) {
4803                                 usleep(3000);
4804                                 rv = load_and_parse_mpb(fd, super, devname, 0);
4805                                 if (rv != 3)
4806                                         break;
4807                         }
4808                 }
4809
4810                 free_mdstat(mdstat);
4811         }
4812
4813         if (rv) {
4814                 if (devname)
4815                         pr_err("Failed to load all information sections on %s\n", devname);
4816                 free_imsm(super);
4817                 return rv;
4818         }
4819
4820         st->sb = super;
4821         if (st->ss == NULL) {
4822                 st->ss = &super_imsm;
4823                 st->minor_version = 0;
4824                 st->max_devs = IMSM_MAX_DEVICES;
4825         }
4826
4827         /* load migration record */
4828         if (load_imsm_migr_rec(super, NULL) == 0) {
4829                 /* Check for unsupported migration features */
4830                 if (check_mpb_migr_compatibility(super) != 0) {
4831                         pr_err("Unsupported migration detected");
4832                         if (devname)
4833                                 fprintf(stderr, " on %s\n", devname);
4834                         else
4835                                 fprintf(stderr, " (IMSM).\n");
4836                         return 3;
4837                 }
4838         }
4839
4840         return 0;
4841 }
4842
4843 static __u16 info_to_blocks_per_strip(mdu_array_info_t *info)
4844 {
4845         if (info->level == 1)
4846                 return 128;
4847         return info->chunk_size >> 9;
4848 }
4849
4850 static unsigned long long info_to_blocks_per_member(mdu_array_info_t *info,
4851                                                     unsigned long long size)
4852 {
4853         if (info->level == 1)
4854                 return size * 2;
4855         else
4856                 return (size * 2) & ~(info_to_blocks_per_strip(info) - 1);
4857 }
4858
4859 static void imsm_update_version_info(struct intel_super *super)
4860 {
4861         /* update the version and attributes */
4862         struct imsm_super *mpb = super->anchor;
4863         char *version;
4864         struct imsm_dev *dev;
4865         struct imsm_map *map;
4866         int i;
4867
4868         for (i = 0; i < mpb->num_raid_devs; i++) {
4869                 dev = get_imsm_dev(super, i);
4870                 map = get_imsm_map(dev, MAP_0);
4871                 if (__le32_to_cpu(dev->size_high) > 0)
4872                         mpb->attributes |= MPB_ATTRIB_2TB;
4873
4874                 /* FIXME detect when an array spans a port multiplier */
4875                 #if 0
4876                 mpb->attributes |= MPB_ATTRIB_PM;
4877                 #endif
4878
4879                 if (mpb->num_raid_devs > 1 ||
4880                     mpb->attributes != MPB_ATTRIB_CHECKSUM_VERIFY) {
4881                         version = MPB_VERSION_ATTRIBS;
4882                         switch (get_imsm_raid_level(map)) {
4883                         case 0: mpb->attributes |= MPB_ATTRIB_RAID0; break;
4884                         case 1: mpb->attributes |= MPB_ATTRIB_RAID1; break;
4885                         case 10: mpb->attributes |= MPB_ATTRIB_RAID10; break;
4886                         case 5: mpb->attributes |= MPB_ATTRIB_RAID5; break;
4887                         }
4888                 } else {
4889                         if (map->num_members >= 5)
4890                                 version = MPB_VERSION_5OR6_DISK_ARRAY;
4891                         else if (dev->status == DEV_CLONE_N_GO)
4892                                 version = MPB_VERSION_CNG;
4893                         else if (get_imsm_raid_level(map) == 5)
4894                                 version = MPB_VERSION_RAID5;
4895                         else if (map->num_members >= 3)
4896                                 version = MPB_VERSION_3OR4_DISK_ARRAY;
4897                         else if (get_imsm_raid_level(map) == 1)
4898                                 version = MPB_VERSION_RAID1;
4899                         else
4900                                 version = MPB_VERSION_RAID0;
4901                 }
4902                 strcpy(((char *) mpb->sig) + strlen(MPB_SIGNATURE), version);
4903         }
4904 }
4905
4906 static int check_name(struct intel_super *super, char *name, int quiet)
4907 {
4908         struct imsm_super *mpb = super->anchor;
4909         char *reason = NULL;
4910         int i;
4911
4912         if (strlen(name) > MAX_RAID_SERIAL_LEN)
4913                 reason = "must be 16 characters or less";
4914
4915         for (i = 0; i < mpb->num_raid_devs; i++) {
4916                 struct imsm_dev *dev = get_imsm_dev(super, i);
4917
4918                 if (strncmp((char *) dev->volume, name, MAX_RAID_SERIAL_LEN) == 0) {
4919                         reason = "already exists";
4920                         break;
4921                 }
4922         }
4923
4924         if (reason && !quiet)
4925                 pr_err("imsm volume name %s\n", reason);
4926
4927         return !reason;
4928 }
4929
4930 static int init_super_imsm_volume(struct supertype *st, mdu_array_info_t *info,
4931                                   unsigned long long size, char *name,
4932                                   char *homehost, int *uuid,
4933                                   long long data_offset)
4934 {
4935         /* We are creating a volume inside a pre-existing container.
4936          * so st->sb is already set.
4937          */
4938         struct intel_super *super = st->sb;
4939         unsigned int sector_size = super->sector_size;
4940         struct imsm_super *mpb = super->anchor;
4941         struct intel_dev *dv;
4942         struct imsm_dev *dev;
4943         struct imsm_vol *vol;
4944         struct imsm_map *map;
4945         int idx = mpb->num_raid_devs;
4946         int i;
4947         unsigned long long array_blocks;
4948         size_t size_old, size_new;
4949         unsigned long long num_data_stripes;
4950
4951         if (super->orom && mpb->num_raid_devs >= super->orom->vpa) {
4952                 pr_err("This imsm-container already has the maximum of %d volumes\n", super->orom->vpa);
4953                 return 0;
4954         }
4955
4956         /* ensure the mpb is large enough for the new data */
4957         size_old = __le32_to_cpu(mpb->mpb_size);
4958         size_new = disks_to_mpb_size(info->nr_disks);
4959         if (size_new > size_old) {
4960                 void *mpb_new;
4961                 size_t size_round = ROUND_UP(size_new, sector_size);
4962
4963                 if (posix_memalign(&mpb_new, sector_size, size_round) != 0) {
4964                         pr_err("could not allocate new mpb\n");
4965                         return 0;
4966                 }
4967                 if (posix_memalign(&super->migr_rec_buf, sector_size,
4968                                    MIGR_REC_BUF_SECTORS*sector_size) != 0) {
4969                         pr_err("could not allocate migr_rec buffer\n");
4970                         free(super->buf);
4971                         free(super);
4972                         free(mpb_new);
4973                         return 0;
4974                 }
4975                 memcpy(mpb_new, mpb, size_old);
4976                 free(mpb);
4977                 mpb = mpb_new;
4978                 super->anchor = mpb_new;
4979                 mpb->mpb_size = __cpu_to_le32(size_new);
4980                 memset(mpb_new + size_old, 0, size_round - size_old);
4981                 super->len = size_round;
4982         }
4983         super->current_vol = idx;
4984
4985         /* handle 'failed_disks' by either:
4986          * a) create dummy disk entries in the table if this the first
4987          *    volume in the array.  We add them here as this is the only
4988          *    opportunity to add them. add_to_super_imsm_volume()
4989          *    handles the non-failed disks and continues incrementing
4990          *    mpb->num_disks.
4991          * b) validate that 'failed_disks' matches the current number
4992          *    of missing disks if the container is populated
4993          */
4994         if (super->current_vol == 0) {
4995                 mpb->num_disks = 0;
4996                 for (i = 0; i < info->failed_disks; i++) {
4997                         struct imsm_disk *disk;
4998
4999                         mpb->num_disks++;
5000                         disk = __get_imsm_disk(mpb, i);
5001                         disk->status = CONFIGURED_DISK | FAILED_DISK;
5002                         disk->scsi_id = __cpu_to_le32(~(__u32)0);
5003                         snprintf((char *) disk->serial, MAX_RAID_SERIAL_LEN,
5004                                  "missing:%d", i);
5005                 }
5006                 find_missing(super);
5007         } else {
5008                 int missing = 0;
5009                 struct dl *d;
5010
5011                 for (d = super->missing; d; d = d->next)
5012                         missing++;
5013                 if (info->failed_disks > missing) {
5014                         pr_err("unable to add 'missing' disk to container\n");
5015                         return 0;
5016                 }
5017         }
5018
5019         if (!check_name(super, name, 0))
5020                 return 0;
5021         dv = xmalloc(sizeof(*dv));
5022         dev = xcalloc(1, sizeof(*dev) + sizeof(__u32) * (info->raid_disks - 1));
5023         strncpy((char *) dev->volume, name, MAX_RAID_SERIAL_LEN);
5024         array_blocks = calc_array_size(info->level, info->raid_disks,
5025                                                info->layout, info->chunk_size,
5026                                                size * 2);
5027         /* round array size down to closest MB */
5028         array_blocks = (array_blocks >> SECT_PER_MB_SHIFT) << SECT_PER_MB_SHIFT;
5029
5030         dev->size_low = __cpu_to_le32((__u32) array_blocks);
5031         dev->size_high = __cpu_to_le32((__u32) (array_blocks >> 32));
5032         dev->status = (DEV_READ_COALESCING | DEV_WRITE_COALESCING);
5033         vol = &dev->vol;
5034         vol->migr_state = 0;
5035         set_migr_type(dev, MIGR_INIT);
5036         vol->dirty = !info->state;
5037         vol->curr_migr_unit = 0;
5038         map = get_imsm_map(dev, MAP_0);
5039         set_pba_of_lba0(map, super->create_offset);
5040         set_blocks_per_member(map, info_to_blocks_per_member(info, size));
5041         map->blocks_per_strip = __cpu_to_le16(info_to_blocks_per_strip(info));
5042         map->failed_disk_num = ~0;
5043         if (info->level > 0)
5044                 map->map_state = (info->state ? IMSM_T_STATE_NORMAL
5045                                   : IMSM_T_STATE_UNINITIALIZED);
5046         else
5047                 map->map_state = info->failed_disks ? IMSM_T_STATE_FAILED :
5048                                                       IMSM_T_STATE_NORMAL;
5049         map->ddf = 1;
5050
5051         if (info->level == 1 && info->raid_disks > 2) {
5052                 free(dev);
5053                 free(dv);
5054                 pr_err("imsm does not support more than 2 disksin a raid1 volume\n");
5055                 return 0;
5056         }
5057
5058         map->raid_level = info->level;
5059         if (info->level == 10) {
5060                 map->raid_level = 1;
5061                 map->num_domains = info->raid_disks / 2;
5062         } else if (info->level == 1)
5063                 map->num_domains = info->raid_disks;
5064         else
5065                 map->num_domains = 1;
5066
5067         /* info->size is only int so use the 'size' parameter instead */
5068         num_data_stripes = (size * 2) / info_to_blocks_per_strip(info);
5069         num_data_stripes /= map->num_domains;
5070         set_num_data_stripes(map, num_data_stripes);
5071
5072         map->num_members = info->raid_disks;
5073         for (i = 0; i < map->num_members; i++) {
5074                 /* initialized in add_to_super */
5075                 set_imsm_ord_tbl_ent(map, i, IMSM_ORD_REBUILD);
5076         }
5077         mpb->num_raid_devs++;
5078
5079         dv->dev = dev;
5080         dv->index = super->current_vol;
5081         dv->next = super->devlist;
5082         super->devlist = dv;
5083
5084         imsm_update_version_info(super);
5085
5086         return 1;
5087 }
5088
5089 static int init_super_imsm(struct supertype *st, mdu_array_info_t *info,
5090                            unsigned long long size, char *name,
5091                            char *homehost, int *uuid,
5092                            unsigned long long data_offset)
5093 {
5094         /* This is primarily called by Create when creating a new array.
5095          * We will then get add_to_super called for each component, and then
5096          * write_init_super called to write it out to each device.
5097          * For IMSM, Create can create on fresh devices or on a pre-existing
5098          * array.
5099          * To create on a pre-existing array a different method will be called.
5100          * This one is just for fresh drives.
5101          */
5102         struct intel_super *super;
5103         struct imsm_super *mpb;
5104         size_t mpb_size;
5105         char *version;
5106
5107         if (data_offset != INVALID_SECTORS) {
5108                 pr_err("data-offset not supported by imsm\n");
5109                 return 0;
5110         }
5111
5112         if (st->sb)
5113                 return init_super_imsm_volume(st, info, size, name, homehost, uuid,
5114                                               data_offset);
5115
5116         if (info)
5117                 mpb_size = disks_to_mpb_size(info->nr_disks);
5118         else
5119                 mpb_size = MAX_SECTOR_SIZE;
5120
5121         super = alloc_super();
5122         if (super &&
5123             posix_memalign(&super->buf, MAX_SECTOR_SIZE, mpb_size) != 0) {
5124                 free_imsm(super);
5125                 super = NULL;
5126         }
5127         if (!super) {
5128                 pr_err("could not allocate superblock\n");
5129                 return 0;
5130         }
5131         if (posix_memalign(&super->migr_rec_buf, MAX_SECTOR_SIZE,
5132             MIGR_REC_BUF_SECTORS*MAX_SECTOR_SIZE) != 0) {
5133                 pr_err("could not allocate migr_rec buffer\n");
5134                 free(super->buf);
5135                 free_imsm(super);
5136                 return 0;
5137         }
5138         memset(super->buf, 0, mpb_size);
5139         mpb = super->buf;
5140         mpb->mpb_size = __cpu_to_le32(mpb_size);
5141         st->sb = super;
5142
5143         if (info == NULL) {
5144                 /* zeroing superblock */
5145                 return 0;
5146         }
5147
5148         mpb->attributes = MPB_ATTRIB_CHECKSUM_VERIFY;
5149
5150         version = (char *) mpb->sig;
5151         strcpy(version, MPB_SIGNATURE);
5152         version += strlen(MPB_SIGNATURE);
5153         strcpy(version, MPB_VERSION_RAID0);
5154
5155         return 1;
5156 }
5157
5158 #ifndef MDASSEMBLE
5159 static int add_to_super_imsm_volume(struct supertype *st, mdu_disk_info_t *dk,
5160                                      int fd, char *devname)
5161 {
5162         struct intel_super *super = st->sb;
5163         struct imsm_super *mpb = super->anchor;
5164         struct imsm_disk *_disk;
5165         struct imsm_dev *dev;
5166         struct imsm_map *map;
5167         struct dl *dl, *df;
5168         int slot;
5169
5170         dev = get_imsm_dev(super, super->current_vol);
5171         map = get_imsm_map(dev, MAP_0);
5172
5173         if (! (dk->state & (1<<MD_DISK_SYNC))) {
5174                 pr_err("%s: Cannot add spare devices to IMSM volume\n",
5175                         devname);
5176                 return 1;
5177         }
5178
5179         if (fd == -1) {
5180                 /* we're doing autolayout so grab the pre-marked (in
5181                  * validate_geometry) raid_disk
5182                  */
5183                 for (dl = super->disks; dl; dl = dl->next)
5184                         if (dl->raiddisk == dk->raid_disk)
5185                                 break;
5186         } else {
5187                 for (dl = super->disks; dl ; dl = dl->next)
5188                         if (dl->major == dk->major &&
5189                             dl->minor == dk->minor)
5190                                 break;
5191         }
5192
5193         if (!dl) {
5194                 pr_err("%s is not a member of the same container\n", devname);
5195                 return 1;
5196         }
5197
5198         /* add a pristine spare to the metadata */
5199         if (dl->index < 0) {
5200                 dl->index = super->anchor->num_disks;
5201                 super->anchor->num_disks++;
5202         }
5203         /* Check the device has not already been added */
5204         slot = get_imsm_disk_slot(map, dl->index);
5205         if (slot >= 0 &&
5206             (get_imsm_ord_tbl_ent(dev, slot, MAP_X) & IMSM_ORD_REBUILD) == 0) {
5207                 pr_err("%s has been included in this array twice\n",
5208                         devname);
5209                 return 1;
5210         }
5211         set_imsm_ord_tbl_ent(map, dk->raid_disk, dl->index);
5212         dl->disk.status = CONFIGURED_DISK;
5213
5214         /* update size of 'missing' disks to be at least as large as the
5215          * largest acitve member (we only have dummy missing disks when
5216          * creating the first volume)
5217          */
5218         if (super->current_vol == 0) {
5219                 for (df = super->missing; df; df = df->next) {
5220                         if (total_blocks(&dl->disk) > total_blocks(&df->disk))
5221                                 set_total_blocks(&df->disk, total_blocks(&dl->disk));
5222                         _disk = __get_imsm_disk(mpb, df->index);
5223                         *_disk = df->disk;
5224                 }
5225         }
5226
5227         /* refresh unset/failed slots to point to valid 'missing' entries */
5228         for (df = super->missing; df; df = df->next)
5229                 for (slot = 0; slot < mpb->num_disks; slot++) {
5230                         __u32 ord = get_imsm_ord_tbl_ent(dev, slot, MAP_X);
5231
5232                         if ((ord & IMSM_ORD_REBUILD) == 0)
5233                                 continue;
5234                         set_imsm_ord_tbl_ent(map, slot, df->index | IMSM_ORD_REBUILD);
5235                         if (is_gen_migration(dev)) {
5236                                 struct imsm_map *map2 = get_imsm_map(dev,
5237                                                                      MAP_1);
5238                                 int slot2 = get_imsm_disk_slot(map2, df->index);
5239                                 if (slot2 < map2->num_members && slot2 >= 0) {
5240                                         __u32 ord2 = get_imsm_ord_tbl_ent(dev,
5241                                                                          slot2,
5242                                                                          MAP_1);
5243                                         if ((unsigned)df->index ==
5244                                                                ord_to_idx(ord2))
5245                                                 set_imsm_ord_tbl_ent(map2,
5246                                                         slot2,
5247                                                         df->index |
5248                                                         IMSM_ORD_REBUILD);
5249                                 }
5250                         }
5251                         dprintf("set slot:%d to missing disk:%d\n", slot, df->index);
5252                         break;
5253                 }
5254
5255         /* if we are creating the first raid device update the family number */
5256         if (super->current_vol == 0) {
5257                 __u32 sum;
5258                 struct imsm_dev *_dev = __get_imsm_dev(mpb, 0);
5259
5260                 _disk = __get_imsm_disk(mpb, dl->index);
5261                 if (!_dev || !_disk) {
5262                         pr_err("BUG mpb setup error\n");
5263                         return 1;
5264                 }
5265                 *_dev = *dev;
5266                 *_disk = dl->disk;
5267                 sum = random32();
5268                 sum += __gen_imsm_checksum(mpb);
5269                 mpb->family_num = __cpu_to_le32(sum);
5270                 mpb->orig_family_num = mpb->family_num;
5271         }
5272         super->current_disk = dl;
5273         return 0;
5274 }
5275
5276 /* mark_spare()
5277  *   Function marks disk as spare and restores disk serial
5278  *   in case it was previously marked as failed by takeover operation
5279  * reruns:
5280  *   -1 : critical error
5281  *    0 : disk is marked as spare but serial is not set
5282  *    1 : success
5283  */
5284 int mark_spare(struct dl *disk)
5285 {
5286         __u8 serial[MAX_RAID_SERIAL_LEN];
5287         int ret_val = -1;
5288
5289         if (!disk)
5290                 return ret_val;
5291
5292         ret_val = 0;
5293         if (!imsm_read_serial(disk->fd, NULL, serial)) {
5294                 /* Restore disk serial number, because takeover marks disk
5295                  * as failed and adds to serial ':0' before it becomes
5296                  * a spare disk.
5297                  */
5298                 serialcpy(disk->serial, serial);
5299                 serialcpy(disk->disk.serial, serial);
5300                 ret_val = 1;
5301         }
5302         disk->disk.status = SPARE_DISK;
5303         disk->index = -1;
5304
5305         return ret_val;
5306 }
5307
5308 static int add_to_super_imsm(struct supertype *st, mdu_disk_info_t *dk,
5309                              int fd, char *devname,
5310                              unsigned long long data_offset)
5311 {
5312         struct intel_super *super = st->sb;
5313         struct dl *dd;
5314         unsigned long long size;
5315         unsigned int member_sector_size;
5316         __u32 id;
5317         int rv;
5318         struct stat stb;
5319
5320         /* If we are on an RAID enabled platform check that the disk is
5321          * attached to the raid controller.
5322          * We do not need to test disks attachment for container based additions,
5323          * they shall be already tested when container was created/assembled.
5324          */
5325         rv = find_intel_hba_capability(fd, super, devname);
5326         /* no orom/efi or non-intel hba of the disk */
5327         if (rv != 0) {
5328                 dprintf("capability: %p fd: %d ret: %d\n",
5329                         super->orom, fd, rv);
5330                 return 1;
5331         }
5332
5333         if (super->current_vol >= 0)
5334                 return add_to_super_imsm_volume(st, dk, fd, devname);
5335
5336         fstat(fd, &stb);
5337         dd = xcalloc(sizeof(*dd), 1);
5338         dd->major = major(stb.st_rdev);
5339         dd->minor = minor(stb.st_rdev);
5340         dd->devname = devname ? xstrdup(devname) : NULL;
5341         dd->fd = fd;
5342         dd->e = NULL;
5343         dd->action = DISK_ADD;
5344         rv = imsm_read_serial(fd, devname, dd->serial);
5345         if (rv) {
5346                 pr_err("failed to retrieve scsi serial, aborting\n");
5347                 if (dd->devname)
5348                         free(dd->devname);
5349                 free(dd);
5350                 abort();
5351         }
5352         if (super->hba && ((super->hba->type == SYS_DEV_NVME) ||
5353            (super->hba->type == SYS_DEV_VMD))) {
5354                 int i;
5355                 char *devpath = diskfd_to_devpath(fd);
5356                 char controller_path[PATH_MAX];
5357
5358                 if (!devpath) {
5359                         pr_err("failed to get devpath, aborting\n");
5360                         if (dd->devname)
5361                                 free(dd->devname);
5362                         free(dd);
5363                         return 1;
5364                 }
5365
5366                 snprintf(controller_path, PATH_MAX-1, "%s/device", devpath);
5367                 free(devpath);
5368
5369                 if (devpath_to_vendor(controller_path) == 0x8086) {
5370                         /*
5371                          * If Intel's NVMe drive has serial ended with
5372                          * "-A","-B","-1" or "-2" it means that this is "x8"
5373                          * device (double drive on single PCIe card).
5374                          * User should be warned about potential data loss.
5375                          */
5376                         for (i = MAX_RAID_SERIAL_LEN-1; i > 0; i--) {
5377                                 /* Skip empty character at the end */
5378                                 if (dd->serial[i] == 0)
5379                                         continue;
5380
5381                                 if (((dd->serial[i] == 'A') ||
5382                                    (dd->serial[i] == 'B') ||
5383                                    (dd->serial[i] == '1') ||
5384                                    (dd->serial[i] == '2')) &&
5385                                    (dd->serial[i-1] == '-'))
5386                                         pr_err("\tThe action you are about to take may put your data at risk.\n"
5387                                                 "\tPlease note that x8 devices may consist of two separate x4 devices "
5388                                                 "located on a single PCIe port.\n"
5389                                                 "\tRAID 0 is the only supported configuration for this type of x8 device.\n");
5390                                 break;
5391                         }
5392                 }
5393         }
5394
5395         get_dev_size(fd, NULL, &size);
5396         get_dev_sector_size(fd, NULL, &member_sector_size);
5397
5398         if (super->sector_size == 0) {
5399                 /* this a first device, so sector_size is not set yet */
5400                 super->sector_size = member_sector_size;
5401         } else if (member_sector_size != super->sector_size) {
5402                 pr_err("Mixing between different sector size is forbidden, aborting...\n");
5403                 if (dd->devname)
5404                         free(dd->devname);
5405                 free(dd);
5406                 return 1;
5407         }
5408
5409         /* clear migr_rec when adding disk to container */
5410         memset(super->migr_rec_buf, 0, MIGR_REC_BUF_SECTORS*super->sector_size);
5411         if (lseek64(fd, size - MIGR_REC_SECTOR_POSITION*super->sector_size,
5412             SEEK_SET) >= 0) {
5413                 if (write(fd, super->migr_rec_buf,
5414                     MIGR_REC_BUF_SECTORS*super->sector_size) !=
5415                     MIGR_REC_BUF_SECTORS*super->sector_size)
5416                         perror("Write migr_rec failed");
5417         }
5418
5419         size /= 512;
5420         serialcpy(dd->disk.serial, dd->serial);
5421         set_total_blocks(&dd->disk, size);
5422         if (__le32_to_cpu(dd->disk.total_blocks_hi) > 0) {
5423                 struct imsm_super *mpb = super->anchor;
5424                 mpb->attributes |= MPB_ATTRIB_2TB_DISK;
5425         }
5426         mark_spare(dd);
5427         if (sysfs_disk_to_scsi_id(fd, &id) == 0)
5428                 dd->disk.scsi_id = __cpu_to_le32(id);
5429         else
5430                 dd->disk.scsi_id = __cpu_to_le32(0);
5431
5432         if (st->update_tail) {
5433                 dd->next = super->disk_mgmt_list;
5434                 super->disk_mgmt_list = dd;
5435         } else {
5436                 dd->next = super->disks;
5437                 super->disks = dd;
5438                 super->updates_pending++;
5439         }
5440
5441         return 0;
5442 }
5443
5444 static int remove_from_super_imsm(struct supertype *st, mdu_disk_info_t *dk)
5445 {
5446         struct intel_super *super = st->sb;
5447         struct dl *dd;
5448
5449         /* remove from super works only in mdmon - for communication
5450          * manager - monitor. Check if communication memory buffer
5451          * is prepared.
5452          */
5453         if (!st->update_tail) {
5454                 pr_err("shall be used in mdmon context only\n");
5455                 return 1;
5456         }
5457         dd = xcalloc(1, sizeof(*dd));
5458         dd->major = dk->major;
5459         dd->minor = dk->minor;
5460         dd->fd = -1;
5461         mark_spare(dd);
5462         dd->action = DISK_REMOVE;
5463
5464         dd->next = super->disk_mgmt_list;
5465         super->disk_mgmt_list = dd;
5466
5467         return 0;
5468 }
5469
5470 static int store_imsm_mpb(int fd, struct imsm_super *mpb);
5471
5472 static union {
5473         char buf[MAX_SECTOR_SIZE];
5474         struct imsm_super anchor;
5475 } spare_record __attribute__ ((aligned(MAX_SECTOR_SIZE)));
5476
5477 /* spare records have their own family number and do not have any defined raid
5478  * devices
5479  */
5480 static int write_super_imsm_spares(struct intel_super *super, int doclose)
5481 {
5482         struct imsm_super *mpb = super->anchor;
5483         struct imsm_super *spare = &spare_record.anchor;
5484         __u32 sum;
5485         struct dl *d;
5486
5487         spare->mpb_size = __cpu_to_le32(sizeof(struct imsm_super));
5488         spare->generation_num = __cpu_to_le32(1UL);
5489         spare->attributes = MPB_ATTRIB_CHECKSUM_VERIFY;
5490         spare->num_disks = 1;
5491         spare->num_raid_devs = 0;
5492         spare->cache_size = mpb->cache_size;
5493         spare->pwr_cycle_count = __cpu_to_le32(1);
5494
5495         snprintf((char *) spare->sig, MAX_SIGNATURE_LENGTH,
5496                  MPB_SIGNATURE MPB_VERSION_RAID0);
5497
5498         for (d = super->disks; d; d = d->next) {
5499                 if (d->index != -1)
5500                         continue;
5501
5502                 spare->disk[0] = d->disk;
5503                 if (__le32_to_cpu(d->disk.total_blocks_hi) > 0)
5504                         spare->attributes |= MPB_ATTRIB_2TB_DISK;
5505
5506                 if (super->sector_size == 4096)
5507                         convert_to_4k_imsm_disk(&spare->disk[0]);
5508
5509                 sum = __gen_imsm_checksum(spare);
5510                 spare->family_num = __cpu_to_le32(sum);
5511                 spare->orig_family_num = 0;
5512                 sum = __gen_imsm_checksum(spare);
5513                 spare->check_sum = __cpu_to_le32(sum);
5514
5515                 if (store_imsm_mpb(d->fd, spare)) {
5516                         pr_err("failed for device %d:%d %s\n",
5517                                 d->major, d->minor, strerror(errno));
5518                         return 1;
5519                 }
5520                 if (doclose) {
5521                         close(d->fd);
5522                         d->fd = -1;
5523                 }
5524         }
5525
5526         return 0;
5527 }
5528
5529 static int write_super_imsm(struct supertype *st, int doclose)
5530 {
5531         struct intel_super *super = st->sb;
5532         unsigned int sector_size = super->sector_size;
5533         struct imsm_super *mpb = super->anchor;
5534         struct dl *d;
5535         __u32 generation;
5536         __u32 sum;
5537         int spares = 0;
5538         int i;
5539         __u32 mpb_size = sizeof(struct imsm_super) - sizeof(struct imsm_disk);
5540         int num_disks = 0;
5541         int clear_migration_record = 1;
5542         __u32 bbm_log_size;
5543
5544         /* 'generation' is incremented everytime the metadata is written */
5545         generation = __le32_to_cpu(mpb->generation_num);
5546         generation++;
5547         mpb->generation_num = __cpu_to_le32(generation);
5548
5549         /* fix up cases where previous mdadm releases failed to set
5550          * orig_family_num
5551          */
5552         if (mpb->orig_family_num == 0)
5553                 mpb->orig_family_num = mpb->family_num;
5554
5555         for (d = super->disks; d; d = d->next) {
5556                 if (d->index == -1)
5557                         spares++;
5558                 else {
5559                         mpb->disk[d->index] = d->disk;
5560                         num_disks++;
5561                 }
5562         }
5563         for (d = super->missing; d; d = d->next) {
5564                 mpb->disk[d->index] = d->disk;
5565                 num_disks++;
5566         }
5567         mpb->num_disks = num_disks;
5568         mpb_size += sizeof(struct imsm_disk) * mpb->num_disks;
5569
5570         for (i = 0; i < mpb->num_raid_devs; i++) {
5571                 struct imsm_dev *dev = __get_imsm_dev(mpb, i);
5572                 struct imsm_dev *dev2 = get_imsm_dev(super, i);
5573                 if (dev && dev2) {
5574                         imsm_copy_dev(dev, dev2);
5575                         mpb_size += sizeof_imsm_dev(dev, 0);
5576                 }
5577                 if (is_gen_migration(dev2))
5578                         clear_migration_record = 0;
5579         }
5580
5581         bbm_log_size = get_imsm_bbm_log_size(super->bbm_log);
5582
5583         if (bbm_log_size) {
5584                 memcpy((void *)mpb + mpb_size, super->bbm_log, bbm_log_size);
5585                 mpb->attributes |= MPB_ATTRIB_BBM;
5586         } else
5587                 mpb->attributes &= ~MPB_ATTRIB_BBM;
5588
5589         super->anchor->bbm_log_size = __cpu_to_le32(bbm_log_size);
5590         mpb_size += bbm_log_size;
5591         mpb->mpb_size = __cpu_to_le32(mpb_size);
5592
5593 #ifdef DEBUG
5594         assert(super->len == 0 || mpb_size <= super->len);
5595 #endif
5596
5597         /* recalculate checksum */
5598         sum = __gen_imsm_checksum(mpb);
5599         mpb->check_sum = __cpu_to_le32(sum);
5600
5601         if (super->clean_migration_record_by_mdmon) {
5602                 clear_migration_record = 1;
5603                 super->clean_migration_record_by_mdmon = 0;
5604         }
5605         if (clear_migration_record)
5606                 memset(super->migr_rec_buf, 0,
5607                     MIGR_REC_BUF_SECTORS*sector_size);
5608
5609         if (sector_size == 4096)
5610                 convert_to_4k(super);
5611
5612         /* write the mpb for disks that compose raid devices */
5613         for (d = super->disks; d ; d = d->next) {
5614                 if (d->index < 0 || is_failed(&d->disk))
5615                         continue;
5616
5617                 if (clear_migration_record) {
5618                         unsigned long long dsize;
5619
5620                         get_dev_size(d->fd, NULL, &dsize);
5621                         if (lseek64(d->fd, dsize - sector_size,
5622                             SEEK_SET) >= 0) {
5623                                 if (write(d->fd, super->migr_rec_buf,
5624                                     MIGR_REC_BUF_SECTORS*sector_size) !=
5625                                     MIGR_REC_BUF_SECTORS*sector_size)
5626                                         perror("Write migr_rec failed");
5627                         }
5628                 }
5629
5630                 if (store_imsm_mpb(d->fd, mpb))
5631                         fprintf(stderr,
5632                                 "failed for device %d:%d (fd: %d)%s\n",
5633                                 d->major, d->minor,
5634                                 d->fd, strerror(errno));
5635
5636                 if (doclose) {
5637                         close(d->fd);
5638                         d->fd = -1;
5639                 }
5640         }
5641
5642         if (spares)
5643                 return write_super_imsm_spares(super, doclose);
5644
5645         return 0;
5646 }
5647
5648 static int create_array(struct supertype *st, int dev_idx)
5649 {
5650         size_t len;
5651         struct imsm_update_create_array *u;
5652         struct intel_super *super = st->sb;
5653         struct imsm_dev *dev = get_imsm_dev(super, dev_idx);
5654         struct imsm_map *map = get_imsm_map(dev, MAP_0);
5655         struct disk_info *inf;
5656         struct imsm_disk *disk;
5657         int i;
5658
5659         len = sizeof(*u) - sizeof(*dev) + sizeof_imsm_dev(dev, 0) +
5660               sizeof(*inf) * map->num_members;
5661         u = xmalloc(len);
5662         u->type = update_create_array;
5663         u->dev_idx = dev_idx;
5664         imsm_copy_dev(&u->dev, dev);
5665         inf = get_disk_info(u);
5666         for (i = 0; i < map->num_members; i++) {
5667                 int idx = get_imsm_disk_idx(dev, i, MAP_X);
5668
5669                 disk = get_imsm_disk(super, idx);
5670                 if (!disk)
5671                         disk = get_imsm_missing(super, idx);
5672                 serialcpy(inf[i].serial, disk->serial);
5673         }
5674         append_metadata_update(st, u, len);
5675
5676         return 0;
5677 }
5678
5679 static int mgmt_disk(struct supertype *st)
5680 {
5681         struct intel_super *super = st->sb;
5682         size_t len;
5683         struct imsm_update_add_remove_disk *u;
5684
5685         if (!super->disk_mgmt_list)
5686                 return 0;
5687
5688         len = sizeof(*u);
5689         u = xmalloc(len);
5690         u->type = update_add_remove_disk;
5691         append_metadata_update(st, u, len);
5692
5693         return 0;
5694 }
5695
5696 static int write_init_super_imsm(struct supertype *st)
5697 {
5698         struct intel_super *super = st->sb;
5699         int current_vol = super->current_vol;
5700
5701         /* we are done with current_vol reset it to point st at the container */
5702         super->current_vol = -1;
5703
5704         if (st->update_tail) {
5705                 /* queue the recently created array / added disk
5706                  * as a metadata update */
5707                 int rv;
5708
5709                 /* determine if we are creating a volume or adding a disk */
5710                 if (current_vol < 0) {
5711                         /* in the mgmt (add/remove) disk case we are running
5712                          * in mdmon context, so don't close fd's
5713                          */
5714                         return mgmt_disk(st);
5715                 } else
5716                         rv = create_array(st, current_vol);
5717
5718                 return rv;
5719         } else {
5720                 struct dl *d;
5721                 for (d = super->disks; d; d = d->next)
5722                         Kill(d->devname, NULL, 0, -1, 1);
5723                 return write_super_imsm(st, 1);
5724         }
5725 }
5726 #endif
5727
5728 static int store_super_imsm(struct supertype *st, int fd)
5729 {
5730         struct intel_super *super = st->sb;
5731         struct imsm_super *mpb = super ? super->anchor : NULL;
5732
5733         if (!mpb)
5734                 return 1;
5735
5736 #ifndef MDASSEMBLE
5737         if (super->sector_size == 4096)
5738                 convert_to_4k(super);
5739         return store_imsm_mpb(fd, mpb);
5740 #else
5741         return 1;
5742 #endif
5743 }
5744
5745 #ifndef MDASSEMBLE
5746 static int validate_geometry_imsm_container(struct supertype *st, int level,
5747                                             int layout, int raiddisks, int chunk,
5748                                             unsigned long long size,
5749                                             unsigned long long data_offset,
5750                                             char *dev,
5751                                             unsigned long long *freesize,
5752                                             int verbose)
5753 {
5754         int fd;
5755         unsigned long long ldsize;
5756         struct intel_super *super;
5757         int rv = 0;
5758
5759         if (level != LEVEL_CONTAINER)
5760                 return 0;
5761         if (!dev)
5762                 return 1;
5763
5764         fd = open(dev, O_RDONLY|O_EXCL, 0);
5765         if (fd < 0) {
5766                 if (verbose > 0)
5767                         pr_err("imsm: Cannot open %s: %s\n",
5768                                 dev, strerror(errno));
5769                 return 0;
5770         }
5771         if (!get_dev_size(fd, dev, &ldsize)) {
5772                 close(fd);
5773                 return 0;
5774         }
5775
5776         /* capabilities retrieve could be possible
5777          * note that there is no fd for the disks in array.
5778          */
5779         super = alloc_super();
5780         if (!super) {
5781                 close(fd);
5782                 return 0;
5783         }
5784         if (!get_dev_sector_size(fd, NULL, &super->sector_size)) {
5785                 close(fd);
5786                 free_imsm(super);
5787                 return 0;
5788         }
5789
5790         rv = find_intel_hba_capability(fd, super, verbose > 0 ? dev : NULL);
5791         if (rv != 0) {
5792 #if DEBUG
5793                 char str[256];
5794                 fd2devname(fd, str);
5795                 dprintf("fd: %d %s orom: %p rv: %d raiddisk: %d\n",
5796                         fd, str, super->orom, rv, raiddisks);
5797 #endif
5798                 /* no orom/efi or non-intel hba of the disk */
5799                 close(fd);
5800                 free_imsm(super);
5801                 return 0;
5802         }
5803         close(fd);
5804         if (super->orom) {
5805                 if (raiddisks > super->orom->tds) {
5806                         if (verbose)
5807                                 pr_err("%d exceeds maximum number of platform supported disks: %d\n",
5808                                         raiddisks, super->orom->tds);
5809                         free_imsm(super);
5810                         return 0;
5811                 }
5812                 if ((super->orom->attr & IMSM_OROM_ATTR_2TB_DISK) == 0 &&
5813                     (ldsize >> 9) >> 32 > 0) {
5814                         if (verbose)
5815                                 pr_err("%s exceeds maximum platform supported size\n", dev);
5816                         free_imsm(super);
5817                         return 0;
5818                 }
5819         }
5820
5821         *freesize = avail_size_imsm(st, ldsize >> 9, data_offset);
5822         free_imsm(super);
5823
5824         return 1;
5825 }
5826
5827 static unsigned long long find_size(struct extent *e, int *idx, int num_extents)
5828 {
5829         const unsigned long long base_start = e[*idx].start;
5830         unsigned long long end = base_start + e[*idx].size;
5831         int i;
5832
5833         if (base_start == end)
5834                 return 0;
5835
5836         *idx = *idx + 1;
5837         for (i = *idx; i < num_extents; i++) {
5838                 /* extend overlapping extents */
5839                 if (e[i].start >= base_start &&
5840                     e[i].start <= end) {
5841                         if (e[i].size == 0)
5842                                 return 0;
5843                         if (e[i].start + e[i].size > end)
5844                                 end = e[i].start + e[i].size;
5845                 } else if (e[i].start > end) {
5846                         *idx = i;
5847                         break;
5848                 }
5849         }
5850
5851         return end - base_start;
5852 }
5853
5854 static unsigned long long merge_extents(struct intel_super *super, int sum_extents)
5855 {
5856         /* build a composite disk with all known extents and generate a new
5857          * 'maxsize' given the "all disks in an array must share a common start
5858          * offset" constraint
5859          */
5860         struct extent *e = xcalloc(sum_extents, sizeof(*e));
5861         struct dl *dl;
5862         int i, j;
5863         int start_extent;
5864         unsigned long long pos;
5865         unsigned long long start = 0;
5866         unsigned long long maxsize;
5867         unsigned long reserve;
5868
5869         /* coalesce and sort all extents. also, check to see if we need to
5870          * reserve space between member arrays
5871          */
5872         j = 0;
5873         for (dl = super->disks; dl; dl = dl->next) {
5874                 if (!dl->e)
5875                         continue;
5876                 for (i = 0; i < dl->extent_cnt; i++)
5877                         e[j++] = dl->e[i];
5878         }
5879         qsort(e, sum_extents, sizeof(*e), cmp_extent);
5880
5881         /* merge extents */
5882         i = 0;
5883         j = 0;
5884         while (i < sum_extents) {
5885                 e[j].start = e[i].start;
5886                 e[j].size = find_size(e, &i, sum_extents);
5887                 j++;
5888                 if (e[j-1].size == 0)
5889                         break;
5890         }
5891
5892         pos = 0;
5893         maxsize = 0;
5894         start_extent = 0;
5895         i = 0;
5896         do {
5897                 unsigned long long esize;
5898
5899                 esize = e[i].start - pos;
5900                 if (esize >= maxsize) {
5901                         maxsize = esize;
5902                         start = pos;
5903                         start_extent = i;
5904                 }
5905                 pos = e[i].start + e[i].size;
5906                 i++;
5907         } while (e[i-1].size);
5908         free(e);
5909
5910         if (maxsize == 0)
5911                 return 0;
5912
5913         /* FIXME assumes volume at offset 0 is the first volume in a
5914          * container
5915          */
5916         if (start_extent > 0)
5917                 reserve = IMSM_RESERVED_SECTORS; /* gap between raid regions */
5918         else
5919                 reserve = 0;
5920
5921         if (maxsize < reserve)
5922                 return 0;
5923
5924         super->create_offset = ~((unsigned long long) 0);
5925         if (start + reserve > super->create_offset)
5926                 return 0; /* start overflows create_offset */
5927         super->create_offset = start + reserve;
5928
5929         return maxsize - reserve;
5930 }
5931
5932 static int is_raid_level_supported(const struct imsm_orom *orom, int level, int raiddisks)
5933 {
5934         if (level < 0 || level == 6 || level == 4)
5935                 return 0;
5936
5937         /* if we have an orom prevent invalid raid levels */
5938         if (orom)
5939                 switch (level) {
5940                 case 0: return imsm_orom_has_raid0(orom);
5941                 case 1:
5942                         if (raiddisks > 2)
5943                                 return imsm_orom_has_raid1e(orom);
5944                         return imsm_orom_has_raid1(orom) && raiddisks == 2;
5945                 case 10: return imsm_orom_has_raid10(orom) && raiddisks == 4;
5946                 case 5: return imsm_orom_has_raid5(orom) && raiddisks > 2;
5947                 }
5948         else
5949                 return 1; /* not on an Intel RAID platform so anything goes */
5950
5951         return 0;
5952 }
5953
5954 static int
5955 active_arrays_by_format(char *name, char* hba, struct md_list **devlist,
5956                         int dpa, int verbose)
5957 {
5958         struct mdstat_ent *mdstat = mdstat_read(0, 0);
5959         struct mdstat_ent *memb;
5960         int count = 0;
5961         int num = 0;
5962         struct md_list *dv;
5963         int found;
5964
5965         for (memb = mdstat ; memb ; memb = memb->next) {
5966                 if (memb->metadata_version &&
5967                     (strncmp(memb->metadata_version, "external:", 9) == 0)  &&
5968                     (strcmp(&memb->metadata_version[9], name) == 0) &&
5969                     !is_subarray(memb->metadata_version+9) &&
5970                     memb->members) {
5971                         struct dev_member *dev = memb->members;
5972                         int fd = -1;
5973                         while(dev && (fd < 0)) {
5974                                 char *path = xmalloc(strlen(dev->name) + strlen("/dev/") + 1);
5975                                 num = sprintf(path, "%s%s", "/dev/", dev->name);
5976                                 if (num > 0)
5977                                         fd = open(path, O_RDONLY, 0);
5978                                 if (num <= 0 || fd < 0) {
5979                                         pr_vrb("Cannot open %s: %s\n",
5980                                                dev->name, strerror(errno));
5981                                 }
5982                                 free(path);
5983                                 dev = dev->next;
5984                         }
5985                         found = 0;
5986                         if (fd >= 0 && disk_attached_to_hba(fd, hba)) {
5987                                 struct mdstat_ent *vol;
5988                                 for (vol = mdstat ; vol ; vol = vol->next) {
5989                                         if (vol->active > 0 &&
5990                                             vol->metadata_version &&
5991                                             is_container_member(vol, memb->devnm)) {
5992                                                 found++;
5993                                                 count++;
5994                                         }
5995                                 }
5996                                 if (*devlist && (found < dpa)) {
5997                                         dv = xcalloc(1, sizeof(*dv));
5998                                         dv->devname = xmalloc(strlen(memb->devnm) + strlen("/dev/") + 1);
5999                                         sprintf(dv->devname, "%s%s", "/dev/", memb->devnm);
6000                                         dv->found = found;
6001                                         dv->used = 0;
6002                                         dv->next = *devlist;
6003                                         *devlist = dv;
6004                                 }
6005                         }
6006                         if (fd >= 0)
6007                                 close(fd);
6008                 }
6009         }
6010         free_mdstat(mdstat);
6011         return count;
6012 }
6013
6014 #ifdef DEBUG_LOOP
6015 static struct md_list*
6016 get_loop_devices(void)
6017 {
6018         int i;
6019         struct md_list *devlist = NULL;
6020         struct md_list *dv;
6021
6022         for(i = 0; i < 12; i++) {
6023                 dv = xcalloc(1, sizeof(*dv));
6024                 dv->devname = xmalloc(40);
6025                 sprintf(dv->devname, "/dev/loop%d", i);
6026                 dv->next = devlist;
6027                 devlist = dv;
6028         }
6029         return devlist;
6030 }
6031 #endif
6032
6033 static struct md_list*
6034 get_devices(const char *hba_path)
6035 {
6036         struct md_list *devlist = NULL;
6037         struct md_list *dv;
6038         struct dirent *ent;
6039         DIR *dir;
6040         int err = 0;
6041
6042 #if DEBUG_LOOP
6043         devlist = get_loop_devices();
6044         return devlist;
6045 #endif
6046         /* scroll through /sys/dev/block looking for devices attached to
6047          * this hba
6048          */
6049         dir = opendir("/sys/dev/block");
6050         for (ent = dir ? readdir(dir) : NULL; ent; ent = readdir(dir)) {
6051                 int fd;
6052                 char buf[1024];
6053                 int major, minor;
6054                 char *path = NULL;
6055                 if (sscanf(ent->d_name, "%d:%d", &major, &minor) != 2)
6056                         continue;
6057                 path = devt_to_devpath(makedev(major, minor));
6058                 if (!path)
6059                         continue;
6060                 if (!path_attached_to_hba(path, hba_path)) {
6061                         free(path);
6062                         path = NULL;
6063                         continue;
6064                 }
6065                 free(path);
6066                 path = NULL;
6067                 fd = dev_open(ent->d_name, O_RDONLY);
6068                 if (fd >= 0) {
6069                         fd2devname(fd, buf);
6070                         close(fd);
6071                 } else {
6072                         pr_err("cannot open device: %s\n",
6073                                 ent->d_name);
6074                         continue;
6075                 }
6076
6077                 dv = xcalloc(1, sizeof(*dv));
6078                 dv->devname = xstrdup(buf);
6079                 dv->next = devlist;
6080                 devlist = dv;
6081         }
6082         if (err) {
6083                 while(devlist) {
6084                         dv = devlist;
6085                         devlist = devlist->next;
6086                         free(dv->devname);
6087                         free(dv);
6088                 }
6089         }
6090         closedir(dir);
6091         return devlist;
6092 }
6093
6094 static int
6095 count_volumes_list(struct md_list *devlist, char *homehost,
6096                    int verbose, int *found)
6097 {
6098         struct md_list *tmpdev;
6099         int count = 0;
6100         struct supertype *st;
6101
6102         /* first walk the list of devices to find a consistent set
6103          * that match the criterea, if that is possible.
6104          * We flag the ones we like with 'used'.
6105          */
6106         *found = 0;
6107         st = match_metadata_desc_imsm("imsm");
6108         if (st == NULL) {
6109                 pr_vrb("cannot allocate memory for imsm supertype\n");
6110                 return 0;
6111         }
6112
6113         for (tmpdev = devlist; tmpdev; tmpdev = tmpdev->next) {
6114                 char *devname = tmpdev->devname;
6115                 struct stat stb;
6116                 struct supertype *tst;
6117                 int dfd;
6118                 if (tmpdev->used > 1)
6119                         continue;
6120                 tst = dup_super(st);
6121                 if (tst == NULL) {
6122                         pr_vrb("cannot allocate memory for imsm supertype\n");
6123                         goto err_1;
6124                 }
6125                 tmpdev->container = 0;
6126                 dfd = dev_open(devname, O_RDONLY|O_EXCL);
6127                 if (dfd < 0) {
6128                         dprintf("cannot open device %s: %s\n",
6129                                 devname, strerror(errno));
6130                         tmpdev->used = 2;
6131                 } else if (fstat(dfd, &stb)< 0) {
6132                         /* Impossible! */
6133                         dprintf("fstat failed for %s: %s\n",
6134                                 devname, strerror(errno));
6135                         tmpdev->used = 2;
6136                 } else if ((stb.st_mode & S_IFMT) != S_IFBLK) {
6137                         dprintf("%s is not a block device.\n",
6138                                 devname);
6139                         tmpdev->used = 2;
6140                 } else if (must_be_container(dfd)) {
6141                         struct supertype *cst;
6142                         cst = super_by_fd(dfd, NULL);
6143                         if (cst == NULL) {
6144                                 dprintf("cannot recognize container type %s\n",
6145                                         devname);
6146                                 tmpdev->used = 2;
6147                         } else if (tst->ss != st->ss) {
6148                                 dprintf("non-imsm container - ignore it: %s\n",
6149                                         devname);
6150                                 tmpdev->used = 2;
6151                         } else if (!tst->ss->load_container ||
6152                                    tst->ss->load_container(tst, dfd, NULL))
6153                                 tmpdev->used = 2;
6154                         else {
6155                                 tmpdev->container = 1;
6156                         }
6157                         if (cst)
6158                                 cst->ss->free_super(cst);
6159                 } else {
6160                         tmpdev->st_rdev = stb.st_rdev;
6161                         if (tst->ss->load_super(tst,dfd, NULL)) {
6162                                 dprintf("no RAID superblock on %s\n",
6163                                         devname);
6164                                 tmpdev->used = 2;
6165                         } else if (tst->ss->compare_super == NULL) {
6166                                 dprintf("Cannot assemble %s metadata on %s\n",
6167                                         tst->ss->name, devname);
6168                                 tmpdev->used = 2;
6169                         }
6170                 }
6171                 if (dfd >= 0)
6172                         close(dfd);
6173                 if (tmpdev->used == 2 || tmpdev->used == 4) {
6174                         /* Ignore unrecognised devices during auto-assembly */
6175                         goto loop;
6176                 }
6177                 else {
6178                         struct mdinfo info;
6179                         tst->ss->getinfo_super(tst, &info, NULL);
6180
6181                         if (st->minor_version == -1)
6182                                 st->minor_version = tst->minor_version;
6183
6184                         if (memcmp(info.uuid, uuid_zero,
6185                                    sizeof(int[4])) == 0) {
6186                                 /* this is a floating spare.  It cannot define
6187                                  * an array unless there are no more arrays of
6188                                  * this type to be found.  It can be included
6189                                  * in an array of this type though.
6190                                  */
6191                                 tmpdev->used = 3;
6192                                 goto loop;
6193                         }
6194
6195                         if (st->ss != tst->ss ||
6196                             st->minor_version != tst->minor_version ||
6197                             st->ss->compare_super(st, tst) != 0) {
6198                                 /* Some mismatch. If exactly one array matches this host,
6199                                  * we can resolve on that one.
6200                                  * Or, if we are auto assembling, we just ignore the second
6201                                  * for now.
6202                                  */
6203                                 dprintf("superblock on %s doesn't match others - assembly aborted\n",
6204                                         devname);
6205                                 goto loop;
6206                         }
6207                         tmpdev->used = 1;
6208                         *found = 1;
6209                         dprintf("found: devname: %s\n", devname);
6210                 }
6211         loop:
6212                 if (tst)
6213                         tst->ss->free_super(tst);
6214         }
6215         if (*found != 0) {
6216                 int err;
6217                 if ((err = load_super_imsm_all(st, -1, &st->sb, NULL, devlist, 0)) == 0) {
6218                         struct mdinfo *iter, *head = st->ss->container_content(st, NULL);
6219                         for (iter = head; iter; iter = iter->next) {
6220                                 dprintf("content->text_version: %s vol\n",
6221                                         iter->text_version);
6222                                 if (iter->array.state & (1<<MD_SB_BLOCK_VOLUME)) {
6223                                         /* do not assemble arrays with unsupported
6224                                            configurations */
6225                                         dprintf("Cannot activate member %s.\n",
6226                                                 iter->text_version);
6227                                 } else
6228                                         count++;
6229                         }
6230                         sysfs_free(head);
6231
6232                 } else {
6233                         dprintf("No valid super block on device list: err: %d %p\n",
6234                                 err, st->sb);
6235                 }
6236         } else {
6237                 dprintf("no more devices to examine\n");
6238         }
6239
6240         for (tmpdev = devlist; tmpdev; tmpdev = tmpdev->next) {
6241                 if (tmpdev->used == 1 && tmpdev->found) {
6242                         if (count) {
6243                                 if (count < tmpdev->found)
6244                                         count = 0;
6245                                 else
6246                                         count -= tmpdev->found;
6247                         }
6248                 }
6249                 if (tmpdev->used == 1)
6250                         tmpdev->used = 4;
6251         }
6252         err_1:
6253         if (st)
6254                 st->ss->free_super(st);
6255         return count;
6256 }
6257
6258 static int
6259 count_volumes(struct intel_hba *hba, int dpa, int verbose)
6260 {
6261         struct sys_dev *idev, *intel_devices = find_intel_devices();
6262         int count = 0;
6263         const struct orom_entry *entry;
6264         struct devid_list *dv, *devid_list;
6265
6266         if (!hba || !hba->path)
6267                 return 0;
6268
6269         for (idev = intel_devices; idev; idev = idev->next) {
6270                 if (strstr(idev->path, hba->path))
6271                                 break;
6272         }
6273
6274         if (!idev || !idev->dev_id)
6275                 return 0;
6276
6277         entry = get_orom_entry_by_device_id(idev->dev_id);
6278
6279         if (!entry || !entry->devid_list)
6280                 return 0;
6281
6282         devid_list = entry->devid_list;
6283         for (dv = devid_list; dv; dv = dv->next) {
6284                 struct md_list *devlist;
6285                 struct sys_dev *device = device_by_id(dv->devid);
6286                 char *hba_path;
6287                 int found = 0;
6288
6289                 if (device)
6290                         hba_path = device->path;
6291                 else
6292                         return 0;
6293
6294                 devlist = get_devices(hba_path);
6295                 /* if no intel devices return zero volumes */
6296                 if (devlist == NULL)
6297                         return 0;
6298
6299                 count += active_arrays_by_format("imsm", hba_path, &devlist, dpa, verbose);
6300                 dprintf("path: %s active arrays: %d\n", hba_path, count);
6301                 if (devlist == NULL)
6302                         return 0;
6303                 do  {
6304                         found = 0;
6305                         count += count_volumes_list(devlist,
6306                                                         NULL,
6307                                                         verbose,
6308                                                         &found);
6309                         dprintf("found %d count: %d\n", found, count);
6310                 } while (found);
6311
6312                 dprintf("path: %s total number of volumes: %d\n", hba_path, count);
6313
6314                 while (devlist) {
6315                         struct md_list *dv = devlist;
6316                         devlist = devlist->next;
6317                         free(dv->devname);
6318                         free(dv);
6319                 }
6320         }
6321         return count;
6322 }
6323
6324 static int imsm_default_chunk(const struct imsm_orom *orom)
6325 {
6326         /* up to 512 if the plaform supports it, otherwise the platform max.
6327          * 128 if no platform detected
6328          */
6329         int fs = max(7, orom ? fls(orom->sss) : 0);
6330
6331         return min(512, (1 << fs));
6332 }
6333
6334 static int
6335 validate_geometry_imsm_orom(struct intel_super *super, int level, int layout,
6336                             int raiddisks, int *chunk, unsigned long long size, int verbose)
6337 {
6338         /* check/set platform and metadata limits/defaults */
6339         if (super->orom && raiddisks > super->orom->dpa) {
6340                 pr_vrb("platform supports a maximum of %d disks per array\n",
6341                        super->orom->dpa);
6342                 return 0;
6343         }
6344
6345         /* capabilities of OROM tested - copied from validate_geometry_imsm_volume */
6346         if (!is_raid_level_supported(super->orom, level, raiddisks)) {
6347                 pr_vrb("platform does not support raid%d with %d disk%s\n",
6348                         level, raiddisks, raiddisks > 1 ? "s" : "");
6349                 return 0;
6350         }
6351
6352         if (*chunk == 0 || *chunk == UnSet)
6353                 *chunk = imsm_default_chunk(super->orom);
6354
6355         if (super->orom && !imsm_orom_has_chunk(super->orom, *chunk)) {
6356                 pr_vrb("platform does not support a chunk size of: %d\n", *chunk);
6357                 return 0;
6358         }
6359
6360         if (layout != imsm_level_to_layout(level)) {
6361                 if (level == 5)
6362                         pr_vrb("imsm raid 5 only supports the left-asymmetric layout\n");
6363                 else if (level == 10)
6364                         pr_vrb("imsm raid 10 only supports the n2 layout\n");
6365                 else
6366                         pr_vrb("imsm unknown layout %#x for this raid level %d\n",
6367                                 layout, level);
6368                 return 0;
6369         }
6370
6371         if (super->orom && (super->orom->attr & IMSM_OROM_ATTR_2TB) == 0 &&
6372                         (calc_array_size(level, raiddisks, layout, *chunk, size) >> 32) > 0) {
6373                 pr_vrb("platform does not support a volume size over 2TB\n");
6374                 return 0;
6375         }
6376
6377         return 1;
6378 }
6379
6380 /* validate_geometry_imsm_volume - lifted from validate_geometry_ddf_bvd
6381  * FIX ME add ahci details
6382  */
6383 static int validate_geometry_imsm_volume(struct supertype *st, int level,
6384                                          int layout, int raiddisks, int *chunk,
6385                                          unsigned long long size,
6386                                          unsigned long long data_offset,
6387                                          char *dev,
6388                                          unsigned long long *freesize,
6389                                          int verbose)
6390 {
6391         struct stat stb;
6392         struct intel_super *super = st->sb;
6393         struct imsm_super *mpb;
6394         struct dl *dl;
6395         unsigned long long pos = 0;
6396         unsigned long long maxsize;
6397         struct extent *e;
6398         int i;
6399
6400         /* We must have the container info already read in. */
6401         if (!super)
6402                 return 0;
6403
6404         mpb = super->anchor;
6405
6406         if (!validate_geometry_imsm_orom(super, level, layout, raiddisks, chunk, size, verbose)) {
6407                 pr_err("RAID gemetry validation failed. Cannot proceed with the action(s).\n");
6408                 return 0;
6409         }
6410         if (!dev) {
6411                 /* General test:  make sure there is space for
6412                  * 'raiddisks' device extents of size 'size' at a given
6413                  * offset
6414                  */
6415                 unsigned long long minsize = size;
6416                 unsigned long long start_offset = MaxSector;
6417                 int dcnt = 0;
6418                 if (minsize == 0)
6419                         minsize = MPB_SECTOR_CNT + IMSM_RESERVED_SECTORS;
6420                 for (dl = super->disks; dl ; dl = dl->next) {
6421                         int found = 0;
6422
6423                         pos = 0;
6424                         i = 0;
6425                         e = get_extents(super, dl);
6426                         if (!e) continue;
6427                         do {
6428                                 unsigned long long esize;
6429                                 esize = e[i].start - pos;
6430                                 if (esize >= minsize)
6431                                         found = 1;
6432                                 if (found && start_offset == MaxSector) {
6433                                         start_offset = pos;
6434                                         break;
6435                                 } else if (found && pos != start_offset) {
6436                                         found = 0;
6437                                         break;
6438                                 }
6439                                 pos = e[i].start + e[i].size;
6440                                 i++;
6441                         } while (e[i-1].size);
6442                         if (found)
6443                                 dcnt++;
6444                         free(e);
6445                 }
6446                 if (dcnt < raiddisks) {
6447                         if (verbose)
6448                                 pr_err("imsm: Not enough devices with space for this array (%d < %d)\n",
6449                                         dcnt, raiddisks);
6450                         return 0;
6451                 }
6452                 return 1;
6453         }
6454
6455         /* This device must be a member of the set */
6456         if (stat(dev, &stb) < 0)
6457                 return 0;
6458         if ((S_IFMT & stb.st_mode) != S_IFBLK)
6459                 return 0;
6460         for (dl = super->disks ; dl ; dl = dl->next) {
6461                 if (dl->major == (int)major(stb.st_rdev) &&
6462                     dl->minor == (int)minor(stb.st_rdev))
6463                         break;
6464         }
6465         if (!dl) {
6466                 if (verbose)
6467                         pr_err("%s is not in the same imsm set\n", dev);
6468                 return 0;
6469         } else if (super->orom && dl->index < 0 && mpb->num_raid_devs) {
6470                 /* If a volume is present then the current creation attempt
6471                  * cannot incorporate new spares because the orom may not
6472                  * understand this configuration (all member disks must be
6473                  * members of each array in the container).
6474                  */
6475                 pr_err("%s is a spare and a volume is already defined for this container\n", dev);
6476                 pr_err("The option-rom requires all member disks to be a member of all volumes\n");
6477                 return 0;
6478         } else if (super->orom && mpb->num_raid_devs > 0 &&
6479                    mpb->num_disks != raiddisks) {
6480                 pr_err("The option-rom requires all member disks to be a member of all volumes\n");
6481                 return 0;
6482         }
6483
6484         /* retrieve the largest free space block */
6485         e = get_extents(super, dl);
6486         maxsize = 0;
6487         i = 0;
6488         if (e) {
6489                 do {
6490                         unsigned long long esize;
6491
6492                         esize = e[i].start - pos;
6493                         if (esize >= maxsize)
6494                                 maxsize = esize;
6495                         pos = e[i].start + e[i].size;
6496                         i++;
6497                 } while (e[i-1].size);
6498                 dl->e = e;
6499                 dl->extent_cnt = i;
6500         } else {
6501                 if (verbose)
6502                         pr_err("unable to determine free space for: %s\n",
6503                                 dev);
6504                 return 0;
6505         }
6506         if (maxsize < size) {
6507                 if (verbose)
6508                         pr_err("%s not enough space (%llu < %llu)\n",
6509                                 dev, maxsize, size);
6510                 return 0;
6511         }
6512
6513         /* count total number of extents for merge */
6514         i = 0;
6515         for (dl = super->disks; dl; dl = dl->next)
6516                 if (dl->e)
6517                         i += dl->extent_cnt;
6518
6519         maxsize = merge_extents(super, i);
6520
6521         if (!check_env("IMSM_NO_PLATFORM") &&
6522             mpb->num_raid_devs > 0 && size && size != maxsize) {
6523                 pr_err("attempting to create a second volume with size less then remaining space. Aborting...\n");
6524                 return 0;
6525         }
6526
6527         if (maxsize < size || maxsize == 0) {
6528                 if (verbose) {
6529                         if (maxsize == 0)
6530                                 pr_err("no free space left on device. Aborting...\n");
6531                         else
6532                                 pr_err("not enough space to create volume of given size (%llu < %llu). Aborting...\n",
6533                                                 maxsize, size);
6534                 }
6535                 return 0;
6536         }
6537
6538         *freesize = maxsize;
6539
6540         if (super->orom) {
6541                 int count = count_volumes(super->hba,
6542                                       super->orom->dpa, verbose);
6543                 if (super->orom->vphba <= count) {
6544                         pr_vrb("platform does not support more than %d raid volumes.\n",
6545                                super->orom->vphba);
6546                         return 0;
6547                 }
6548         }
6549         return 1;
6550 }
6551
6552 static int imsm_get_free_size(struct supertype *st, int raiddisks,
6553                          unsigned long long size, int chunk,
6554                          unsigned long long *freesize)
6555 {
6556         struct intel_super *super = st->sb;
6557         struct imsm_super *mpb = super->anchor;
6558         struct dl *dl;
6559         int i;
6560         int extent_cnt;
6561         struct extent *e;
6562         unsigned long long maxsize;
6563         unsigned long long minsize;
6564         int cnt;
6565         int used;
6566
6567         /* find the largest common start free region of the possible disks */
6568         used = 0;
6569         extent_cnt = 0;
6570         cnt = 0;
6571         for (dl = super->disks; dl; dl = dl->next) {
6572                 dl->raiddisk = -1;
6573
6574                 if (dl->index >= 0)
6575                         used++;
6576
6577                 /* don't activate new spares if we are orom constrained
6578                  * and there is already a volume active in the container
6579                  */
6580                 if (super->orom && dl->index < 0 && mpb->num_raid_devs)
6581                         continue;
6582
6583                 e = get_extents(super, dl);
6584                 if (!e)
6585                         continue;
6586                 for (i = 1; e[i-1].size; i++)
6587                         ;
6588                 dl->e = e;
6589                 dl->extent_cnt = i;
6590                 extent_cnt += i;
6591                 cnt++;
6592         }
6593
6594         maxsize = merge_extents(super, extent_cnt);
6595         minsize = size;
6596         if (size == 0)
6597                 /* chunk is in K */
6598                 minsize = chunk * 2;
6599
6600         if (cnt < raiddisks ||
6601             (super->orom && used && used != raiddisks) ||
6602             maxsize < minsize ||
6603             maxsize == 0) {
6604                 pr_err("not enough devices with space to create array.\n");
6605                 return 0; /* No enough free spaces large enough */
6606         }
6607
6608         if (size == 0) {
6609                 size = maxsize;
6610                 if (chunk) {
6611                         size /= 2 * chunk;
6612                         size *= 2 * chunk;
6613                 }
6614                 maxsize = size;
6615         }
6616         if (!check_env("IMSM_NO_PLATFORM") &&
6617             mpb->num_raid_devs > 0 && size && size != maxsize) {
6618                 pr_err("attempting to create a second volume with size less then remaining space. Aborting...\n");
6619                 return 0;
6620         }
6621         cnt = 0;
6622         for (dl = super->disks; dl; dl = dl->next)
6623                 if (dl->e)
6624                         dl->raiddisk = cnt++;
6625
6626         *freesize = size;
6627
6628         dprintf("imsm: imsm_get_free_size() returns : %llu\n", size);
6629
6630         return 1;
6631 }
6632
6633 static int reserve_space(struct supertype *st, int raiddisks,
6634                          unsigned long long size, int chunk,
6635                          unsigned long long *freesize)
6636 {
6637         struct intel_super *super = st->sb;
6638         struct dl *dl;
6639         int cnt;
6640         int rv = 0;
6641
6642         rv = imsm_get_free_size(st, raiddisks, size, chunk, freesize);
6643         if (rv) {
6644                 cnt = 0;
6645                 for (dl = super->disks; dl; dl = dl->next)
6646                         if (dl->e)
6647                                 dl->raiddisk = cnt++;
6648                 rv = 1;
6649         }
6650
6651         return rv;
6652 }
6653
6654 static int validate_geometry_imsm(struct supertype *st, int level, int layout,
6655                                   int raiddisks, int *chunk, unsigned long long size,
6656                                   unsigned long long data_offset,
6657                                   char *dev, unsigned long long *freesize,
6658                                   int verbose)
6659 {
6660         int fd, cfd;
6661         struct mdinfo *sra;
6662         int is_member = 0;
6663
6664         /* load capability
6665          * if given unused devices create a container
6666          * if given given devices in a container create a member volume
6667          */
6668         if (level == LEVEL_CONTAINER) {
6669                 /* Must be a fresh device to add to a container */
6670                 return validate_geometry_imsm_container(st, level, layout,
6671                                                         raiddisks,
6672                                                         *chunk,
6673                                                         size, data_offset,
6674                                                         dev, freesize,
6675                                                         verbose);
6676         }
6677
6678         if (!dev) {
6679                 if (st->sb) {
6680                         struct intel_super *super = st->sb;
6681                         if (!validate_geometry_imsm_orom(st->sb, level, layout,
6682                                                          raiddisks, chunk, size,
6683                                                          verbose))
6684                                 return 0;
6685                         /* we are being asked to automatically layout a
6686                          * new volume based on the current contents of
6687                          * the container.  If the the parameters can be
6688                          * satisfied reserve_space will record the disks,
6689                          * start offset, and size of the volume to be
6690                          * created.  add_to_super and getinfo_super
6691                          * detect when autolayout is in progress.
6692                          */
6693                         /* assuming that freesize is always given when array is
6694                            created */
6695                         if (super->orom && freesize) {
6696                                 int count;
6697                                 count = count_volumes(super->hba,
6698                                                       super->orom->dpa, verbose);
6699                                 if (super->orom->vphba <= count) {
6700                                         pr_vrb("platform does not support more than %d raid volumes.\n",
6701                                                super->orom->vphba);
6702                                         return 0;
6703                                 }
6704                         }
6705                         if (freesize)
6706                                 return reserve_space(st, raiddisks, size,
6707                                                      *chunk, freesize);
6708                 }
6709                 return 1;
6710         }
6711         if (st->sb) {
6712                 /* creating in a given container */
6713                 return validate_geometry_imsm_volume(st, level, layout,
6714                                                      raiddisks, chunk, size,
6715                                                      data_offset,
6716                                                      dev, freesize, verbose);
6717         }
6718
6719         /* This device needs to be a device in an 'imsm' container */
6720         fd = open(dev, O_RDONLY|O_EXCL, 0);
6721         if (fd >= 0) {
6722                 if (verbose)
6723                         pr_err("Cannot create this array on device %s\n",
6724                                dev);
6725                 close(fd);
6726                 return 0;
6727         }
6728         if (errno != EBUSY || (fd = open(dev, O_RDONLY, 0)) < 0) {
6729                 if (verbose)
6730                         pr_err("Cannot open %s: %s\n",
6731                                 dev, strerror(errno));
6732                 return 0;
6733         }
6734         /* Well, it is in use by someone, maybe an 'imsm' container. */
6735         cfd = open_container(fd);
6736         close(fd);
6737         if (cfd < 0) {
6738                 if (verbose)
6739                         pr_err("Cannot use %s: It is busy\n",
6740                                 dev);
6741                 return 0;
6742         }
6743         sra = sysfs_read(cfd, NULL, GET_VERSION);
6744         if (sra && sra->array.major_version == -1 &&
6745             strcmp(sra->text_version, "imsm") == 0)
6746                 is_member = 1;
6747         sysfs_free(sra);
6748         if (is_member) {
6749                 /* This is a member of a imsm container.  Load the container
6750                  * and try to create a volume
6751                  */
6752                 struct intel_super *super;
6753
6754                 if (load_super_imsm_all(st, cfd, (void **) &super, NULL, NULL, 1) == 0) {
6755                         st->sb = super;
6756                         strcpy(st->container_devnm, fd2devnm(cfd));
6757                         close(cfd);
6758                         return validate_geometry_imsm_volume(st, level, layout,
6759                                                              raiddisks, chunk,
6760                                                              size, data_offset, dev,
6761                                                              freesize, 1)
6762                                 ? 1 : -1;
6763                 }
6764         }
6765
6766         if (verbose)
6767                 pr_err("failed container membership check\n");
6768
6769         close(cfd);
6770         return 0;
6771 }
6772
6773 static void default_geometry_imsm(struct supertype *st, int *level, int *layout, int *chunk)
6774 {
6775         struct intel_super *super = st->sb;
6776
6777         if (level && *level == UnSet)
6778                 *level = LEVEL_CONTAINER;
6779
6780         if (level && layout && *layout == UnSet)
6781                 *layout = imsm_level_to_layout(*level);
6782
6783         if (chunk && (*chunk == UnSet || *chunk == 0))
6784                 *chunk = imsm_default_chunk(super->orom);
6785 }
6786
6787 static void handle_missing(struct intel_super *super, struct imsm_dev *dev);
6788
6789 static int kill_subarray_imsm(struct supertype *st)
6790 {
6791         /* remove the subarray currently referenced by ->current_vol */
6792         __u8 i;
6793         struct intel_dev **dp;
6794         struct intel_super *super = st->sb;
6795         __u8 current_vol = super->current_vol;
6796         struct imsm_super *mpb = super->anchor;
6797
6798         if (super->current_vol < 0)
6799                 return 2;
6800         super->current_vol = -1; /* invalidate subarray cursor */
6801
6802         /* block deletions that would change the uuid of active subarrays
6803          *
6804          * FIXME when immutable ids are available, but note that we'll
6805          * also need to fixup the invalidated/active subarray indexes in
6806          * mdstat
6807          */
6808         for (i = 0; i < mpb->num_raid_devs; i++) {
6809                 char subarray[4];
6810
6811                 if (i < current_vol)
6812                         continue;
6813                 sprintf(subarray, "%u", i);
6814                 if (is_subarray_active(subarray, st->devnm)) {
6815                         pr_err("deleting subarray-%d would change the UUID of active subarray-%d, aborting\n",
6816                                current_vol, i);
6817
6818                         return 2;
6819                 }
6820         }
6821
6822         if (st->update_tail) {
6823                 struct imsm_update_kill_array *u = xmalloc(sizeof(*u));
6824
6825                 u->type = update_kill_array;
6826                 u->dev_idx = current_vol;
6827                 append_metadata_update(st, u, sizeof(*u));
6828
6829                 return 0;
6830         }
6831
6832         for (dp = &super->devlist; *dp;)
6833                 if ((*dp)->index == current_vol) {
6834                         *dp = (*dp)->next;
6835                 } else {
6836                         handle_missing(super, (*dp)->dev);
6837                         if ((*dp)->index > current_vol)
6838                                 (*dp)->index--;
6839                         dp = &(*dp)->next;
6840                 }
6841
6842         /* no more raid devices, all active components are now spares,
6843          * but of course failed are still failed
6844          */
6845         if (--mpb->num_raid_devs == 0) {
6846                 struct dl *d;
6847
6848                 for (d = super->disks; d; d = d->next)
6849                         if (d->index > -2)
6850                                 mark_spare(d);
6851         }
6852
6853         super->updates_pending++;
6854
6855         return 0;
6856 }
6857
6858 static int update_subarray_imsm(struct supertype *st, char *subarray,
6859                                 char *update, struct mddev_ident *ident)
6860 {
6861         /* update the subarray currently referenced by ->current_vol */
6862         struct intel_super *super = st->sb;
6863         struct imsm_super *mpb = super->anchor;
6864
6865         if (strcmp(update, "name") == 0) {
6866                 char *name = ident->name;
6867                 char *ep;
6868                 int vol;
6869
6870                 if (is_subarray_active(subarray, st->devnm)) {
6871                         pr_err("Unable to update name of active subarray\n");
6872                         return 2;
6873                 }
6874
6875                 if (!check_name(super, name, 0))
6876                         return 2;
6877
6878                 vol = strtoul(subarray, &ep, 10);
6879                 if (*ep != '\0' || vol >= super->anchor->num_raid_devs)
6880                         return 2;
6881
6882                 if (st->update_tail) {
6883                         struct imsm_update_rename_array *u = xmalloc(sizeof(*u));
6884
6885                         u->type = update_rename_array;
6886                         u->dev_idx = vol;
6887                         snprintf((char *) u->name, MAX_RAID_SERIAL_LEN, "%s", name);
6888                         append_metadata_update(st, u, sizeof(*u));
6889                 } else {
6890                         struct imsm_dev *dev;
6891                         int i;
6892
6893                         dev = get_imsm_dev(super, vol);
6894                         snprintf((char *) dev->volume, MAX_RAID_SERIAL_LEN, "%s", name);
6895                         for (i = 0; i < mpb->num_raid_devs; i++) {
6896                                 dev = get_imsm_dev(super, i);
6897                                 handle_missing(super, dev);
6898                         }
6899                         super->updates_pending++;
6900                 }
6901         } else
6902                 return 2;
6903
6904         return 0;
6905 }
6906 #endif /* MDASSEMBLE */
6907
6908 static int is_gen_migration(struct imsm_dev *dev)
6909 {
6910         if (dev == NULL)
6911                 return 0;
6912
6913         if (!dev->vol.migr_state)
6914                 return 0;
6915
6916         if (migr_type(dev) == MIGR_GEN_MIGR)
6917                 return 1;
6918
6919         return 0;
6920 }
6921
6922 static int is_rebuilding(struct imsm_dev *dev)
6923 {
6924         struct imsm_map *migr_map;
6925
6926         if (!dev->vol.migr_state)
6927                 return 0;
6928
6929         if (migr_type(dev) != MIGR_REBUILD)
6930                 return 0;
6931
6932         migr_map = get_imsm_map(dev, MAP_1);
6933
6934         if (migr_map->map_state == IMSM_T_STATE_DEGRADED)
6935                 return 1;
6936         else
6937                 return 0;
6938 }
6939
6940 #ifndef MDASSEMBLE
6941 static int is_initializing(struct imsm_dev *dev)
6942 {
6943         struct imsm_map *migr_map;
6944
6945         if (!dev->vol.migr_state)
6946                 return 0;
6947
6948         if (migr_type(dev) != MIGR_INIT)
6949                 return 0;
6950
6951         migr_map = get_imsm_map(dev, MAP_1);
6952
6953         if (migr_map->map_state == IMSM_T_STATE_UNINITIALIZED)
6954                 return 1;
6955
6956         return 0;
6957 }
6958 #endif
6959
6960 static void update_recovery_start(struct intel_super *super,
6961                                         struct imsm_dev *dev,
6962                                         struct mdinfo *array)
6963 {
6964         struct mdinfo *rebuild = NULL;
6965         struct mdinfo *d;
6966         __u32 units;
6967
6968         if (!is_rebuilding(dev))
6969                 return;
6970
6971         /* Find the rebuild target, but punt on the dual rebuild case */
6972         for (d = array->devs; d; d = d->next)
6973                 if (d->recovery_start == 0) {
6974                         if (rebuild)
6975                                 return;
6976                         rebuild = d;
6977                 }
6978
6979         if (!rebuild) {
6980                 /* (?) none of the disks are marked with
6981                  * IMSM_ORD_REBUILD, so assume they are missing and the
6982                  * disk_ord_tbl was not correctly updated
6983                  */
6984                 dprintf("failed to locate out-of-sync disk\n");
6985                 return;
6986         }
6987
6988         units = __le32_to_cpu(dev->vol.curr_migr_unit);
6989         rebuild->recovery_start = units * blocks_per_migr_unit(super, dev);
6990 }
6991
6992 #ifndef MDASSEMBLE
6993 static int recover_backup_imsm(struct supertype *st, struct mdinfo *info);
6994 #endif
6995
6996 static struct mdinfo *container_content_imsm(struct supertype *st, char *subarray)
6997 {
6998         /* Given a container loaded by load_super_imsm_all,
6999          * extract information about all the arrays into
7000          * an mdinfo tree.
7001          * If 'subarray' is given, just extract info about that array.
7002          *
7003          * For each imsm_dev create an mdinfo, fill it in,
7004          *  then look for matching devices in super->disks
7005          *  and create appropriate device mdinfo.
7006          */
7007         struct intel_super *super = st->sb;
7008         struct imsm_super *mpb = super->anchor;
7009         struct mdinfo *rest = NULL;
7010         unsigned int i;
7011         int sb_errors = 0;
7012         struct dl *d;
7013         int spare_disks = 0;
7014
7015         /* do not assemble arrays when not all attributes are supported */
7016         if (imsm_check_attributes(mpb->attributes) == 0) {
7017                 sb_errors = 1;
7018                 pr_err("Unsupported attributes in IMSM metadata.Arrays activation is blocked.\n");
7019         }
7020
7021         /* count spare devices, not used in maps
7022          */
7023         for (d = super->disks; d; d = d->next)
7024                 if (d->index == -1)
7025                         spare_disks++;
7026
7027         for (i = 0; i < mpb->num_raid_devs; i++) {
7028                 struct imsm_dev *dev;
7029                 struct imsm_map *map;
7030                 struct imsm_map *map2;
7031                 struct mdinfo *this;
7032                 int slot;
7033 #ifndef MDASSEMBLE
7034                 int chunk;
7035 #endif
7036                 char *ep;
7037
7038                 if (subarray &&
7039                     (i != strtoul(subarray, &ep, 10) || *ep != '\0'))
7040                         continue;
7041
7042                 dev = get_imsm_dev(super, i);
7043                 map = get_imsm_map(dev, MAP_0);
7044                 map2 = get_imsm_map(dev, MAP_1);
7045
7046                 /* do not publish arrays that are in the middle of an
7047                  * unsupported migration
7048                  */
7049                 if (dev->vol.migr_state &&
7050                     (migr_type(dev) == MIGR_STATE_CHANGE)) {
7051                         pr_err("cannot assemble volume '%.16s': unsupported migration in progress\n",
7052                                 dev->volume);
7053                         continue;
7054                 }
7055                 /* do not publish arrays that are not support by controller's
7056                  * OROM/EFI
7057                  */
7058
7059                 this = xmalloc(sizeof(*this));
7060
7061                 super->current_vol = i;
7062                 getinfo_super_imsm_volume(st, this, NULL);
7063                 this->next = rest;
7064 #ifndef MDASSEMBLE
7065                 chunk = __le16_to_cpu(map->blocks_per_strip) >> 1;
7066                 /* mdadm does not support all metadata features- set the bit in all arrays state */
7067                 if (!validate_geometry_imsm_orom(super,
7068                                                  get_imsm_raid_level(map), /* RAID level */
7069                                                  imsm_level_to_layout(get_imsm_raid_level(map)),
7070                                                  map->num_members, /* raid disks */
7071                                                  &chunk, join_u32(dev->size_low, dev->size_high),
7072                                                  1 /* verbose */)) {
7073                         pr_err("IMSM RAID geometry validation failed.  Array %s activation is blocked.\n",
7074                                 dev->volume);
7075                         this->array.state |=
7076                           (1<<MD_SB_BLOCK_CONTAINER_RESHAPE) |
7077                           (1<<MD_SB_BLOCK_VOLUME);
7078                 }
7079 #endif
7080
7081                 /* if array has bad blocks, set suitable bit in all arrays state */
7082                 if (sb_errors)
7083                         this->array.state |=
7084                           (1<<MD_SB_BLOCK_CONTAINER_RESHAPE) |
7085                           (1<<MD_SB_BLOCK_VOLUME);
7086
7087                 for (slot = 0 ; slot <  map->num_members; slot++) {
7088                         unsigned long long recovery_start;
7089                         struct mdinfo *info_d;
7090                         struct dl *d;
7091                         int idx;
7092                         int skip;
7093                         __u32 ord;
7094
7095                         skip = 0;
7096                         idx = get_imsm_disk_idx(dev, slot, MAP_0);
7097                         ord = get_imsm_ord_tbl_ent(dev, slot, MAP_X);
7098                         for (d = super->disks; d ; d = d->next)
7099                                 if (d->index == idx)
7100                                         break;
7101
7102                         recovery_start = MaxSector;
7103                         if (d == NULL)
7104                                 skip = 1;
7105                         if (d && is_failed(&d->disk))
7106                                 skip = 1;
7107                         if (ord & IMSM_ORD_REBUILD)
7108                                 recovery_start = 0;
7109
7110                         /*
7111                          * if we skip some disks the array will be assmebled degraded;
7112                          * reset resync start to avoid a dirty-degraded
7113                          * situation when performing the intial sync
7114                          *
7115                          * FIXME handle dirty degraded
7116                          */
7117                         if ((skip || recovery_start == 0) && !dev->vol.dirty)
7118                                 this->resync_start = MaxSector;
7119                         if (skip)
7120                                 continue;
7121
7122                         info_d = xcalloc(1, sizeof(*info_d));
7123                         info_d->next = this->devs;
7124                         this->devs = info_d;
7125
7126                         info_d->disk.number = d->index;
7127                         info_d->disk.major = d->major;
7128                         info_d->disk.minor = d->minor;
7129                         info_d->disk.raid_disk = slot;
7130                         info_d->recovery_start = recovery_start;
7131                         if (map2) {
7132                                 if (slot < map2->num_members)
7133                                         info_d->disk.state = (1 << MD_DISK_ACTIVE);
7134                                 else
7135                                         this->array.spare_disks++;
7136                         } else {
7137                                 if (slot < map->num_members)
7138                                         info_d->disk.state = (1 << MD_DISK_ACTIVE);
7139                                 else
7140                                         this->array.spare_disks++;
7141                         }
7142                         if (info_d->recovery_start == MaxSector)
7143                                 this->array.working_disks++;
7144
7145                         info_d->events = __le32_to_cpu(mpb->generation_num);
7146                         info_d->data_offset = pba_of_lba0(map);
7147
7148                         if (map->raid_level == 5) {
7149                                 info_d->component_size =
7150                                                 num_data_stripes(map) *
7151                                                 map->blocks_per_strip;
7152                         } else {
7153                                 info_d->component_size = blocks_per_member(map);
7154                         }
7155                 }
7156                 /* now that the disk list is up-to-date fixup recovery_start */
7157                 update_recovery_start(super, dev, this);
7158                 this->array.spare_disks += spare_disks;
7159
7160 #ifndef MDASSEMBLE
7161                 /* check for reshape */
7162                 if (this->reshape_active == 1)
7163                         recover_backup_imsm(st, this);
7164 #endif
7165                 rest = this;
7166         }
7167
7168         return rest;
7169 }
7170
7171 static __u8 imsm_check_degraded(struct intel_super *super, struct imsm_dev *dev,
7172                                 int failed, int look_in_map)
7173 {
7174         struct imsm_map *map;
7175
7176         map = get_imsm_map(dev, look_in_map);
7177
7178         if (!failed)
7179                 return map->map_state == IMSM_T_STATE_UNINITIALIZED ?
7180                         IMSM_T_STATE_UNINITIALIZED : IMSM_T_STATE_NORMAL;
7181
7182         switch (get_imsm_raid_level(map)) {
7183         case 0:
7184                 return IMSM_T_STATE_FAILED;
7185                 break;
7186         case 1:
7187                 if (failed < map->num_members)
7188                         return IMSM_T_STATE_DEGRADED;
7189                 else
7190                         return IMSM_T_STATE_FAILED;
7191                 break;
7192         case 10:
7193         {
7194                 /**
7195                  * check to see if any mirrors have failed, otherwise we
7196                  * are degraded.  Even numbered slots are mirrored on
7197                  * slot+1
7198                  */
7199                 int i;
7200                 /* gcc -Os complains that this is unused */
7201                 int insync = insync;
7202
7203                 for (i = 0; i < map->num_members; i++) {
7204                         __u32 ord = get_imsm_ord_tbl_ent(dev, i, MAP_X);
7205                         int idx = ord_to_idx(ord);
7206                         struct imsm_disk *disk;
7207
7208                         /* reset the potential in-sync count on even-numbered
7209                          * slots.  num_copies is always 2 for imsm raid10
7210                          */
7211                         if ((i & 1) == 0)
7212                                 insync = 2;
7213
7214                         disk = get_imsm_disk(super, idx);
7215                         if (!disk || is_failed(disk) || ord & IMSM_ORD_REBUILD)
7216                                 insync--;
7217
7218                         /* no in-sync disks left in this mirror the
7219                          * array has failed
7220                          */
7221                         if (insync == 0)
7222                                 return IMSM_T_STATE_FAILED;
7223                 }
7224
7225                 return IMSM_T_STATE_DEGRADED;
7226         }
7227         case 5:
7228                 if (failed < 2)
7229                         return IMSM_T_STATE_DEGRADED;
7230                 else
7231                         return IMSM_T_STATE_FAILED;
7232                 break;
7233         default:
7234                 break;
7235         }
7236
7237         return map->map_state;
7238 }
7239
7240 static int imsm_count_failed(struct intel_super *super, struct imsm_dev *dev,
7241                              int look_in_map)
7242 {
7243         int i;
7244         int failed = 0;
7245         struct imsm_disk *disk;
7246         struct imsm_map *map = get_imsm_map(dev, MAP_0);
7247         struct imsm_map *prev = get_imsm_map(dev, MAP_1);
7248         struct imsm_map *map_for_loop;
7249         __u32 ord;
7250         int idx;
7251         int idx_1;
7252
7253         /* at the beginning of migration we set IMSM_ORD_REBUILD on
7254          * disks that are being rebuilt.  New failures are recorded to
7255          * map[0].  So we look through all the disks we started with and
7256          * see if any failures are still present, or if any new ones
7257          * have arrived
7258          */
7259         map_for_loop = map;
7260         if (prev && (map->num_members < prev->num_members))
7261                 map_for_loop = prev;
7262
7263         for (i = 0; i < map_for_loop->num_members; i++) {
7264                 idx_1 = -255;
7265                 /* when MAP_X is passed both maps failures are counted
7266                  */
7267                 if (prev &&
7268                     (look_in_map == MAP_1 || look_in_map == MAP_X) &&
7269                     i < prev->num_members) {
7270                         ord = __le32_to_cpu(prev->disk_ord_tbl[i]);
7271                         idx_1 = ord_to_idx(ord);
7272
7273                         disk = get_imsm_disk(super, idx_1);
7274                         if (!disk || is_failed(disk) || ord & IMSM_ORD_REBUILD)
7275                                 failed++;
7276                 }
7277                 if ((look_in_map == MAP_0 || look_in_map == MAP_X) &&
7278                     i < map->num_members) {
7279                         ord = __le32_to_cpu(map->disk_ord_tbl[i]);
7280                         idx = ord_to_idx(ord);
7281
7282                         if (idx != idx_1) {
7283                                 disk = get_imsm_disk(super, idx);
7284                                 if (!disk || is_failed(disk) ||
7285                                     ord & IMSM_ORD_REBUILD)
7286                                         failed++;
7287                         }
7288                 }
7289         }
7290
7291         return failed;
7292 }
7293
7294 #ifndef MDASSEMBLE
7295 static int imsm_open_new(struct supertype *c, struct active_array *a,
7296                          char *inst)
7297 {
7298         struct intel_super *super = c->sb;
7299         struct imsm_super *mpb = super->anchor;
7300         struct imsm_update_prealloc_bb_mem u;
7301
7302         if (atoi(inst) >= mpb->num_raid_devs) {
7303                 pr_err("subarry index %d, out of range\n", atoi(inst));
7304                 return -ENODEV;
7305         }
7306
7307         dprintf("imsm: open_new %s\n", inst);
7308         a->info.container_member = atoi(inst);
7309
7310         u.type = update_prealloc_badblocks_mem;
7311         imsm_update_metadata_locally(c, &u, sizeof(u));
7312
7313         return 0;
7314 }
7315
7316 static int is_resyncing(struct imsm_dev *dev)
7317 {
7318         struct imsm_map *migr_map;
7319
7320         if (!dev->vol.migr_state)
7321                 return 0;
7322
7323         if (migr_type(dev) == MIGR_INIT ||
7324             migr_type(dev) == MIGR_REPAIR)
7325                 return 1;
7326
7327         if (migr_type(dev) == MIGR_GEN_MIGR)
7328                 return 0;
7329
7330         migr_map = get_imsm_map(dev, MAP_1);
7331
7332         if (migr_map->map_state == IMSM_T_STATE_NORMAL &&
7333             dev->vol.migr_type != MIGR_GEN_MIGR)
7334                 return 1;
7335         else
7336                 return 0;
7337 }
7338
7339 /* return true if we recorded new information */
7340 static int mark_failure(struct imsm_dev *dev, struct imsm_disk *disk, int idx)
7341 {
7342         __u32 ord;
7343         int slot;
7344         struct imsm_map *map;
7345         char buf[MAX_RAID_SERIAL_LEN+3];
7346         unsigned int len, shift = 0;
7347
7348         /* new failures are always set in map[0] */
7349         map = get_imsm_map(dev, MAP_0);
7350
7351         slot = get_imsm_disk_slot(map, idx);
7352         if (slot < 0)
7353                 return 0;
7354
7355         ord = __le32_to_cpu(map->disk_ord_tbl[slot]);
7356         if (is_failed(disk) && (ord & IMSM_ORD_REBUILD))
7357                 return 0;
7358
7359         memcpy(buf, disk->serial, MAX_RAID_SERIAL_LEN);
7360         buf[MAX_RAID_SERIAL_LEN] = '\000';
7361         strcat(buf, ":0");
7362         if ((len = strlen(buf)) >= MAX_RAID_SERIAL_LEN)
7363                 shift = len - MAX_RAID_SERIAL_LEN + 1;
7364         strncpy((char *)disk->serial, &buf[shift], MAX_RAID_SERIAL_LEN);
7365
7366         disk->status |= FAILED_DISK;
7367         set_imsm_ord_tbl_ent(map, slot, idx | IMSM_ORD_REBUILD);
7368         /* mark failures in second map if second map exists and this disk
7369          * in this slot.
7370          * This is valid for migration, initialization and rebuild
7371          */
7372         if (dev->vol.migr_state) {
7373                 struct imsm_map *map2 = get_imsm_map(dev, MAP_1);
7374                 int slot2 = get_imsm_disk_slot(map2, idx);
7375
7376                 if (slot2 < map2->num_members && slot2 >= 0)
7377                         set_imsm_ord_tbl_ent(map2, slot2,
7378                                              idx | IMSM_ORD_REBUILD);
7379         }
7380         if (map->failed_disk_num == 0xff)
7381                 map->failed_disk_num = slot;
7382         return 1;
7383 }
7384
7385 static void mark_missing(struct imsm_dev *dev, struct imsm_disk *disk, int idx)
7386 {
7387         mark_failure(dev, disk, idx);
7388
7389         if (disk->scsi_id == __cpu_to_le32(~(__u32)0))
7390                 return;
7391
7392         disk->scsi_id = __cpu_to_le32(~(__u32)0);
7393         memmove(&disk->serial[0], &disk->serial[1], MAX_RAID_SERIAL_LEN - 1);
7394 }
7395
7396 static void handle_missing(struct intel_super *super, struct imsm_dev *dev)
7397 {
7398         struct dl *dl;
7399
7400         if (!super->missing)
7401                 return;
7402
7403         /* When orom adds replacement for missing disk it does
7404          * not remove entry of missing disk, but just updates map with
7405          * new added disk. So it is not enough just to test if there is
7406          * any missing disk, we have to look if there are any failed disks
7407          * in map to stop migration */
7408
7409         dprintf("imsm: mark missing\n");
7410         /* end process for initialization and rebuild only
7411          */
7412         if (is_gen_migration(dev) == 0) {
7413                 __u8 map_state;
7414                 int failed;
7415
7416                 failed = imsm_count_failed(super, dev, MAP_0);
7417                 map_state = imsm_check_degraded(super, dev, failed, MAP_0);
7418
7419                 if (failed)
7420                         end_migration(dev, super, map_state);
7421         }
7422         for (dl = super->missing; dl; dl = dl->next)
7423                 mark_missing(dev, &dl->disk, dl->index);
7424         super->updates_pending++;
7425 }
7426
7427 static unsigned long long imsm_set_array_size(struct imsm_dev *dev,
7428                                               long long new_size)
7429 {
7430         int used_disks = imsm_num_data_members(dev, MAP_0);
7431         unsigned long long array_blocks;
7432         struct imsm_map *map;
7433
7434         if (used_disks == 0) {
7435                 /* when problems occures
7436                  * return current array_blocks value
7437                  */
7438                 array_blocks = __le32_to_cpu(dev->size_high);
7439                 array_blocks = array_blocks << 32;
7440                 array_blocks += __le32_to_cpu(dev->size_low);
7441
7442                 return array_blocks;
7443         }
7444
7445         /* set array size in metadata
7446          */
7447         if (new_size <= 0) {
7448                 /* OLCE size change is caused by added disks
7449                  */
7450                 map = get_imsm_map(dev, MAP_0);
7451                 array_blocks = blocks_per_member(map) * used_disks;
7452         } else {
7453                 /* Online Volume Size Change
7454                  * Using  available free space
7455                  */
7456                 array_blocks = new_size;
7457         }
7458
7459         /* round array size down to closest MB
7460          */
7461         array_blocks = (array_blocks >> SECT_PER_MB_SHIFT) << SECT_PER_MB_SHIFT;
7462         dev->size_low = __cpu_to_le32((__u32)array_blocks);
7463         dev->size_high = __cpu_to_le32((__u32)(array_blocks >> 32));
7464
7465         return array_blocks;
7466 }
7467
7468 static void imsm_set_disk(struct active_array *a, int n, int state);
7469
7470 static void imsm_progress_container_reshape(struct intel_super *super)
7471 {
7472         /* if no device has a migr_state, but some device has a
7473          * different number of members than the previous device, start
7474          * changing the number of devices in this device to match
7475          * previous.
7476          */
7477         struct imsm_super *mpb = super->anchor;
7478         int prev_disks = -1;
7479         int i;
7480         int copy_map_size;
7481
7482         for (i = 0; i < mpb->num_raid_devs; i++) {
7483                 struct imsm_dev *dev = get_imsm_dev(super, i);
7484                 struct imsm_map *map = get_imsm_map(dev, MAP_0);
7485                 struct imsm_map *map2;
7486                 int prev_num_members;
7487
7488                 if (dev->vol.migr_state)
7489                         return;
7490
7491                 if (prev_disks == -1)
7492                         prev_disks = map->num_members;
7493                 if (prev_disks == map->num_members)
7494                         continue;
7495
7496                 /* OK, this array needs to enter reshape mode.
7497                  * i.e it needs a migr_state
7498                  */
7499
7500                 copy_map_size = sizeof_imsm_map(map);
7501                 prev_num_members = map->num_members;
7502                 map->num_members = prev_disks;
7503                 dev->vol.migr_state = 1;
7504                 dev->vol.curr_migr_unit = 0;
7505                 set_migr_type(dev, MIGR_GEN_MIGR);
7506                 for (i = prev_num_members;
7507                      i < map->num_members; i++)
7508                         set_imsm_ord_tbl_ent(map, i, i);
7509                 map2 = get_imsm_map(dev, MAP_1);
7510                 /* Copy the current map */
7511                 memcpy(map2, map, copy_map_size);
7512                 map2->num_members = prev_num_members;
7513
7514                 imsm_set_array_size(dev, -1);
7515                 super->clean_migration_record_by_mdmon = 1;
7516                 super->updates_pending++;
7517         }
7518 }
7519
7520 /* Handle dirty -> clean transititions, resync and reshape.  Degraded and rebuild
7521  * states are handled in imsm_set_disk() with one exception, when a
7522  * resync is stopped due to a new failure this routine will set the
7523  * 'degraded' state for the array.
7524  */
7525 static int imsm_set_array_state(struct active_array *a, int consistent)
7526 {
7527         int inst = a->info.container_member;
7528         struct intel_super *super = a->container->sb;
7529         struct imsm_dev *dev = get_imsm_dev(super, inst);
7530         struct imsm_map *map = get_imsm_map(dev, MAP_0);
7531         int failed = imsm_count_failed(super, dev, MAP_0);
7532         __u8 map_state = imsm_check_degraded(super, dev, failed, MAP_0);
7533         __u32 blocks_per_unit;
7534
7535         if (dev->vol.migr_state &&
7536             dev->vol.migr_type  == MIGR_GEN_MIGR) {
7537                 /* array state change is blocked due to reshape action
7538                  * We might need to
7539                  * - abort the reshape (if last_checkpoint is 0 and action!= reshape)
7540                  * - finish the reshape (if last_checkpoint is big and action != reshape)
7541                  * - update curr_migr_unit
7542                  */
7543                 if (a->curr_action == reshape) {
7544                         /* still reshaping, maybe update curr_migr_unit */
7545                         goto mark_checkpoint;
7546                 } else {
7547                         if (a->last_checkpoint == 0 && a->prev_action == reshape) {
7548                                 /* for some reason we aborted the reshape.
7549                                  *
7550                                  * disable automatic metadata rollback
7551                                  * user action is required to recover process
7552                                  */
7553                                 if (0) {
7554                                         struct imsm_map *map2 =
7555                                                 get_imsm_map(dev, MAP_1);
7556                                         dev->vol.migr_state = 0;
7557                                         set_migr_type(dev, 0);
7558                                         dev->vol.curr_migr_unit = 0;
7559                                         memcpy(map, map2,
7560                                                sizeof_imsm_map(map2));
7561                                         super->updates_pending++;
7562                                 }
7563                         }
7564                         if (a->last_checkpoint >= a->info.component_size) {
7565                                 unsigned long long array_blocks;
7566                                 int used_disks;
7567                                 struct mdinfo *mdi;
7568
7569                                 used_disks = imsm_num_data_members(dev, MAP_0);
7570                                 if (used_disks > 0) {
7571                                         array_blocks =
7572                                                 blocks_per_member(map) *
7573                                                 used_disks;
7574                                         /* round array size down to closest MB
7575                                          */
7576                                         array_blocks = (array_blocks
7577                                                         >> SECT_PER_MB_SHIFT)
7578                                                 << SECT_PER_MB_SHIFT;
7579                                         a->info.custom_array_size = array_blocks;
7580                                         /* encourage manager to update array
7581                                          * size
7582                                          */
7583
7584                                         a->check_reshape = 1;
7585                                 }
7586                                 /* finalize online capacity expansion/reshape */
7587                                 for (mdi = a->info.devs; mdi; mdi = mdi->next)
7588                                         imsm_set_disk(a,
7589                                                       mdi->disk.raid_disk,
7590                                                       mdi->curr_state);
7591
7592                                 imsm_progress_container_reshape(super);
7593                         }
7594                 }
7595         }
7596
7597         /* before we activate this array handle any missing disks */
7598         if (consistent == 2)
7599                 handle_missing(super, dev);
7600
7601         if (consistent == 2 &&
7602             (!is_resync_complete(&a->info) ||
7603              map_state != IMSM_T_STATE_NORMAL ||
7604              dev->vol.migr_state))
7605                 consistent = 0;
7606
7607         if (is_resync_complete(&a->info)) {
7608                 /* complete intialization / resync,
7609                  * recovery and interrupted recovery is completed in
7610                  * ->set_disk
7611                  */
7612                 if (is_resyncing(dev)) {
7613                         dprintf("imsm: mark resync done\n");
7614                         end_migration(dev, super, map_state);
7615                         super->updates_pending++;
7616                         a->last_checkpoint = 0;
7617                 }
7618         } else if ((!is_resyncing(dev) && !failed) &&
7619                    (imsm_reshape_blocks_arrays_changes(super) == 0)) {
7620                 /* mark the start of the init process if nothing is failed */
7621                 dprintf("imsm: mark resync start\n");
7622                 if (map->map_state == IMSM_T_STATE_UNINITIALIZED)
7623                         migrate(dev, super, IMSM_T_STATE_NORMAL, MIGR_INIT);
7624                 else
7625                         migrate(dev, super, IMSM_T_STATE_NORMAL, MIGR_REPAIR);
7626                 super->updates_pending++;
7627         }
7628
7629 mark_checkpoint:
7630         /* skip checkpointing for general migration,
7631          * it is controlled in mdadm
7632          */
7633         if (is_gen_migration(dev))
7634                 goto skip_mark_checkpoint;
7635
7636         /* check if we can update curr_migr_unit from resync_start, recovery_start */
7637         blocks_per_unit = blocks_per_migr_unit(super, dev);
7638         if (blocks_per_unit) {
7639                 __u32 units32;
7640                 __u64 units;
7641
7642                 units = a->last_checkpoint / blocks_per_unit;
7643                 units32 = units;
7644
7645                 /* check that we did not overflow 32-bits, and that
7646                  * curr_migr_unit needs updating
7647                  */
7648                 if (units32 == units &&
7649                     units32 != 0 &&
7650                     __le32_to_cpu(dev->vol.curr_migr_unit) != units32) {
7651                         dprintf("imsm: mark checkpoint (%u)\n", units32);
7652                         dev->vol.curr_migr_unit = __cpu_to_le32(units32);
7653                         super->updates_pending++;
7654                 }
7655         }
7656
7657 skip_mark_checkpoint:
7658         /* mark dirty / clean */
7659         if (dev->vol.dirty != !consistent) {
7660                 dprintf("imsm: mark '%s'\n", consistent ? "clean" : "dirty");
7661                 if (consistent)
7662                         dev->vol.dirty = 0;
7663                 else
7664                         dev->vol.dirty = 1;
7665                 super->updates_pending++;
7666         }
7667
7668         return consistent;
7669 }
7670
7671 static void imsm_set_disk(struct active_array *a, int n, int state)
7672 {
7673         int inst = a->info.container_member;
7674         struct intel_super *super = a->container->sb;
7675         struct imsm_dev *dev = get_imsm_dev(super, inst);
7676         struct imsm_map *map = get_imsm_map(dev, MAP_0);
7677         struct imsm_disk *disk;
7678         struct mdinfo *mdi;
7679         int recovery_not_finished = 0;
7680         int failed;
7681         __u32 ord;
7682         __u8 map_state;
7683
7684         if (n > map->num_members)
7685                 pr_err("imsm: set_disk %d out of range 0..%d\n",
7686                         n, map->num_members - 1);
7687
7688         if (n < 0)
7689                 return;
7690
7691         dprintf("imsm: set_disk %d:%x\n", n, state);
7692
7693         ord = get_imsm_ord_tbl_ent(dev, n, MAP_0);
7694         disk = get_imsm_disk(super, ord_to_idx(ord));
7695
7696         /* check for new failures */
7697         if (state & DS_FAULTY) {
7698                 if (mark_failure(dev, disk, ord_to_idx(ord)))
7699                         super->updates_pending++;
7700         }
7701
7702         /* check if in_sync */
7703         if (state & DS_INSYNC && ord & IMSM_ORD_REBUILD && is_rebuilding(dev)) {
7704                 struct imsm_map *migr_map = get_imsm_map(dev, MAP_1);
7705
7706                 set_imsm_ord_tbl_ent(migr_map, n, ord_to_idx(ord));
7707                 super->updates_pending++;
7708         }
7709
7710         failed = imsm_count_failed(super, dev, MAP_0);
7711         map_state = imsm_check_degraded(super, dev, failed, MAP_0);
7712
7713         /* check if recovery complete, newly degraded, or failed */
7714         dprintf("imsm: Detected transition to state ");
7715         switch (map_state) {
7716         case IMSM_T_STATE_NORMAL: /* transition to normal state */
7717                 dprintf("normal: ");
7718                 if (is_rebuilding(dev)) {
7719                         dprintf_cont("while rebuilding");
7720                         /* check if recovery is really finished */
7721                         for (mdi = a->info.devs; mdi ; mdi = mdi->next)
7722                                 if (mdi->recovery_start != MaxSector) {
7723                                         recovery_not_finished = 1;
7724                                         break;
7725                                 }
7726                         if (recovery_not_finished) {
7727                                 dprintf_cont("\n");
7728                                 dprintf("Rebuild has not finished yet, state not changed");
7729                                 if (a->last_checkpoint < mdi->recovery_start) {
7730                                         a->last_checkpoint = mdi->recovery_start;
7731                                         super->updates_pending++;
7732                                 }
7733                                 break;
7734                         }
7735                         end_migration(dev, super, map_state);
7736                         map = get_imsm_map(dev, MAP_0);
7737                         map->failed_disk_num = ~0;
7738                         super->updates_pending++;
7739                         a->last_checkpoint = 0;
7740                         break;
7741                 }
7742                 if (is_gen_migration(dev)) {
7743                         dprintf_cont("while general migration");
7744                         if (a->last_checkpoint >= a->info.component_size)
7745                                 end_migration(dev, super, map_state);
7746                         else
7747                                 map->map_state = map_state;
7748                         map = get_imsm_map(dev, MAP_0);
7749                         map->failed_disk_num = ~0;
7750                         super->updates_pending++;
7751                         break;
7752                 }
7753         break;
7754         case IMSM_T_STATE_DEGRADED: /* transition to degraded state */
7755                 dprintf_cont("degraded: ");
7756                 if (map->map_state != map_state && !dev->vol.migr_state) {
7757                         dprintf_cont("mark degraded");
7758                         map->map_state = map_state;
7759                         super->updates_pending++;
7760                         a->last_checkpoint = 0;
7761                         break;
7762                 }
7763                 if (is_rebuilding(dev)) {
7764                         dprintf_cont("while rebuilding.");
7765                         if (map->map_state != map_state)  {
7766                                 dprintf_cont(" Map state change");
7767                                 end_migration(dev, super, map_state);
7768                                 super->updates_pending++;
7769                         }
7770                         break;
7771                 }
7772                 if (is_gen_migration(dev)) {
7773                         dprintf_cont("while general migration");
7774                         if (a->last_checkpoint >= a->info.component_size)
7775                                 end_migration(dev, super, map_state);
7776                         else {
7777                                 map->map_state = map_state;
7778                                 manage_second_map(super, dev);
7779                         }
7780                         super->updates_pending++;
7781                         break;
7782                 }
7783                 if (is_initializing(dev)) {
7784                         dprintf_cont("while initialization.");
7785                         map->map_state = map_state;
7786                         super->updates_pending++;
7787                         break;
7788                 }
7789         break;
7790         case IMSM_T_STATE_FAILED: /* transition to failed state */
7791                 dprintf_cont("failed: ");
7792                 if (is_gen_migration(dev)) {
7793                         dprintf_cont("while general migration");
7794                         map->map_state = map_state;
7795                         super->updates_pending++;
7796                         break;
7797                 }
7798                 if (map->map_state != map_state) {
7799                         dprintf_cont("mark failed");
7800                         end_migration(dev, super, map_state);
7801                         super->updates_pending++;
7802                         a->last_checkpoint = 0;
7803                         break;
7804                 }
7805         break;
7806         default:
7807                 dprintf_cont("state %i\n", map_state);
7808         }
7809         dprintf_cont("\n");
7810 }
7811
7812 static int store_imsm_mpb(int fd, struct imsm_super *mpb)
7813 {
7814         void *buf = mpb;
7815         __u32 mpb_size = __le32_to_cpu(mpb->mpb_size);
7816         unsigned long long dsize;
7817         unsigned long long sectors;
7818         unsigned int sector_size;
7819
7820         get_dev_sector_size(fd, NULL, &sector_size);
7821         get_dev_size(fd, NULL, &dsize);
7822
7823         if (mpb_size > sector_size) {
7824                 /* -1 to account for anchor */
7825                 sectors = mpb_sectors(mpb, sector_size) - 1;
7826
7827                 /* write the extended mpb to the sectors preceeding the anchor */
7828                 if (lseek64(fd, dsize - (sector_size * (2 + sectors)),
7829                    SEEK_SET) < 0)
7830                         return 1;
7831
7832                 if ((unsigned long long)write(fd, buf + sector_size,
7833                    sector_size * sectors) != sector_size * sectors)
7834                         return 1;
7835         }
7836
7837         /* first block is stored on second to last sector of the disk */
7838         if (lseek64(fd, dsize - (sector_size * 2), SEEK_SET) < 0)
7839                 return 1;
7840
7841         if (write(fd, buf, sector_size) != sector_size)
7842                 return 1;
7843
7844         return 0;
7845 }
7846
7847 static void imsm_sync_metadata(struct supertype *container)
7848 {
7849         struct intel_super *super = container->sb;
7850
7851         dprintf("sync metadata: %d\n", super->updates_pending);
7852         if (!super->updates_pending)
7853                 return;
7854
7855         write_super_imsm(container, 0);
7856
7857         super->updates_pending = 0;
7858 }
7859
7860 static struct dl *imsm_readd(struct intel_super *super, int idx, struct active_array *a)
7861 {
7862         struct imsm_dev *dev = get_imsm_dev(super, a->info.container_member);
7863         int i = get_imsm_disk_idx(dev, idx, MAP_X);
7864         struct dl *dl;
7865
7866         for (dl = super->disks; dl; dl = dl->next)
7867                 if (dl->index == i)
7868                         break;
7869
7870         if (dl && is_failed(&dl->disk))
7871                 dl = NULL;
7872
7873         if (dl)
7874                 dprintf("found %x:%x\n", dl->major, dl->minor);
7875
7876         return dl;
7877 }
7878
7879 static struct dl *imsm_add_spare(struct intel_super *super, int slot,
7880                                  struct active_array *a, int activate_new,
7881                                  struct mdinfo *additional_test_list)
7882 {
7883         struct imsm_dev *dev = get_imsm_dev(super, a->info.container_member);
7884         int idx = get_imsm_disk_idx(dev, slot, MAP_X);
7885         struct imsm_super *mpb = super->anchor;
7886         struct imsm_map *map;
7887         unsigned long long pos;
7888         struct mdinfo *d;
7889         struct extent *ex;
7890         int i, j;
7891         int found;
7892         __u32 array_start = 0;
7893         __u32 array_end = 0;
7894         struct dl *dl;
7895         struct mdinfo *test_list;
7896
7897         for (dl = super->disks; dl; dl = dl->next) {
7898                 /* If in this array, skip */
7899                 for (d = a->info.devs ; d ; d = d->next)
7900                         if (d->state_fd >= 0 &&
7901                             d->disk.major == dl->major &&
7902                             d->disk.minor == dl->minor) {
7903                                 dprintf("%x:%x already in array\n",
7904                                         dl->major, dl->minor);
7905                                 break;
7906                         }
7907                 if (d)
7908                         continue;
7909                 test_list = additional_test_list;
7910                 while (test_list) {
7911                         if (test_list->disk.major == dl->major &&
7912                             test_list->disk.minor == dl->minor) {
7913                                 dprintf("%x:%x already in additional test list\n",
7914                                         dl->major, dl->minor);
7915                                 break;
7916                         }
7917                         test_list = test_list->next;
7918                 }
7919                 if (test_list)
7920                         continue;
7921
7922                 /* skip in use or failed drives */
7923                 if (is_failed(&dl->disk) || idx == dl->index ||
7924                     dl->index == -2) {
7925                         dprintf("%x:%x status (failed: %d index: %d)\n",
7926                                 dl->major, dl->minor, is_failed(&dl->disk), idx);
7927                         continue;
7928                 }
7929
7930                 /* skip pure spares when we are looking for partially
7931                  * assimilated drives
7932                  */
7933                 if (dl->index == -1 && !activate_new)
7934                         continue;
7935
7936                 /* Does this unused device have the requisite free space?
7937                  * It needs to be able to cover all member volumes
7938                  */
7939                 ex = get_extents(super, dl);
7940                 if (!ex) {
7941                         dprintf("cannot get extents\n");
7942                         continue;
7943                 }
7944                 for (i = 0; i < mpb->num_raid_devs; i++) {
7945                         dev = get_imsm_dev(super, i);
7946                         map = get_imsm_map(dev, MAP_0);
7947
7948                         /* check if this disk is already a member of
7949                          * this array
7950                          */
7951                         if (get_imsm_disk_slot(map, dl->index) >= 0)
7952                                 continue;
7953
7954                         found = 0;
7955                         j = 0;
7956                         pos = 0;
7957                         array_start = pba_of_lba0(map);
7958                         array_end = array_start +
7959                                     blocks_per_member(map) - 1;
7960
7961                         do {
7962                                 /* check that we can start at pba_of_lba0 with
7963                                  * blocks_per_member of space
7964                                  */
7965                                 if (array_start >= pos && array_end < ex[j].start) {
7966                                         found = 1;
7967                                         break;
7968                                 }
7969                                 pos = ex[j].start + ex[j].size;
7970                                 j++;
7971                         } while (ex[j-1].size);
7972
7973                         if (!found)
7974                                 break;
7975                 }
7976
7977                 free(ex);
7978                 if (i < mpb->num_raid_devs) {
7979                         dprintf("%x:%x does not have %u to %u available\n",
7980                                 dl->major, dl->minor, array_start, array_end);
7981                         /* No room */
7982                         continue;
7983                 }
7984                 return dl;
7985         }
7986
7987         return dl;
7988 }
7989
7990 static int imsm_rebuild_allowed(struct supertype *cont, int dev_idx, int failed)
7991 {
7992         struct imsm_dev *dev2;
7993         struct imsm_map *map;
7994         struct dl *idisk;
7995         int slot;
7996         int idx;
7997         __u8 state;
7998
7999         dev2 = get_imsm_dev(cont->sb, dev_idx);
8000         if (dev2) {
8001                 state = imsm_check_degraded(cont->sb, dev2, failed, MAP_0);
8002                 if (state == IMSM_T_STATE_FAILED) {
8003                         map = get_imsm_map(dev2, MAP_0);
8004                         if (!map)
8005                                 return 1;
8006                         for (slot = 0; slot < map->num_members; slot++) {
8007                                 /*
8008                                  * Check if failed disks are deleted from intel
8009                                  * disk list or are marked to be deleted
8010                                  */
8011                                 idx = get_imsm_disk_idx(dev2, slot, MAP_X);
8012                                 idisk = get_imsm_dl_disk(cont->sb, idx);
8013                                 /*
8014                                  * Do not rebuild the array if failed disks
8015                                  * from failed sub-array are not removed from
8016                                  * container.
8017                                  */
8018                                 if (idisk &&
8019                                     is_failed(&idisk->disk) &&
8020                                     (idisk->action != DISK_REMOVE))
8021                                         return 0;
8022                         }
8023                 }
8024         }
8025         return 1;
8026 }
8027
8028 static struct mdinfo *imsm_activate_spare(struct active_array *a,
8029                                           struct metadata_update **updates)
8030 {
8031         /**
8032          * Find a device with unused free space and use it to replace a
8033          * failed/vacant region in an array.  We replace failed regions one a
8034          * array at a time.  The result is that a new spare disk will be added
8035          * to the first failed array and after the monitor has finished
8036          * propagating failures the remainder will be consumed.
8037          *
8038          * FIXME add a capability for mdmon to request spares from another
8039          * container.
8040          */
8041
8042         struct intel_super *super = a->container->sb;
8043         int inst = a->info.container_member;
8044         struct imsm_dev *dev = get_imsm_dev(super, inst);
8045         struct imsm_map *map = get_imsm_map(dev, MAP_0);
8046         int failed = a->info.array.raid_disks;
8047         struct mdinfo *rv = NULL;
8048         struct mdinfo *d;
8049         struct mdinfo *di;
8050         struct metadata_update *mu;
8051         struct dl *dl;
8052         struct imsm_update_activate_spare *u;
8053         int num_spares = 0;
8054         int i;
8055         int allowed;
8056
8057         for (d = a->info.devs ; d ; d = d->next) {
8058                 if ((d->curr_state & DS_FAULTY) &&
8059                         d->state_fd >= 0)
8060                         /* wait for Removal to happen */
8061                         return NULL;
8062                 if (d->state_fd >= 0)
8063                         failed--;
8064         }
8065
8066         dprintf("imsm: activate spare: inst=%d failed=%d (%d) level=%d\n",
8067                 inst, failed, a->info.array.raid_disks, a->info.array.level);
8068
8069         if (imsm_reshape_blocks_arrays_changes(super))
8070                         return NULL;
8071
8072         /* Cannot activate another spare if rebuild is in progress already
8073          */
8074         if (is_rebuilding(dev)) {
8075                 dprintf("imsm: No spare activation allowed. Rebuild in progress already.\n");
8076                 return NULL;
8077         }
8078
8079         if (a->info.array.level == 4)
8080                 /* No repair for takeovered array
8081                  * imsm doesn't support raid4
8082                  */
8083                 return NULL;
8084
8085         if (imsm_check_degraded(super, dev, failed, MAP_0) !=
8086                         IMSM_T_STATE_DEGRADED)
8087                 return NULL;
8088
8089         if (get_imsm_map(dev, MAP_0)->map_state == IMSM_T_STATE_UNINITIALIZED) {
8090                 dprintf("imsm: No spare activation allowed. Volume is not initialized.\n");
8091                 return NULL;
8092         }
8093
8094         /*
8095          * If there are any failed disks check state of the other volume.
8096          * Block rebuild if the another one is failed until failed disks
8097          * are removed from container.
8098          */
8099         if (failed) {
8100                 dprintf("found failed disks in %.*s, check if there anotherfailed sub-array.\n",
8101                         MAX_RAID_SERIAL_LEN, dev->volume);
8102                 /* check if states of the other volumes allow for rebuild */
8103                 for (i = 0; i <  super->anchor->num_raid_devs; i++) {
8104                         if (i != inst) {
8105                                 allowed = imsm_rebuild_allowed(a->container,
8106                                                                i, failed);
8107                                 if (!allowed)
8108                                         return NULL;
8109                         }
8110                 }
8111         }
8112
8113         /* For each slot, if it is not working, find a spare */
8114         for (i = 0; i < a->info.array.raid_disks; i++) {
8115                 for (d = a->info.devs ; d ; d = d->next)
8116                         if (d->disk.raid_disk == i)
8117                                 break;
8118                 dprintf("found %d: %p %x\n", i, d, d?d->curr_state:0);
8119                 if (d && (d->state_fd >= 0))
8120                         continue;
8121
8122                 /*
8123                  * OK, this device needs recovery.  Try to re-add the
8124                  * previous occupant of this slot, if this fails see if
8125                  * we can continue the assimilation of a spare that was
8126                  * partially assimilated, finally try to activate a new
8127                  * spare.
8128                  */
8129                 dl = imsm_readd(super, i, a);
8130                 if (!dl)
8131                         dl = imsm_add_spare(super, i, a, 0, rv);
8132                 if (!dl)
8133                         dl = imsm_add_spare(super, i, a, 1, rv);
8134                 if (!dl)
8135                         continue;
8136
8137                 /* found a usable disk with enough space */
8138                 di = xcalloc(1, sizeof(*di));
8139
8140                 /* dl->index will be -1 in the case we are activating a
8141                  * pristine spare.  imsm_process_update() will create a
8142                  * new index in this case.  Once a disk is found to be
8143                  * failed in all member arrays it is kicked from the
8144                  * metadata
8145                  */
8146                 di->disk.number = dl->index;
8147
8148                 /* (ab)use di->devs to store a pointer to the device
8149                  * we chose
8150                  */
8151                 di->devs = (struct mdinfo *) dl;
8152
8153                 di->disk.raid_disk = i;
8154                 di->disk.major = dl->major;
8155                 di->disk.minor = dl->minor;
8156                 di->disk.state = 0;
8157                 di->recovery_start = 0;
8158                 di->data_offset = pba_of_lba0(map);
8159                 di->component_size = a->info.component_size;
8160                 di->container_member = inst;
8161                 super->random = random32();
8162                 di->next = rv;
8163                 rv = di;
8164                 num_spares++;
8165                 dprintf("%x:%x to be %d at %llu\n", dl->major, dl->minor,
8166                         i, di->data_offset);
8167         }
8168
8169         if (!rv)
8170                 /* No spares found */
8171                 return rv;
8172         /* Now 'rv' has a list of devices to return.
8173          * Create a metadata_update record to update the
8174          * disk_ord_tbl for the array
8175          */
8176         mu = xmalloc(sizeof(*mu));
8177         mu->buf = xcalloc(num_spares,
8178                           sizeof(struct imsm_update_activate_spare));
8179         mu->space = NULL;
8180         mu->space_list = NULL;
8181         mu->len = sizeof(struct imsm_update_activate_spare) * num_spares;
8182         mu->next = *updates;
8183         u = (struct imsm_update_activate_spare *) mu->buf;
8184
8185         for (di = rv ; di ; di = di->next) {
8186                 u->type = update_activate_spare;
8187                 u->dl = (struct dl *) di->devs;
8188                 di->devs = NULL;
8189                 u->slot = di->disk.raid_disk;
8190                 u->array = inst;
8191                 u->next = u + 1;
8192                 u++;
8193         }
8194         (u-1)->next = NULL;
8195         *updates = mu;
8196
8197         return rv;
8198 }
8199
8200 static int disks_overlap(struct intel_super *super, int idx, struct imsm_update_create_array *u)
8201 {
8202         struct imsm_dev *dev = get_imsm_dev(super, idx);
8203         struct imsm_map *map = get_imsm_map(dev, MAP_0);
8204         struct imsm_map *new_map = get_imsm_map(&u->dev, MAP_0);
8205         struct disk_info *inf = get_disk_info(u);
8206         struct imsm_disk *disk;
8207         int i;
8208         int j;
8209
8210         for (i = 0; i < map->num_members; i++) {
8211                 disk = get_imsm_disk(super, get_imsm_disk_idx(dev, i, MAP_X));
8212                 for (j = 0; j < new_map->num_members; j++)
8213                         if (serialcmp(disk->serial, inf[j].serial) == 0)
8214                                 return 1;
8215         }
8216
8217         return 0;
8218 }
8219
8220 static struct dl *get_disk_super(struct intel_super *super, int major, int minor)
8221 {
8222         struct dl *dl;
8223
8224         for (dl = super->disks; dl; dl = dl->next)
8225                 if (dl->major == major &&  dl->minor == minor)
8226                         return dl;
8227         return NULL;
8228 }
8229
8230 static int remove_disk_super(struct intel_super *super, int major, int minor)
8231 {
8232         struct dl *prev;
8233         struct dl *dl;
8234
8235         prev = NULL;
8236         for (dl = super->disks; dl; dl = dl->next) {
8237                 if (dl->major == major && dl->minor == minor) {
8238                         /* remove */
8239                         if (prev)
8240                                 prev->next = dl->next;
8241                         else
8242                                 super->disks = dl->next;
8243                         dl->next = NULL;
8244                         __free_imsm_disk(dl);
8245                         dprintf("removed %x:%x\n", major, minor);
8246                         break;
8247                 }
8248                 prev = dl;
8249         }
8250         return 0;
8251 }
8252
8253 static void imsm_delete(struct intel_super *super, struct dl **dlp, unsigned index);
8254
8255 static int add_remove_disk_update(struct intel_super *super)
8256 {
8257         int check_degraded = 0;
8258         struct dl *disk;
8259
8260         /* add/remove some spares to/from the metadata/contrainer */
8261         while (super->disk_mgmt_list) {
8262                 struct dl *disk_cfg;
8263
8264                 disk_cfg = super->disk_mgmt_list;
8265                 super->disk_mgmt_list = disk_cfg->next;
8266                 disk_cfg->next = NULL;
8267
8268                 if (disk_cfg->action == DISK_ADD) {
8269                         disk_cfg->next = super->disks;
8270                         super->disks = disk_cfg;
8271                         check_degraded = 1;
8272                         dprintf("added %x:%x\n",
8273                                 disk_cfg->major, disk_cfg->minor);
8274                 } else if (disk_cfg->action == DISK_REMOVE) {
8275                         dprintf("Disk remove action processed: %x.%x\n",
8276                                 disk_cfg->major, disk_cfg->minor);
8277                         disk = get_disk_super(super,
8278                                               disk_cfg->major,
8279                                               disk_cfg->minor);
8280                         if (disk) {
8281                                 /* store action status */
8282                                 disk->action = DISK_REMOVE;
8283                                 /* remove spare disks only */
8284                                 if (disk->index == -1) {
8285                                         remove_disk_super(super,
8286                                                           disk_cfg->major,
8287                                                           disk_cfg->minor);
8288                                 }
8289                         }
8290                         /* release allocate disk structure */
8291                         __free_imsm_disk(disk_cfg);
8292                 }
8293         }
8294         return check_degraded;
8295 }
8296
8297 static int apply_reshape_migration_update(struct imsm_update_reshape_migration *u,
8298                                                 struct intel_super *super,
8299                                                 void ***space_list)
8300 {
8301         struct intel_dev *id;
8302         void **tofree = NULL;
8303         int ret_val = 0;
8304
8305         dprintf("(enter)\n");
8306         if (u->subdev < 0 || u->subdev > 1) {
8307                 dprintf("imsm: Error: Wrong subdev: %i\n", u->subdev);
8308                 return ret_val;
8309         }
8310         if (space_list == NULL || *space_list == NULL) {
8311                 dprintf("imsm: Error: Memory is not allocated\n");
8312                 return ret_val;
8313         }
8314
8315         for (id = super->devlist ; id; id = id->next) {
8316                 if (id->index == (unsigned)u->subdev) {
8317                         struct imsm_dev *dev = get_imsm_dev(super, u->subdev);
8318                         struct imsm_map *map;
8319                         struct imsm_dev *new_dev =
8320                                 (struct imsm_dev *)*space_list;
8321                         struct imsm_map *migr_map = get_imsm_map(dev, MAP_1);
8322                         int to_state;
8323                         struct dl *new_disk;
8324
8325                         if (new_dev == NULL)
8326                                 return ret_val;
8327                         *space_list = **space_list;
8328                         memcpy(new_dev, dev, sizeof_imsm_dev(dev, 0));
8329                         map = get_imsm_map(new_dev, MAP_0);
8330                         if (migr_map) {
8331                                 dprintf("imsm: Error: migration in progress");
8332                                 return ret_val;
8333                         }
8334
8335                         to_state = map->map_state;
8336                         if ((u->new_level == 5) && (map->raid_level == 0)) {
8337                                 map->num_members++;
8338                                 /* this should not happen */
8339                                 if (u->new_disks[0] < 0) {
8340                                         map->failed_disk_num =
8341                                                 map->num_members - 1;
8342                                         to_state = IMSM_T_STATE_DEGRADED;
8343                                 } else
8344                                         to_state = IMSM_T_STATE_NORMAL;
8345                         }
8346                         migrate(new_dev, super, to_state, MIGR_GEN_MIGR);
8347                         if (u->new_level > -1)
8348                                 map->raid_level = u->new_level;
8349                         migr_map = get_imsm_map(new_dev, MAP_1);
8350                         if ((u->new_level == 5) &&
8351                             (migr_map->raid_level == 0)) {
8352                                 int ord = map->num_members - 1;
8353                                 migr_map->num_members--;
8354                                 if (u->new_disks[0] < 0)
8355                                         ord |= IMSM_ORD_REBUILD;
8356                                 set_imsm_ord_tbl_ent(map,
8357                                                      map->num_members - 1,
8358                                                      ord);
8359                         }
8360                         id->dev = new_dev;
8361                         tofree = (void **)dev;
8362
8363                         /* update chunk size
8364                          */
8365                         if (u->new_chunksize > 0) {
8366                                 unsigned long long num_data_stripes;
8367                                 int used_disks =
8368                                         imsm_num_data_members(dev, MAP_0);
8369
8370                                 if (used_disks == 0)
8371                                         return ret_val;
8372
8373                                 map->blocks_per_strip =
8374                                         __cpu_to_le16(u->new_chunksize * 2);
8375                                 num_data_stripes =
8376                                         (join_u32(dev->size_low, dev->size_high)
8377                                         / used_disks);
8378                                 num_data_stripes /= map->blocks_per_strip;
8379                                 num_data_stripes /= map->num_domains;
8380                                 set_num_data_stripes(map, num_data_stripes);
8381                         }
8382
8383                         /* add disk
8384                          */
8385                         if (u->new_level != 5 || migr_map->raid_level != 0 ||
8386                             migr_map->raid_level == map->raid_level)
8387                                 goto skip_disk_add;
8388
8389                         if (u->new_disks[0] >= 0) {
8390                                 /* use passes spare
8391                                  */
8392                                 new_disk = get_disk_super(super,
8393                                                         major(u->new_disks[0]),
8394                                                         minor(u->new_disks[0]));
8395                                 dprintf("imsm: new disk for reshape is: %i:%i (%p, index = %i)\n",
8396                                         major(u->new_disks[0]),
8397                                         minor(u->new_disks[0]),
8398                                         new_disk, new_disk->index);
8399                                 if (new_disk == NULL)
8400                                         goto error_disk_add;
8401
8402                                 new_disk->index = map->num_members - 1;
8403                                 /* slot to fill in autolayout
8404                                  */
8405                                 new_disk->raiddisk = new_disk->index;
8406                                 new_disk->disk.status |= CONFIGURED_DISK;
8407                                 new_disk->disk.status &= ~SPARE_DISK;
8408                         } else
8409                                 goto error_disk_add;
8410
8411 skip_disk_add:
8412                         *tofree = *space_list;
8413                         /* calculate new size
8414                          */
8415                         imsm_set_array_size(new_dev, -1);
8416
8417                         ret_val = 1;
8418                 }
8419         }
8420
8421         if (tofree)
8422                 *space_list = tofree;
8423         return ret_val;
8424
8425 error_disk_add:
8426         dprintf("Error: imsm: Cannot find disk.\n");
8427         return ret_val;
8428 }
8429
8430 static int apply_size_change_update(struct imsm_update_size_change *u,
8431                 struct intel_super *super)
8432 {
8433         struct intel_dev *id;
8434         int ret_val = 0;
8435
8436         dprintf("(enter)\n");
8437         if (u->subdev < 0 || u->subdev > 1) {
8438                 dprintf("imsm: Error: Wrong subdev: %i\n", u->subdev);
8439                 return ret_val;
8440         }
8441
8442         for (id = super->devlist ; id; id = id->next) {
8443                 if (id->index == (unsigned)u->subdev) {
8444                         struct imsm_dev *dev = get_imsm_dev(super, u->subdev);
8445                         struct imsm_map *map = get_imsm_map(dev, MAP_0);
8446                         int used_disks = imsm_num_data_members(dev, MAP_0);
8447                         unsigned long long blocks_per_member;
8448                         unsigned long long num_data_stripes;
8449
8450                         /* calculate new size
8451                          */
8452                         blocks_per_member = u->new_size / used_disks;
8453                         num_data_stripes = blocks_per_member /
8454                                            map->blocks_per_strip;
8455                         num_data_stripes /= map->num_domains;
8456                         dprintf("(size: %llu, blocks per member: %llu, num_data_stipes: %llu)\n",
8457                                 u->new_size, blocks_per_member,
8458                                 num_data_stripes);
8459                         set_blocks_per_member(map, blocks_per_member);
8460                         set_num_data_stripes(map, num_data_stripes);
8461                         imsm_set_array_size(dev, u->new_size);
8462
8463                         ret_val = 1;
8464                         break;
8465                 }
8466         }
8467
8468         return ret_val;
8469 }
8470
8471 static int apply_update_activate_spare(struct imsm_update_activate_spare *u,
8472                                        struct intel_super *super,
8473                                        struct active_array *active_array)
8474 {
8475         struct imsm_super *mpb = super->anchor;
8476         struct imsm_dev *dev = get_imsm_dev(super, u->array);
8477         struct imsm_map *map = get_imsm_map(dev, MAP_0);
8478         struct imsm_map *migr_map;
8479         struct active_array *a;
8480         struct imsm_disk *disk;
8481         __u8 to_state;
8482         struct dl *dl;
8483         unsigned int found;
8484         int failed;
8485         int victim;
8486         int i;
8487         int second_map_created = 0;
8488
8489         for (; u; u = u->next) {
8490                 victim = get_imsm_disk_idx(dev, u->slot, MAP_X);
8491
8492                 if (victim < 0)
8493                         return 0;
8494
8495                 for (dl = super->disks; dl; dl = dl->next)
8496                         if (dl == u->dl)
8497                                 break;
8498
8499                 if (!dl) {
8500                         pr_err("error: imsm_activate_spare passed an unknown disk (index: %d)\n",
8501                                 u->dl->index);
8502                         return 0;
8503                 }
8504
8505                 /* count failures (excluding rebuilds and the victim)
8506                  * to determine map[0] state
8507                  */
8508                 failed = 0;
8509                 for (i = 0; i < map->num_members; i++) {
8510                         if (i == u->slot)
8511                                 continue;
8512                         disk = get_imsm_disk(super,
8513                                              get_imsm_disk_idx(dev, i, MAP_X));
8514                         if (!disk || is_failed(disk))
8515                                 failed++;
8516                 }
8517
8518                 /* adding a pristine spare, assign a new index */
8519                 if (dl->index < 0) {
8520                         dl->index = super->anchor->num_disks;
8521                         super->anchor->num_disks++;
8522                 }
8523                 disk = &dl->disk;
8524                 disk->status |= CONFIGURED_DISK;
8525                 disk->status &= ~SPARE_DISK;
8526
8527                 /* mark rebuild */
8528                 to_state = imsm_check_degraded(super, dev, failed, MAP_0);
8529                 if (!second_map_created) {
8530                         second_map_created = 1;
8531                         map->map_state = IMSM_T_STATE_DEGRADED;
8532                         migrate(dev, super, to_state, MIGR_REBUILD);
8533                 } else
8534                         map->map_state = to_state;
8535                 migr_map = get_imsm_map(dev, MAP_1);
8536                 set_imsm_ord_tbl_ent(map, u->slot, dl->index);
8537                 set_imsm_ord_tbl_ent(migr_map, u->slot,
8538                                      dl->index | IMSM_ORD_REBUILD);
8539
8540                 /* update the family_num to mark a new container
8541                  * generation, being careful to record the existing
8542                  * family_num in orig_family_num to clean up after
8543                  * earlier mdadm versions that neglected to set it.
8544                  */
8545                 if (mpb->orig_family_num == 0)
8546                         mpb->orig_family_num = mpb->family_num;
8547                 mpb->family_num += super->random;
8548
8549                 /* count arrays using the victim in the metadata */
8550                 found = 0;
8551                 for (a = active_array; a ; a = a->next) {
8552                         dev = get_imsm_dev(super, a->info.container_member);
8553                         map = get_imsm_map(dev, MAP_0);
8554
8555                         if (get_imsm_disk_slot(map, victim) >= 0)
8556                                 found++;
8557                 }
8558
8559                 /* delete the victim if it is no longer being
8560                  * utilized anywhere
8561                  */
8562                 if (!found) {
8563                         struct dl **dlp;
8564
8565                         /* We know that 'manager' isn't touching anything,
8566                          * so it is safe to delete
8567                          */
8568                         for (dlp = &super->disks; *dlp; dlp = &(*dlp)->next)
8569                                 if ((*dlp)->index == victim)
8570                                         break;
8571
8572                         /* victim may be on the missing list */
8573                         if (!*dlp)
8574                                 for (dlp = &super->missing; *dlp;
8575                                      dlp = &(*dlp)->next)
8576                                         if ((*dlp)->index == victim)
8577                                                 break;
8578                         imsm_delete(super, dlp, victim);
8579                 }
8580         }
8581
8582         return 1;
8583 }
8584
8585 static int apply_reshape_container_disks_update(struct imsm_update_reshape *u,
8586                                                 struct intel_super *super,
8587                                                 void ***space_list)
8588 {
8589         struct dl *new_disk;
8590         struct intel_dev *id;
8591         int i;
8592         int delta_disks = u->new_raid_disks - u->old_raid_disks;
8593         int disk_count = u->old_raid_disks;
8594         void **tofree = NULL;
8595         int devices_to_reshape = 1;
8596         struct imsm_super *mpb = super->anchor;
8597         int ret_val = 0;
8598         unsigned int dev_id;
8599
8600         dprintf("(enter)\n");
8601
8602         /* enable spares to use in array */
8603         for (i = 0; i < delta_disks; i++) {
8604                 new_disk = get_disk_super(super,
8605                                           major(u->new_disks[i]),
8606                                           minor(u->new_disks[i]));
8607                 dprintf("imsm: new disk for reshape is: %i:%i (%p, index = %i)\n",
8608                         major(u->new_disks[i]), minor(u->new_disks[i]),
8609                         new_disk, new_disk->index);
8610                 if (new_disk == NULL ||
8611                     (new_disk->index >= 0 &&
8612                      new_disk->index < u->old_raid_disks))
8613                         goto update_reshape_exit;
8614                 new_disk->index = disk_count++;
8615                 /* slot to fill in autolayout
8616                  */
8617                 new_disk->raiddisk = new_disk->index;
8618                 new_disk->disk.status |=
8619                         CONFIGURED_DISK;
8620                 new_disk->disk.status &= ~SPARE_DISK;
8621         }
8622
8623         dprintf("imsm: volume set mpb->num_raid_devs = %i\n",
8624                 mpb->num_raid_devs);
8625         /* manage changes in volume
8626          */
8627         for (dev_id = 0; dev_id < mpb->num_raid_devs; dev_id++) {
8628                 void **sp = *space_list;
8629                 struct imsm_dev *newdev;
8630                 struct imsm_map *newmap, *oldmap;
8631
8632                 for (id = super->devlist ; id; id = id->next) {
8633                         if (id->index == dev_id)
8634                                 break;
8635                 }
8636                 if (id == NULL)
8637                         break;
8638                 if (!sp)
8639                         continue;
8640                 *space_list = *sp;
8641                 newdev = (void*)sp;
8642                 /* Copy the dev, but not (all of) the map */
8643                 memcpy(newdev, id->dev, sizeof(*newdev));
8644                 oldmap = get_imsm_map(id->dev, MAP_0);
8645                 newmap = get_imsm_map(newdev, MAP_0);
8646                 /* Copy the current map */
8647                 memcpy(newmap, oldmap, sizeof_imsm_map(oldmap));
8648                 /* update one device only
8649                  */
8650                 if (devices_to_reshape) {
8651                         dprintf("imsm: modifying subdev: %i\n",
8652                                 id->index);
8653                         devices_to_reshape--;
8654                         newdev->vol.migr_state = 1;
8655                         newdev->vol.curr_migr_unit = 0;
8656                         set_migr_type(newdev, MIGR_GEN_MIGR);
8657                         newmap->num_members = u->new_raid_disks;
8658                         for (i = 0; i < delta_disks; i++) {
8659                                 set_imsm_ord_tbl_ent(newmap,
8660                                                      u->old_raid_disks + i,
8661                                                      u->old_raid_disks + i);
8662                         }
8663                         /* New map is correct, now need to save old map
8664                          */
8665                         newmap = get_imsm_map(newdev, MAP_1);
8666                         memcpy(newmap, oldmap, sizeof_imsm_map(oldmap));
8667
8668                         imsm_set_array_size(newdev, -1);
8669                 }
8670
8671                 sp = (void **)id->dev;
8672                 id->dev = newdev;
8673                 *sp = tofree;
8674                 tofree = sp;
8675
8676                 /* Clear migration record */
8677                 memset(super->migr_rec, 0, sizeof(struct migr_record));
8678         }
8679         if (tofree)
8680                 *space_list = tofree;
8681         ret_val = 1;
8682
8683 update_reshape_exit:
8684
8685         return ret_val;
8686 }
8687
8688 static int apply_takeover_update(struct imsm_update_takeover *u,
8689                                  struct intel_super *super,
8690                                  void ***space_list)
8691 {
8692         struct imsm_dev *dev = NULL;
8693         struct intel_dev *dv;
8694         struct imsm_dev *dev_new;
8695         struct imsm_map *map;
8696         struct dl *dm, *du;
8697         int i;
8698
8699         for (dv = super->devlist; dv; dv = dv->next)
8700                 if (dv->index == (unsigned int)u->subarray) {
8701                         dev = dv->dev;
8702                         break;
8703                 }
8704
8705         if (dev == NULL)
8706                 return 0;
8707
8708         map = get_imsm_map(dev, MAP_0);
8709
8710         if (u->direction == R10_TO_R0) {
8711                 unsigned long long num_data_stripes;
8712
8713                 map->num_domains = 1;
8714                 num_data_stripes = blocks_per_member(map);
8715                 num_data_stripes /= map->blocks_per_strip;
8716                 num_data_stripes /= map->num_domains;
8717                 set_num_data_stripes(map, num_data_stripes);
8718
8719                 /* Number of failed disks must be half of initial disk number */
8720                 if (imsm_count_failed(super, dev, MAP_0) !=
8721                                 (map->num_members / 2))
8722                         return 0;
8723
8724                 /* iterate through devices to mark removed disks as spare */
8725                 for (dm = super->disks; dm; dm = dm->next) {
8726                         if (dm->disk.status & FAILED_DISK) {
8727                                 int idx = dm->index;
8728                                 /* update indexes on the disk list */
8729 /* FIXME this loop-with-the-loop looks wrong,  I'm not convinced
8730    the index values will end up being correct.... NB */
8731                                 for (du = super->disks; du; du = du->next)
8732                                         if (du->index > idx)
8733                                                 du->index--;
8734                                 /* mark as spare disk */
8735                                 mark_spare(dm);
8736                         }
8737                 }
8738                 /* update map */
8739                 map->num_members = map->num_members / 2;
8740                 map->map_state = IMSM_T_STATE_NORMAL;
8741                 map->num_domains = 1;
8742                 map->raid_level = 0;
8743                 map->failed_disk_num = -1;
8744         }
8745
8746         if (u->direction == R0_TO_R10) {
8747                 void **space;
8748                 /* update slots in current disk list */
8749                 for (dm = super->disks; dm; dm = dm->next) {
8750                         if (dm->index >= 0)
8751                                 dm->index *= 2;
8752                 }
8753                 /* create new *missing* disks */
8754                 for (i = 0; i < map->num_members; i++) {
8755                         space = *space_list;
8756                         if (!space)
8757                                 continue;
8758                         *space_list = *space;
8759                         du = (void *)space;
8760                         memcpy(du, super->disks, sizeof(*du));
8761                         du->fd = -1;
8762                         du->minor = 0;
8763                         du->major = 0;
8764                         du->index = (i * 2) + 1;
8765                         sprintf((char *)du->disk.serial,
8766                                 " MISSING_%d", du->index);
8767                         sprintf((char *)du->serial,
8768                                 "MISSING_%d", du->index);
8769                         du->next = super->missing;
8770                         super->missing = du;
8771                 }
8772                 /* create new dev and map */
8773                 space = *space_list;
8774                 if (!space)
8775                         return 0;
8776                 *space_list = *space;
8777                 dev_new = (void *)space;
8778                 memcpy(dev_new, dev, sizeof(*dev));
8779                 /* update new map */
8780                 map = get_imsm_map(dev_new, MAP_0);
8781                 map->num_members = map->num_members * 2;
8782                 map->map_state = IMSM_T_STATE_DEGRADED;
8783                 map->num_domains = 2;
8784                 map->raid_level = 1;
8785                 /* replace dev<->dev_new */
8786                 dv->dev = dev_new;
8787         }
8788         /* update disk order table */
8789         for (du = super->disks; du; du = du->next)
8790                 if (du->index >= 0)
8791                         set_imsm_ord_tbl_ent(map, du->index, du->index);
8792         for (du = super->missing; du; du = du->next)
8793                 if (du->index >= 0) {
8794                         set_imsm_ord_tbl_ent(map, du->index, du->index);
8795                         mark_missing(dv->dev, &du->disk, du->index);
8796                 }
8797
8798         return 1;
8799 }
8800
8801 static void imsm_process_update(struct supertype *st,
8802                                 struct metadata_update *update)
8803 {
8804         /**
8805          * crack open the metadata_update envelope to find the update record
8806          * update can be one of:
8807          *    update_reshape_container_disks - all the arrays in the container
8808          *      are being reshaped to have more devices.  We need to mark
8809          *      the arrays for general migration and convert selected spares
8810          *      into active devices.
8811          *    update_activate_spare - a spare device has replaced a failed
8812          *      device in an array, update the disk_ord_tbl.  If this disk is
8813          *      present in all member arrays then also clear the SPARE_DISK
8814          *      flag
8815          *    update_create_array
8816          *    update_kill_array
8817          *    update_rename_array
8818          *    update_add_remove_disk
8819          */
8820         struct intel_super *super = st->sb;
8821         struct imsm_super *mpb;
8822         enum imsm_update_type type = *(enum imsm_update_type *) update->buf;
8823
8824         /* update requires a larger buf but the allocation failed */
8825         if (super->next_len && !super->next_buf) {
8826                 super->next_len = 0;
8827                 return;
8828         }
8829
8830         if (super->next_buf) {
8831                 memcpy(super->next_buf, super->buf, super->len);
8832                 free(super->buf);
8833                 super->len = super->next_len;
8834                 super->buf = super->next_buf;
8835
8836                 super->next_len = 0;
8837                 super->next_buf = NULL;
8838         }
8839
8840         mpb = super->anchor;
8841
8842         switch (type) {
8843         case update_general_migration_checkpoint: {
8844                 struct intel_dev *id;
8845                 struct imsm_update_general_migration_checkpoint *u =
8846                                                         (void *)update->buf;
8847
8848                 dprintf("called for update_general_migration_checkpoint\n");
8849
8850                 /* find device under general migration */
8851                 for (id = super->devlist ; id; id = id->next) {
8852                         if (is_gen_migration(id->dev)) {
8853                                 id->dev->vol.curr_migr_unit =
8854                                         __cpu_to_le32(u->curr_migr_unit);
8855                                 super->updates_pending++;
8856                         }
8857                 }
8858                 break;
8859         }
8860         case update_takeover: {
8861                 struct imsm_update_takeover *u = (void *)update->buf;
8862                 if (apply_takeover_update(u, super, &update->space_list)) {
8863                         imsm_update_version_info(super);
8864                         super->updates_pending++;
8865                 }
8866                 break;
8867         }
8868
8869         case update_reshape_container_disks: {
8870                 struct imsm_update_reshape *u = (void *)update->buf;
8871                 if (apply_reshape_container_disks_update(
8872                             u, super, &update->space_list))
8873                         super->updates_pending++;
8874                 break;
8875         }
8876         case update_reshape_migration: {
8877                 struct imsm_update_reshape_migration *u = (void *)update->buf;
8878                 if (apply_reshape_migration_update(
8879                             u, super, &update->space_list))
8880                         super->updates_pending++;
8881                 break;
8882         }
8883         case update_size_change: {
8884                 struct imsm_update_size_change *u = (void *)update->buf;
8885                 if (apply_size_change_update(u, super))
8886                         super->updates_pending++;
8887                 break;
8888         }
8889         case update_activate_spare: {
8890                 struct imsm_update_activate_spare *u = (void *) update->buf;
8891                 if (apply_update_activate_spare(u, super, st->arrays))
8892                         super->updates_pending++;
8893                 break;
8894         }
8895         case update_create_array: {
8896                 /* someone wants to create a new array, we need to be aware of
8897                  * a few races/collisions:
8898                  * 1/ 'Create' called by two separate instances of mdadm
8899                  * 2/ 'Create' versus 'activate_spare': mdadm has chosen
8900                  *     devices that have since been assimilated via
8901                  *     activate_spare.
8902                  * In the event this update can not be carried out mdadm will
8903                  * (FIX ME) notice that its update did not take hold.
8904                  */
8905                 struct imsm_update_create_array *u = (void *) update->buf;
8906                 struct intel_dev *dv;
8907                 struct imsm_dev *dev;
8908                 struct imsm_map *map, *new_map;
8909                 unsigned long long start, end;
8910                 unsigned long long new_start, new_end;
8911                 int i;
8912                 struct disk_info *inf;
8913                 struct dl *dl;
8914
8915                 /* handle racing creates: first come first serve */
8916                 if (u->dev_idx < mpb->num_raid_devs) {
8917                         dprintf("subarray %d already defined\n", u->dev_idx);
8918                         goto create_error;
8919                 }
8920
8921                 /* check update is next in sequence */
8922                 if (u->dev_idx != mpb->num_raid_devs) {
8923                         dprintf("can not create array %d expected index %d\n",
8924                                 u->dev_idx, mpb->num_raid_devs);
8925                         goto create_error;
8926                 }
8927
8928                 new_map = get_imsm_map(&u->dev, MAP_0);
8929                 new_start = pba_of_lba0(new_map);
8930                 new_end = new_start + blocks_per_member(new_map);
8931                 inf = get_disk_info(u);
8932
8933                 /* handle activate_spare versus create race:
8934                  * check to make sure that overlapping arrays do not include
8935                  * overalpping disks
8936                  */
8937                 for (i = 0; i < mpb->num_raid_devs; i++) {
8938                         dev = get_imsm_dev(super, i);
8939                         map = get_imsm_map(dev, MAP_0);
8940                         start = pba_of_lba0(map);
8941                         end = start + blocks_per_member(map);
8942                         if ((new_start >= start && new_start <= end) ||
8943                             (start >= new_start && start <= new_end))
8944                                 /* overlap */;
8945                         else
8946                                 continue;
8947
8948                         if (disks_overlap(super, i, u)) {
8949                                 dprintf("arrays overlap\n");
8950                                 goto create_error;
8951                         }
8952                 }
8953
8954                 /* check that prepare update was successful */
8955                 if (!update->space) {
8956                         dprintf("prepare update failed\n");
8957                         goto create_error;
8958                 }
8959
8960                 /* check that all disks are still active before committing
8961                  * changes.  FIXME: could we instead handle this by creating a
8962                  * degraded array?  That's probably not what the user expects,
8963                  * so better to drop this update on the floor.
8964                  */
8965                 for (i = 0; i < new_map->num_members; i++) {
8966                         dl = serial_to_dl(inf[i].serial, super);
8967                         if (!dl) {
8968                                 dprintf("disk disappeared\n");
8969                                 goto create_error;
8970                         }
8971                 }
8972
8973                 super->updates_pending++;
8974
8975                 /* convert spares to members and fixup ord_tbl */
8976                 for (i = 0; i < new_map->num_members; i++) {
8977                         dl = serial_to_dl(inf[i].serial, super);
8978                         if (dl->index == -1) {
8979                                 dl->index = mpb->num_disks;
8980                                 mpb->num_disks++;
8981                                 dl->disk.status |= CONFIGURED_DISK;
8982                                 dl->disk.status &= ~SPARE_DISK;
8983                         }
8984                         set_imsm_ord_tbl_ent(new_map, i, dl->index);
8985                 }
8986
8987                 dv = update->space;
8988                 dev = dv->dev;
8989                 update->space = NULL;
8990                 imsm_copy_dev(dev, &u->dev);
8991                 dv->index = u->dev_idx;
8992                 dv->next = super->devlist;
8993                 super->devlist = dv;
8994                 mpb->num_raid_devs++;
8995
8996                 imsm_update_version_info(super);
8997                 break;
8998  create_error:
8999                 /* mdmon knows how to release update->space, but not
9000                  * ((struct intel_dev *) update->space)->dev
9001                  */
9002                 if (update->space) {
9003                         dv = update->space;
9004                         free(dv->dev);
9005                 }
9006                 break;
9007         }
9008         case update_kill_array: {
9009                 struct imsm_update_kill_array *u = (void *) update->buf;
9010                 int victim = u->dev_idx;
9011                 struct active_array *a;
9012                 struct intel_dev **dp;
9013                 struct imsm_dev *dev;
9014
9015                 /* sanity check that we are not affecting the uuid of
9016                  * active arrays, or deleting an active array
9017                  *
9018                  * FIXME when immutable ids are available, but note that
9019                  * we'll also need to fixup the invalidated/active
9020                  * subarray indexes in mdstat
9021                  */
9022                 for (a = st->arrays; a; a = a->next)
9023                         if (a->info.container_member >= victim)
9024                                 break;
9025                 /* by definition if mdmon is running at least one array
9026                  * is active in the container, so checking
9027                  * mpb->num_raid_devs is just extra paranoia
9028                  */
9029                 dev = get_imsm_dev(super, victim);
9030                 if (a || !dev || mpb->num_raid_devs == 1) {
9031                         dprintf("failed to delete subarray-%d\n", victim);
9032                         break;
9033                 }
9034
9035                 for (dp = &super->devlist; *dp;)
9036                         if ((*dp)->index == (unsigned)super->current_vol) {
9037                                 *dp = (*dp)->next;
9038                         } else {
9039                                 if ((*dp)->index > (unsigned)victim)
9040                                         (*dp)->index--;
9041                                 dp = &(*dp)->next;
9042                         }
9043                 mpb->num_raid_devs--;
9044                 super->updates_pending++;
9045                 break;
9046         }
9047         case update_rename_array: {
9048                 struct imsm_update_rename_array *u = (void *) update->buf;
9049                 char name[MAX_RAID_SERIAL_LEN+1];
9050                 int target = u->dev_idx;
9051                 struct active_array *a;
9052                 struct imsm_dev *dev;
9053
9054                 /* sanity check that we are not affecting the uuid of
9055                  * an active array
9056                  */
9057                 snprintf(name, MAX_RAID_SERIAL_LEN, "%s", (char *) u->name);
9058                 name[MAX_RAID_SERIAL_LEN] = '\0';
9059                 for (a = st->arrays; a; a = a->next)
9060                         if (a->info.container_member == target)
9061                                 break;
9062                 dev = get_imsm_dev(super, u->dev_idx);
9063                 if (a || !dev || !check_name(super, name, 1)) {
9064                         dprintf("failed to rename subarray-%d\n", target);
9065                         break;
9066                 }
9067
9068                 snprintf((char *) dev->volume, MAX_RAID_SERIAL_LEN, "%s", name);
9069                 super->updates_pending++;
9070                 break;
9071         }
9072         case update_add_remove_disk: {
9073                 /* we may be able to repair some arrays if disks are
9074                  * being added, check the status of add_remove_disk
9075                  * if discs has been added.
9076                  */
9077                 if (add_remove_disk_update(super)) {
9078                         struct active_array *a;
9079
9080                         super->updates_pending++;
9081                         for (a = st->arrays; a; a = a->next)
9082                                 a->check_degraded = 1;
9083                 }
9084                 break;
9085         }
9086         case update_prealloc_badblocks_mem:
9087                 break;
9088         default:
9089                 pr_err("error: unsuported process update type:(type: %d)\n",    type);
9090         }
9091 }
9092
9093 static struct mdinfo *get_spares_for_grow(struct supertype *st);
9094
9095 static int imsm_prepare_update(struct supertype *st,
9096                                struct metadata_update *update)
9097 {
9098         /**
9099          * Allocate space to hold new disk entries, raid-device entries or a new
9100          * mpb if necessary.  The manager synchronously waits for updates to
9101          * complete in the monitor, so new mpb buffers allocated here can be
9102          * integrated by the monitor thread without worrying about live pointers
9103          * in the manager thread.
9104          */
9105         enum imsm_update_type type;
9106         struct intel_super *super = st->sb;
9107         unsigned int sector_size = super->sector_size;
9108         struct imsm_super *mpb = super->anchor;
9109         size_t buf_len;
9110         size_t len = 0;
9111
9112         if (update->len < (int)sizeof(type))
9113                 return 0;
9114
9115         type = *(enum imsm_update_type *) update->buf;
9116
9117         switch (type) {
9118         case update_general_migration_checkpoint:
9119                 if (update->len < (int)sizeof(struct imsm_update_general_migration_checkpoint))
9120                         return 0;
9121                 dprintf("called for update_general_migration_checkpoint\n");
9122                 break;
9123         case update_takeover: {
9124                 struct imsm_update_takeover *u = (void *)update->buf;
9125                 if (update->len < (int)sizeof(*u))
9126                         return 0;
9127                 if (u->direction == R0_TO_R10) {
9128                         void **tail = (void **)&update->space_list;
9129                         struct imsm_dev *dev = get_imsm_dev(super, u->subarray);
9130                         struct imsm_map *map = get_imsm_map(dev, MAP_0);
9131                         int num_members = map->num_members;
9132                         void *space;
9133                         int size, i;
9134                         /* allocate memory for added disks */
9135                         for (i = 0; i < num_members; i++) {
9136                                 size = sizeof(struct dl);
9137                                 space = xmalloc(size);
9138                                 *tail = space;
9139                                 tail = space;
9140                                 *tail = NULL;
9141                         }
9142                         /* allocate memory for new device */
9143                         size = sizeof_imsm_dev(super->devlist->dev, 0) +
9144                                 (num_members * sizeof(__u32));
9145                         space = xmalloc(size);
9146                         *tail = space;
9147                         tail = space;
9148                         *tail = NULL;
9149                         len = disks_to_mpb_size(num_members * 2);
9150                 }
9151
9152                 break;
9153         }
9154         case update_reshape_container_disks: {
9155                 /* Every raid device in the container is about to
9156                  * gain some more devices, and we will enter a
9157                  * reconfiguration.
9158                  * So each 'imsm_map' will be bigger, and the imsm_vol
9159                  * will now hold 2 of them.
9160                  * Thus we need new 'struct imsm_dev' allocations sized
9161                  * as sizeof_imsm_dev but with more devices in both maps.
9162                  */
9163                 struct imsm_update_reshape *u = (void *)update->buf;
9164                 struct intel_dev *dl;
9165                 void **space_tail = (void**)&update->space_list;
9166
9167                 if (update->len < (int)sizeof(*u))
9168                         return 0;
9169
9170                 dprintf("for update_reshape\n");
9171
9172                 for (dl = super->devlist; dl; dl = dl->next) {
9173                         int size = sizeof_imsm_dev(dl->dev, 1);
9174                         void *s;
9175                         if (u->new_raid_disks > u->old_raid_disks)
9176                                 size += sizeof(__u32)*2*
9177                                         (u->new_raid_disks - u->old_raid_disks);
9178                         s = xmalloc(size);
9179                         *space_tail = s;
9180                         space_tail = s;
9181                         *space_tail = NULL;
9182                 }
9183
9184                 len = disks_to_mpb_size(u->new_raid_disks);
9185                 dprintf("New anchor length is %llu\n", (unsigned long long)len);
9186                 break;
9187         }
9188         case update_reshape_migration: {
9189                 /* for migration level 0->5 we need to add disks
9190                  * so the same as for container operation we will copy
9191                  * device to the bigger location.
9192                  * in memory prepared device and new disk area are prepared
9193                  * for usage in process update
9194                  */
9195                 struct imsm_update_reshape_migration *u = (void *)update->buf;
9196                 struct intel_dev *id;
9197                 void **space_tail = (void **)&update->space_list;
9198                 int size;
9199                 void *s;
9200                 int current_level = -1;
9201
9202                 if (update->len < (int)sizeof(*u))
9203                         return 0;
9204
9205                 dprintf("for update_reshape\n");
9206
9207                 /* add space for bigger array in update
9208                  */
9209                 for (id = super->devlist; id; id = id->next) {
9210                         if (id->index == (unsigned)u->subdev) {
9211                                 size = sizeof_imsm_dev(id->dev, 1);
9212                                 if (u->new_raid_disks > u->old_raid_disks)
9213                                         size += sizeof(__u32)*2*
9214                                         (u->new_raid_disks - u->old_raid_disks);
9215                                 s = xmalloc(size);
9216                                 *space_tail = s;
9217                                 space_tail = s;
9218                                 *space_tail = NULL;
9219                                 break;
9220                         }
9221                 }
9222                 if (update->space_list == NULL)
9223                         break;
9224
9225                 /* add space for disk in update
9226                  */
9227                 size = sizeof(struct dl);
9228                 s = xmalloc(size);
9229                 *space_tail = s;
9230                 space_tail = s;
9231                 *space_tail = NULL;
9232
9233                 /* add spare device to update
9234                  */
9235                 for (id = super->devlist ; id; id = id->next)
9236                         if (id->index == (unsigned)u->subdev) {
9237                                 struct imsm_dev *dev;
9238                                 struct imsm_map *map;
9239
9240                                 dev = get_imsm_dev(super, u->subdev);
9241                                 map = get_imsm_map(dev, MAP_0);
9242                                 current_level = map->raid_level;
9243                                 break;
9244                         }
9245                 if (u->new_level == 5 && u->new_level != current_level) {
9246                         struct mdinfo *spares;
9247
9248                         spares = get_spares_for_grow(st);
9249                         if (spares) {
9250                                 struct dl *dl;
9251                                 struct mdinfo *dev;
9252
9253                                 dev = spares->devs;
9254                                 if (dev) {
9255                                         u->new_disks[0] =
9256                                                 makedev(dev->disk.major,
9257                                                         dev->disk.minor);
9258                                         dl = get_disk_super(super,
9259                                                             dev->disk.major,
9260                                                             dev->disk.minor);
9261                                         dl->index = u->old_raid_disks;
9262                                         dev = dev->next;
9263                                 }
9264                                 sysfs_free(spares);
9265                         }
9266                 }
9267                 len = disks_to_mpb_size(u->new_raid_disks);
9268                 dprintf("New anchor length is %llu\n", (unsigned long long)len);
9269                 break;
9270         }
9271         case update_size_change: {
9272                 if (update->len < (int)sizeof(struct imsm_update_size_change))
9273                         return 0;
9274                 break;
9275         }
9276         case update_activate_spare: {
9277                 if (update->len < (int)sizeof(struct imsm_update_activate_spare))
9278                         return 0;
9279                 break;
9280         }
9281         case update_create_array: {
9282                 struct imsm_update_create_array *u = (void *) update->buf;
9283                 struct intel_dev *dv;
9284                 struct imsm_dev *dev = &u->dev;
9285                 struct imsm_map *map = get_imsm_map(dev, MAP_0);
9286                 struct dl *dl;
9287                 struct disk_info *inf;
9288                 int i;
9289                 int activate = 0;
9290
9291                 if (update->len < (int)sizeof(*u))
9292                         return 0;
9293
9294                 inf = get_disk_info(u);
9295                 len = sizeof_imsm_dev(dev, 1);
9296                 /* allocate a new super->devlist entry */
9297                 dv = xmalloc(sizeof(*dv));
9298                 dv->dev = xmalloc(len);
9299                 update->space = dv;
9300
9301                 /* count how many spares will be converted to members */
9302                 for (i = 0; i < map->num_members; i++) {
9303                         dl = serial_to_dl(inf[i].serial, super);
9304                         if (!dl) {
9305                                 /* hmm maybe it failed?, nothing we can do about
9306                                  * it here
9307                                  */
9308                                 continue;
9309                         }
9310                         if (count_memberships(dl, super) == 0)
9311                                 activate++;
9312                 }
9313                 len += activate * sizeof(struct imsm_disk);
9314                 break;
9315         }
9316         case update_kill_array: {
9317                 if (update->len < (int)sizeof(struct imsm_update_kill_array))
9318                         return 0;
9319                 break;
9320         }
9321         case update_rename_array: {
9322                 if (update->len < (int)sizeof(struct imsm_update_rename_array))
9323                         return 0;
9324                 break;
9325         }
9326         case update_add_remove_disk:
9327                 /* no update->len needed */
9328                 break;
9329         case update_prealloc_badblocks_mem:
9330                 super->extra_space += sizeof(struct bbm_log) -
9331                         get_imsm_bbm_log_size(super->bbm_log);
9332                 break;
9333         default:
9334                 return 0;
9335         }
9336
9337         /* check if we need a larger metadata buffer */
9338         if (super->next_buf)
9339                 buf_len = super->next_len;
9340         else
9341                 buf_len = super->len;
9342
9343         if (__le32_to_cpu(mpb->mpb_size) + super->extra_space + len > buf_len) {
9344                 /* ok we need a larger buf than what is currently allocated
9345                  * if this allocation fails process_update will notice that
9346                  * ->next_len is set and ->next_buf is NULL
9347                  */
9348                 buf_len = ROUND_UP(__le32_to_cpu(mpb->mpb_size) +
9349                                    super->extra_space + len, sector_size);
9350                 if (super->next_buf)
9351                         free(super->next_buf);
9352
9353                 super->next_len = buf_len;
9354                 if (posix_memalign(&super->next_buf, sector_size, buf_len) == 0)
9355                         memset(super->next_buf, 0, buf_len);
9356                 else
9357                         super->next_buf = NULL;
9358         }
9359         return 1;
9360 }
9361
9362 /* must be called while manager is quiesced */
9363 static void imsm_delete(struct intel_super *super, struct dl **dlp, unsigned index)
9364 {
9365         struct imsm_super *mpb = super->anchor;
9366         struct dl *iter;
9367         struct imsm_dev *dev;
9368         struct imsm_map *map;
9369         int i, j, num_members;
9370         __u32 ord;
9371
9372         dprintf("deleting device[%d] from imsm_super\n", index);
9373
9374         /* shift all indexes down one */
9375         for (iter = super->disks; iter; iter = iter->next)
9376                 if (iter->index > (int)index)
9377                         iter->index--;
9378         for (iter = super->missing; iter; iter = iter->next)
9379                 if (iter->index > (int)index)
9380                         iter->index--;
9381
9382         for (i = 0; i < mpb->num_raid_devs; i++) {
9383                 dev = get_imsm_dev(super, i);
9384                 map = get_imsm_map(dev, MAP_0);
9385                 num_members = map->num_members;
9386                 for (j = 0; j < num_members; j++) {
9387                         /* update ord entries being careful not to propagate
9388                          * ord-flags to the first map
9389                          */
9390                         ord = get_imsm_ord_tbl_ent(dev, j, MAP_X);
9391
9392                         if (ord_to_idx(ord) <= index)
9393                                 continue;
9394
9395                         map = get_imsm_map(dev, MAP_0);
9396                         set_imsm_ord_tbl_ent(map, j, ord_to_idx(ord - 1));
9397                         map = get_imsm_map(dev, MAP_1);
9398                         if (map)
9399                                 set_imsm_ord_tbl_ent(map, j, ord - 1);
9400                 }
9401         }
9402
9403         mpb->num_disks--;
9404         super->updates_pending++;
9405         if (*dlp) {
9406                 struct dl *dl = *dlp;
9407
9408                 *dlp = (*dlp)->next;
9409                 __free_imsm_disk(dl);
9410         }
9411 }
9412 #endif /* MDASSEMBLE */
9413
9414 static void close_targets(int *targets, int new_disks)
9415 {
9416         int i;
9417
9418         if (!targets)
9419                 return;
9420
9421         for (i = 0; i < new_disks; i++) {
9422                 if (targets[i] >= 0) {
9423                         close(targets[i]);
9424                         targets[i] = -1;
9425                 }
9426         }
9427 }
9428
9429 static int imsm_get_allowed_degradation(int level, int raid_disks,
9430                                         struct intel_super *super,
9431                                         struct imsm_dev *dev)
9432 {
9433         switch (level) {
9434         case 1:
9435         case 10:{
9436                 int ret_val = 0;
9437                 struct imsm_map *map;
9438                 int i;
9439
9440                 ret_val = raid_disks/2;
9441                 /* check map if all disks pairs not failed
9442                  * in both maps
9443                  */
9444                 map = get_imsm_map(dev, MAP_0);
9445                 for (i = 0; i < ret_val; i++) {
9446                         int degradation = 0;
9447                         if (get_imsm_disk(super, i) == NULL)
9448                                 degradation++;
9449                         if (get_imsm_disk(super, i + 1) == NULL)
9450                                 degradation++;
9451                         if (degradation == 2)
9452                                 return 0;
9453                 }
9454                 map = get_imsm_map(dev, MAP_1);
9455                 /* if there is no second map
9456                  * result can be returned
9457                  */
9458                 if (map == NULL)
9459                         return ret_val;
9460                 /* check degradation in second map
9461                  */
9462                 for (i = 0; i < ret_val; i++) {
9463                         int degradation = 0;
9464                 if (get_imsm_disk(super, i) == NULL)
9465                                 degradation++;
9466                         if (get_imsm_disk(super, i + 1) == NULL)
9467                                 degradation++;
9468                         if (degradation == 2)
9469                                 return 0;
9470                 }
9471                 return ret_val;
9472         }
9473         case 5:
9474                 return 1;
9475         case 6:
9476                 return 2;
9477         default:
9478                 return 0;
9479         }
9480 }
9481
9482 /*******************************************************************************
9483  * Function:    open_backup_targets
9484  * Description: Function opens file descriptors for all devices given in
9485  *              info->devs
9486  * Parameters:
9487  *      info            : general array info
9488  *      raid_disks      : number of disks
9489  *      raid_fds        : table of device's file descriptors
9490  *      super           : intel super for raid10 degradation check
9491  *      dev             : intel device for raid10 degradation check
9492  * Returns:
9493  *       0 : success
9494  *      -1 : fail
9495  ******************************************************************************/
9496 int open_backup_targets(struct mdinfo *info, int raid_disks, int *raid_fds,
9497                         struct intel_super *super, struct imsm_dev *dev)
9498 {
9499         struct mdinfo *sd;
9500         int i;
9501         int opened = 0;
9502
9503         for (i = 0; i < raid_disks; i++)
9504                 raid_fds[i] = -1;
9505
9506         for (sd = info->devs ; sd ; sd = sd->next) {
9507                 char *dn;
9508
9509                 if (sd->disk.state & (1<<MD_DISK_FAULTY)) {
9510                         dprintf("disk is faulty!!\n");
9511                         continue;
9512                 }
9513
9514                 if (sd->disk.raid_disk >= raid_disks || sd->disk.raid_disk < 0)
9515                         continue;
9516
9517                 dn = map_dev(sd->disk.major,
9518                              sd->disk.minor, 1);
9519                 raid_fds[sd->disk.raid_disk] = dev_open(dn, O_RDWR);
9520                 if (raid_fds[sd->disk.raid_disk] < 0) {
9521                         pr_err("cannot open component\n");
9522                         continue;
9523                 }
9524                 opened++;
9525         }
9526         /* check if maximum array degradation level is not exceeded
9527         */
9528         if ((raid_disks - opened) >
9529             imsm_get_allowed_degradation(info->new_level, raid_disks,
9530                                          super, dev)) {
9531                 pr_err("Not enough disks can be opened.\n");
9532                 close_targets(raid_fds, raid_disks);
9533                 return -2;
9534         }
9535         return 0;
9536 }
9537
9538 /*******************************************************************************
9539  * Function:    validate_container_imsm
9540  * Description: This routine validates container after assemble,
9541  *              eg. if devices in container are under the same controller.
9542  *
9543  * Parameters:
9544  *      info    : linked list with info about devices used in array
9545  * Returns:
9546  *      1 : HBA mismatch
9547  *      0 : Success
9548  ******************************************************************************/
9549 int validate_container_imsm(struct mdinfo *info)
9550 {
9551         if (check_env("IMSM_NO_PLATFORM"))
9552                 return 0;
9553
9554         struct sys_dev *idev;
9555         struct sys_dev *hba = NULL;
9556         struct sys_dev *intel_devices = find_intel_devices();
9557         char *dev_path = devt_to_devpath(makedev(info->disk.major,
9558                                                                         info->disk.minor));
9559
9560         for (idev = intel_devices; idev; idev = idev->next) {
9561                 if (dev_path && strstr(dev_path, idev->path)) {
9562                         hba = idev;
9563                         break;
9564                 }
9565         }
9566         if (dev_path)
9567                 free(dev_path);
9568
9569         if (!hba) {
9570                 pr_err("WARNING - Cannot detect HBA for device %s!\n",
9571                                 devid2kname(makedev(info->disk.major, info->disk.minor)));
9572                 return 1;
9573         }
9574
9575         const struct imsm_orom *orom = get_orom_by_device_id(hba->dev_id);
9576         struct mdinfo *dev;
9577
9578         for (dev = info->next; dev; dev = dev->next) {
9579                 dev_path = devt_to_devpath(makedev(dev->disk.major, dev->disk.minor));
9580
9581                 struct sys_dev *hba2 = NULL;
9582                 for (idev = intel_devices; idev; idev = idev->next) {
9583                         if (dev_path && strstr(dev_path, idev->path)) {
9584                                 hba2 = idev;
9585                                 break;
9586                         }
9587                 }
9588                 if (dev_path)
9589                         free(dev_path);
9590
9591                 const struct imsm_orom *orom2 = hba2 == NULL ? NULL :
9592                                 get_orom_by_device_id(hba2->dev_id);
9593
9594                 if (hba2 && hba->type != hba2->type) {
9595                         pr_err("WARNING - HBAs of devices do not match %s != %s\n",
9596                                 get_sys_dev_type(hba->type), get_sys_dev_type(hba2->type));
9597                         return 1;
9598                 }
9599
9600                 if (orom != orom2) {
9601                         pr_err("WARNING - IMSM container assembled with disks under different HBAs!\n"
9602                                 "       This operation is not supported and can lead to data loss.\n");
9603                         return 1;
9604                 }
9605
9606                 if (!orom) {
9607                         pr_err("WARNING - IMSM container assembled with disks under HBAs without IMSM platform support!\n"
9608                                 "       This operation is not supported and can lead to data loss.\n");
9609                         return 1;
9610                 }
9611         }
9612
9613         return 0;
9614 }
9615 #ifndef MDASSEMBLE
9616 /*******************************************************************************
9617  * Function:    init_migr_record_imsm
9618  * Description: Function inits imsm migration record
9619  * Parameters:
9620  *      super   : imsm internal array info
9621  *      dev     : device under migration
9622  *      info    : general array info to find the smallest device
9623  * Returns:
9624  *      none
9625  ******************************************************************************/
9626 void init_migr_record_imsm(struct supertype *st, struct imsm_dev *dev,
9627                            struct mdinfo *info)
9628 {
9629         struct intel_super *super = st->sb;
9630         struct migr_record *migr_rec = super->migr_rec;
9631         int new_data_disks;
9632         unsigned long long dsize, dev_sectors;
9633         long long unsigned min_dev_sectors = -1LLU;
9634         struct mdinfo *sd;
9635         char nm[30];
9636         int fd;
9637         struct imsm_map *map_dest = get_imsm_map(dev, MAP_0);
9638         struct imsm_map *map_src = get_imsm_map(dev, MAP_1);
9639         unsigned long long num_migr_units;
9640         unsigned long long array_blocks;
9641
9642         memset(migr_rec, 0, sizeof(struct migr_record));
9643         migr_rec->family_num = __cpu_to_le32(super->anchor->family_num);
9644
9645         /* only ascending reshape supported now */
9646         migr_rec->ascending_migr = __cpu_to_le32(1);
9647
9648         migr_rec->dest_depth_per_unit = GEN_MIGR_AREA_SIZE /
9649                 max(map_dest->blocks_per_strip, map_src->blocks_per_strip);
9650         migr_rec->dest_depth_per_unit *=
9651                 max(map_dest->blocks_per_strip, map_src->blocks_per_strip);
9652         new_data_disks = imsm_num_data_members(dev, MAP_0);
9653         migr_rec->blocks_per_unit =
9654                 __cpu_to_le32(migr_rec->dest_depth_per_unit * new_data_disks);
9655         migr_rec->dest_depth_per_unit =
9656                 __cpu_to_le32(migr_rec->dest_depth_per_unit);
9657         array_blocks = info->component_size * new_data_disks;
9658         num_migr_units =
9659                 array_blocks / __le32_to_cpu(migr_rec->blocks_per_unit);
9660
9661         if (array_blocks % __le32_to_cpu(migr_rec->blocks_per_unit))
9662                 num_migr_units++;
9663         migr_rec->num_migr_units = __cpu_to_le32(num_migr_units);
9664
9665         migr_rec->post_migr_vol_cap =  dev->size_low;
9666         migr_rec->post_migr_vol_cap_hi = dev->size_high;
9667
9668         /* Find the smallest dev */
9669         for (sd = info->devs ; sd ; sd = sd->next) {
9670                 sprintf(nm, "%d:%d", sd->disk.major, sd->disk.minor);
9671                 fd = dev_open(nm, O_RDONLY);
9672                 if (fd < 0)
9673                         continue;
9674                 get_dev_size(fd, NULL, &dsize);
9675                 dev_sectors = dsize / 512;
9676                 if (dev_sectors < min_dev_sectors)
9677                         min_dev_sectors = dev_sectors;
9678                 close(fd);
9679         }
9680         migr_rec->ckpt_area_pba = __cpu_to_le32(min_dev_sectors -
9681                                         RAID_DISK_RESERVED_BLOCKS_IMSM_HI);
9682
9683         write_imsm_migr_rec(st);
9684
9685         return;
9686 }
9687
9688 /*******************************************************************************
9689  * Function:    save_backup_imsm
9690  * Description: Function saves critical data stripes to Migration Copy Area
9691  *              and updates the current migration unit status.
9692  *              Use restore_stripes() to form a destination stripe,
9693  *              and to write it to the Copy Area.
9694  * Parameters:
9695  *      st              : supertype information
9696  *      dev             : imsm device that backup is saved for
9697  *      info            : general array info
9698  *      buf             : input buffer
9699  *      length          : length of data to backup (blocks_per_unit)
9700  * Returns:
9701  *       0 : success
9702  *,     -1 : fail
9703  ******************************************************************************/
9704 int save_backup_imsm(struct supertype *st,
9705                      struct imsm_dev *dev,
9706                      struct mdinfo *info,
9707                      void *buf,
9708                      int length)
9709 {
9710         int rv = -1;
9711         struct intel_super *super = st->sb;
9712         unsigned long long *target_offsets;
9713         int *targets;
9714         int i;
9715         struct imsm_map *map_dest = get_imsm_map(dev, MAP_0);
9716         int new_disks = map_dest->num_members;
9717         int dest_layout = 0;
9718         int dest_chunk;
9719         unsigned long long start;
9720         int data_disks = imsm_num_data_members(dev, MAP_0);
9721
9722         targets = xmalloc(new_disks * sizeof(int));
9723
9724         for (i = 0; i < new_disks; i++)
9725                 targets[i] = -1;
9726
9727         target_offsets = xcalloc(new_disks, sizeof(unsigned long long));
9728
9729         start = info->reshape_progress * 512;
9730         for (i = 0; i < new_disks; i++) {
9731                 target_offsets[i] = (unsigned long long)
9732                   __le32_to_cpu(super->migr_rec->ckpt_area_pba) * 512;
9733                 /* move back copy area adderss, it will be moved forward
9734                  * in restore_stripes() using start input variable
9735                  */
9736                 target_offsets[i] -= start/data_disks;
9737         }
9738
9739         if (open_backup_targets(info, new_disks, targets,
9740                                 super, dev))
9741                 goto abort;
9742
9743         dest_layout = imsm_level_to_layout(map_dest->raid_level);
9744         dest_chunk = __le16_to_cpu(map_dest->blocks_per_strip) * 512;
9745
9746         if (restore_stripes(targets, /* list of dest devices */
9747                             target_offsets, /* migration record offsets */
9748                             new_disks,
9749                             dest_chunk,
9750                             map_dest->raid_level,
9751                             dest_layout,
9752                             -1,    /* source backup file descriptor */
9753                             0,     /* input buf offset
9754                                     * always 0 buf is already offseted */
9755                             start,
9756                             length,
9757                             buf) != 0) {
9758                 pr_err("Error restoring stripes\n");
9759                 goto abort;
9760         }
9761
9762         rv = 0;
9763
9764 abort:
9765         if (targets) {
9766                 close_targets(targets, new_disks);
9767                 free(targets);
9768         }
9769         free(target_offsets);
9770
9771         return rv;
9772 }
9773
9774 /*******************************************************************************
9775  * Function:    save_checkpoint_imsm
9776  * Description: Function called for current unit status update
9777  *              in the migration record. It writes it to disk.
9778  * Parameters:
9779  *      super   : imsm internal array info
9780  *      info    : general array info
9781  * Returns:
9782  *      0: success
9783  *      1: failure
9784  *      2: failure, means no valid migration record
9785  *                 / no general migration in progress /
9786  ******************************************************************************/
9787 int save_checkpoint_imsm(struct supertype *st, struct mdinfo *info, int state)
9788 {
9789         struct intel_super *super = st->sb;
9790         unsigned long long blocks_per_unit;
9791         unsigned long long curr_migr_unit;
9792
9793         if (load_imsm_migr_rec(super, info) != 0) {
9794                 dprintf("imsm: ERROR: Cannot read migration record for checkpoint save.\n");
9795                 return 1;
9796         }
9797
9798         blocks_per_unit = __le32_to_cpu(super->migr_rec->blocks_per_unit);
9799         if (blocks_per_unit == 0) {
9800                 dprintf("imsm: no migration in progress.\n");
9801                 return 2;
9802         }
9803         curr_migr_unit = info->reshape_progress / blocks_per_unit;
9804         /* check if array is alligned to copy area
9805          * if it is not alligned, add one to current migration unit value
9806          * this can happend on array reshape finish only
9807          */
9808         if (info->reshape_progress % blocks_per_unit)
9809                 curr_migr_unit++;
9810
9811         super->migr_rec->curr_migr_unit =
9812                 __cpu_to_le32(curr_migr_unit);
9813         super->migr_rec->rec_status = __cpu_to_le32(state);
9814         super->migr_rec->dest_1st_member_lba =
9815                 __cpu_to_le32(curr_migr_unit *
9816                               __le32_to_cpu(super->migr_rec->dest_depth_per_unit));
9817         if (write_imsm_migr_rec(st) < 0) {
9818                 dprintf("imsm: Cannot write migration record outside backup area\n");
9819                 return 1;
9820         }
9821
9822         return 0;
9823 }
9824
9825 /*******************************************************************************
9826  * Function:    recover_backup_imsm
9827  * Description: Function recovers critical data from the Migration Copy Area
9828  *              while assembling an array.
9829  * Parameters:
9830  *      super   : imsm internal array info
9831  *      info    : general array info
9832  * Returns:
9833  *      0 : success (or there is no data to recover)
9834  *      1 : fail
9835  ******************************************************************************/
9836 int recover_backup_imsm(struct supertype *st, struct mdinfo *info)
9837 {
9838         struct intel_super *super = st->sb;
9839         struct migr_record *migr_rec = super->migr_rec;
9840         struct imsm_map *map_dest;
9841         struct intel_dev *id = NULL;
9842         unsigned long long read_offset;
9843         unsigned long long write_offset;
9844         unsigned unit_len;
9845         int *targets = NULL;
9846         int new_disks, i, err;
9847         char *buf = NULL;
9848         int retval = 1;
9849         unsigned int sector_size = super->sector_size;
9850         unsigned long curr_migr_unit = __le32_to_cpu(migr_rec->curr_migr_unit);
9851         unsigned long num_migr_units = __le32_to_cpu(migr_rec->num_migr_units);
9852         char buffer[20];
9853         int skipped_disks = 0;
9854
9855         err = sysfs_get_str(info, NULL, "array_state", (char *)buffer, 20);
9856         if (err < 1)
9857                 return 1;
9858
9859         /* recover data only during assemblation */
9860         if (strncmp(buffer, "inactive", 8) != 0)
9861                 return 0;
9862         /* no data to recover */
9863         if (__le32_to_cpu(migr_rec->rec_status) == UNIT_SRC_NORMAL)
9864                 return 0;
9865         if (curr_migr_unit >= num_migr_units)
9866                 return 1;
9867
9868         /* find device during reshape */
9869         for (id = super->devlist; id; id = id->next)
9870                 if (is_gen_migration(id->dev))
9871                         break;
9872         if (id == NULL)
9873                 return 1;
9874
9875         map_dest = get_imsm_map(id->dev, MAP_0);
9876         new_disks = map_dest->num_members;
9877
9878         read_offset = (unsigned long long)
9879                         __le32_to_cpu(migr_rec->ckpt_area_pba) * 512;
9880
9881         write_offset = ((unsigned long long)
9882                         __le32_to_cpu(migr_rec->dest_1st_member_lba) +
9883                         pba_of_lba0(map_dest)) * 512;
9884
9885         unit_len = __le32_to_cpu(migr_rec->dest_depth_per_unit) * 512;
9886         if (posix_memalign((void **)&buf, sector_size, unit_len) != 0)
9887                 goto abort;
9888         targets = xcalloc(new_disks, sizeof(int));
9889
9890         if (open_backup_targets(info, new_disks, targets, super, id->dev)) {
9891                 pr_err("Cannot open some devices belonging to array.\n");
9892                 goto abort;
9893         }
9894
9895         for (i = 0; i < new_disks; i++) {
9896                 if (targets[i] < 0) {
9897                         skipped_disks++;
9898                         continue;
9899                 }
9900                 if (lseek64(targets[i], read_offset, SEEK_SET) < 0) {
9901                         pr_err("Cannot seek to block: %s\n",
9902                                strerror(errno));
9903                         skipped_disks++;
9904                         continue;
9905                 }
9906                 if ((unsigned)read(targets[i], buf, unit_len) != unit_len) {
9907                         pr_err("Cannot read copy area block: %s\n",
9908                                strerror(errno));
9909                         skipped_disks++;
9910                         continue;
9911                 }
9912                 if (lseek64(targets[i], write_offset, SEEK_SET) < 0) {
9913                         pr_err("Cannot seek to block: %s\n",
9914                                strerror(errno));
9915                         skipped_disks++;
9916                         continue;
9917                 }
9918                 if ((unsigned)write(targets[i], buf, unit_len) != unit_len) {
9919                         pr_err("Cannot restore block: %s\n",
9920                                strerror(errno));
9921                         skipped_disks++;
9922                         continue;
9923                 }
9924         }
9925
9926         if (skipped_disks > imsm_get_allowed_degradation(info->new_level,
9927                                                          new_disks,
9928                                                          super,
9929                                                          id->dev)) {
9930                 pr_err("Cannot restore data from backup. Too many failed disks\n");
9931                 goto abort;
9932         }
9933
9934         if (save_checkpoint_imsm(st, info, UNIT_SRC_NORMAL)) {
9935                 /* ignore error == 2, this can mean end of reshape here
9936                  */
9937                 dprintf("imsm: Cannot write checkpoint to migration record (UNIT_SRC_NORMAL) during restart\n");
9938         } else
9939                 retval = 0;
9940
9941 abort:
9942         if (targets) {
9943                 for (i = 0; i < new_disks; i++)
9944                         if (targets[i])
9945                                 close(targets[i]);
9946                 free(targets);
9947         }
9948         free(buf);
9949         return retval;
9950 }
9951
9952 static char disk_by_path[] = "/dev/disk/by-path/";
9953
9954 static const char *imsm_get_disk_controller_domain(const char *path)
9955 {
9956         char disk_path[PATH_MAX];
9957         char *drv=NULL;
9958         struct stat st;
9959
9960         strcpy(disk_path, disk_by_path);
9961         strncat(disk_path, path, PATH_MAX - strlen(disk_path) - 1);
9962         if (stat(disk_path, &st) == 0) {
9963                 struct sys_dev* hba;
9964                 char *path;
9965
9966                 path = devt_to_devpath(st.st_rdev);
9967                 if (path == NULL)
9968                         return "unknown";
9969                 hba = find_disk_attached_hba(-1, path);
9970                 if (hba && hba->type == SYS_DEV_SAS)
9971                         drv = "isci";
9972                 else if (hba && hba->type == SYS_DEV_SATA)
9973                         drv = "ahci";
9974                 else
9975                         drv = "unknown";
9976                 dprintf("path: %s hba: %s attached: %s\n",
9977                         path, (hba) ? hba->path : "NULL", drv);
9978                 free(path);
9979         }
9980         return drv;
9981 }
9982
9983 static char *imsm_find_array_devnm_by_subdev(int subdev, char *container)
9984 {
9985         static char devnm[32];
9986         char subdev_name[20];
9987         struct mdstat_ent *mdstat;
9988
9989         sprintf(subdev_name, "%d", subdev);
9990         mdstat = mdstat_by_subdev(subdev_name, container);
9991         if (!mdstat)
9992                 return NULL;
9993
9994         strcpy(devnm, mdstat->devnm);
9995         free_mdstat(mdstat);
9996         return devnm;
9997 }
9998
9999 static int imsm_reshape_is_allowed_on_container(struct supertype *st,
10000                                                 struct geo_params *geo,
10001                                                 int *old_raid_disks,
10002                                                 int direction)
10003 {
10004         /* currently we only support increasing the number of devices
10005          * for a container.  This increases the number of device for each
10006          * member array.  They must all be RAID0 or RAID5.
10007          */
10008         int ret_val = 0;
10009         struct mdinfo *info, *member;
10010         int devices_that_can_grow = 0;
10011
10012         dprintf("imsm: imsm_reshape_is_allowed_on_container(ENTER): st->devnm = (%s)\n", st->devnm);
10013
10014         if (geo->size > 0 ||
10015             geo->level != UnSet ||
10016             geo->layout != UnSet ||
10017             geo->chunksize != 0 ||
10018             geo->raid_disks == UnSet) {
10019                 dprintf("imsm: Container operation is allowed for raid disks number change only.\n");
10020                 return ret_val;
10021         }
10022
10023         if (direction == ROLLBACK_METADATA_CHANGES) {
10024                 dprintf("imsm: Metadata changes rollback is not supported for container operation.\n");
10025                 return ret_val;
10026         }
10027
10028         info = container_content_imsm(st, NULL);
10029         for (member = info; member; member = member->next) {
10030                 char *result;
10031
10032                 dprintf("imsm: checking device_num: %i\n",
10033                         member->container_member);
10034
10035                 if (geo->raid_disks <= member->array.raid_disks) {
10036                         /* we work on container for Online Capacity Expansion
10037                          * only so raid_disks has to grow
10038                          */
10039                         dprintf("imsm: for container operation raid disks increase is required\n");
10040                         break;
10041                 }
10042
10043                 if (info->array.level != 0 && info->array.level != 5) {
10044                         /* we cannot use this container with other raid level
10045                          */
10046                         dprintf("imsm: for container operation wrong raid level (%i) detected\n",
10047                                 info->array.level);
10048                         break;
10049                 } else {
10050                         /* check for platform support
10051                          * for this raid level configuration
10052                          */
10053                         struct intel_super *super = st->sb;
10054                         if (!is_raid_level_supported(super->orom,
10055                                                      member->array.level,
10056                                                      geo->raid_disks)) {
10057                                 dprintf("platform does not support raid%d with %d disk%s\n",
10058                                          info->array.level,
10059                                          geo->raid_disks,
10060                                          geo->raid_disks > 1 ? "s" : "");
10061                                 break;
10062                         }
10063                         /* check if component size is aligned to chunk size
10064                          */
10065                         if (info->component_size %
10066                             (info->array.chunk_size/512)) {
10067                                 dprintf("Component size is not aligned to chunk size\n");
10068                                 break;
10069                         }
10070                 }
10071
10072                 if (*old_raid_disks &&
10073                     info->array.raid_disks != *old_raid_disks)
10074                         break;
10075                 *old_raid_disks = info->array.raid_disks;
10076
10077                 /* All raid5 and raid0 volumes in container
10078                  * have to be ready for Online Capacity Expansion
10079                  * so they need to be assembled.  We have already
10080                  * checked that no recovery etc is happening.
10081                  */
10082                 result = imsm_find_array_devnm_by_subdev(member->container_member,
10083                                                          st->container_devnm);
10084                 if (result == NULL) {
10085                         dprintf("imsm: cannot find array\n");
10086                         break;
10087                 }
10088                 devices_that_can_grow++;
10089         }
10090         sysfs_free(info);
10091         if (!member && devices_that_can_grow)
10092                 ret_val = 1;
10093
10094         if (ret_val)
10095                 dprintf("Container operation allowed\n");
10096         else
10097                 dprintf("Error: %i\n", ret_val);
10098
10099         return ret_val;
10100 }
10101
10102 /* Function: get_spares_for_grow
10103  * Description: Allocates memory and creates list of spare devices
10104  *              avaliable in container. Checks if spare drive size is acceptable.
10105  * Parameters: Pointer to the supertype structure
10106  * Returns: Pointer to the list of spare devices (mdinfo structure) on success,
10107  *              NULL if fail
10108  */
10109 static struct mdinfo *get_spares_for_grow(struct supertype *st)
10110 {
10111         unsigned long long min_size = min_acceptable_spare_size_imsm(st);
10112         return container_choose_spares(st, min_size, NULL, NULL, NULL, 0);
10113 }
10114
10115 /******************************************************************************
10116  * function: imsm_create_metadata_update_for_reshape
10117  * Function creates update for whole IMSM container.
10118  *
10119  ******************************************************************************/
10120 static int imsm_create_metadata_update_for_reshape(
10121         struct supertype *st,
10122         struct geo_params *geo,
10123         int old_raid_disks,
10124         struct imsm_update_reshape **updatep)
10125 {
10126         struct intel_super *super = st->sb;
10127         struct imsm_super *mpb = super->anchor;
10128         int update_memory_size;
10129         struct imsm_update_reshape *u;
10130         struct mdinfo *spares;
10131         int i;
10132         int delta_disks;
10133         struct mdinfo *dev;
10134
10135         dprintf("(enter) raid_disks = %i\n", geo->raid_disks);
10136
10137         delta_disks = geo->raid_disks - old_raid_disks;
10138
10139         /* size of all update data without anchor */
10140         update_memory_size = sizeof(struct imsm_update_reshape);
10141
10142         /* now add space for spare disks that we need to add. */
10143         update_memory_size += sizeof(u->new_disks[0]) * (delta_disks - 1);
10144
10145         u = xcalloc(1, update_memory_size);
10146         u->type = update_reshape_container_disks;
10147         u->old_raid_disks = old_raid_disks;
10148         u->new_raid_disks = geo->raid_disks;
10149
10150         /* now get spare disks list
10151          */
10152         spares = get_spares_for_grow(st);
10153
10154         if (spares == NULL
10155             || delta_disks > spares->array.spare_disks) {
10156                 pr_err("imsm: ERROR: Cannot get spare devices for %s.\n", geo->dev_name);
10157                 i = -1;
10158                 goto abort;
10159         }
10160
10161         /* we have got spares
10162          * update disk list in imsm_disk list table in anchor
10163          */
10164         dprintf("imsm: %i spares are available.\n\n",
10165                 spares->array.spare_disks);
10166
10167         dev = spares->devs;
10168         for (i = 0; i < delta_disks; i++) {
10169                 struct dl *dl;
10170
10171                 if (dev == NULL)
10172                         break;
10173                 u->new_disks[i] = makedev(dev->disk.major,
10174                                           dev->disk.minor);
10175                 dl = get_disk_super(super, dev->disk.major, dev->disk.minor);
10176                 dl->index = mpb->num_disks;
10177                 mpb->num_disks++;
10178                 dev = dev->next;
10179         }
10180
10181 abort:
10182         /* free spares
10183          */
10184         sysfs_free(spares);
10185
10186         dprintf("imsm: reshape update preparation :");
10187         if (i == delta_disks) {
10188                 dprintf_cont(" OK\n");
10189                 *updatep = u;
10190                 return update_memory_size;
10191         }
10192         free(u);
10193         dprintf_cont(" Error\n");
10194
10195         return 0;
10196 }
10197
10198 /******************************************************************************
10199  * function: imsm_create_metadata_update_for_size_change()
10200  *           Creates update for IMSM array for array size change.
10201  *
10202  ******************************************************************************/
10203 static int imsm_create_metadata_update_for_size_change(
10204                                 struct supertype *st,
10205                                 struct geo_params *geo,
10206                                 struct imsm_update_size_change **updatep)
10207 {
10208         struct intel_super *super = st->sb;
10209         int update_memory_size;
10210         struct imsm_update_size_change *u;
10211
10212         dprintf("(enter) New size = %llu\n", geo->size);
10213
10214         /* size of all update data without anchor */
10215         update_memory_size = sizeof(struct imsm_update_size_change);
10216
10217         u = xcalloc(1, update_memory_size);
10218         u->type = update_size_change;
10219         u->subdev = super->current_vol;
10220         u->new_size = geo->size;
10221
10222         dprintf("imsm: reshape update preparation : OK\n");
10223         *updatep = u;
10224
10225         return update_memory_size;
10226 }
10227
10228 /******************************************************************************
10229  * function: imsm_create_metadata_update_for_migration()
10230  *           Creates update for IMSM array.
10231  *
10232  ******************************************************************************/
10233 static int imsm_create_metadata_update_for_migration(
10234                                         struct supertype *st,
10235                                         struct geo_params *geo,
10236                                         struct imsm_update_reshape_migration **updatep)
10237 {
10238         struct intel_super *super = st->sb;
10239         int update_memory_size;
10240         struct imsm_update_reshape_migration *u;
10241         struct imsm_dev *dev;
10242         int previous_level = -1;
10243
10244         dprintf("(enter) New Level = %i\n", geo->level);
10245
10246         /* size of all update data without anchor */
10247         update_memory_size = sizeof(struct imsm_update_reshape_migration);
10248
10249         u = xcalloc(1, update_memory_size);
10250         u->type = update_reshape_migration;
10251         u->subdev = super->current_vol;
10252         u->new_level = geo->level;
10253         u->new_layout = geo->layout;
10254         u->new_raid_disks = u->old_raid_disks = geo->raid_disks;
10255         u->new_disks[0] = -1;
10256         u->new_chunksize = -1;
10257
10258         dev = get_imsm_dev(super, u->subdev);
10259         if (dev) {
10260                 struct imsm_map *map;
10261
10262                 map = get_imsm_map(dev, MAP_0);
10263                 if (map) {
10264                         int current_chunk_size =
10265                                 __le16_to_cpu(map->blocks_per_strip) / 2;
10266
10267                         if (geo->chunksize != current_chunk_size) {
10268                                 u->new_chunksize = geo->chunksize / 1024;
10269                                 dprintf("imsm: chunk size change from %i to %i\n",
10270                                         current_chunk_size, u->new_chunksize);
10271                         }
10272                         previous_level = map->raid_level;
10273                 }
10274         }
10275         if (geo->level == 5 && previous_level == 0) {
10276                 struct mdinfo *spares = NULL;
10277
10278                 u->new_raid_disks++;
10279                 spares = get_spares_for_grow(st);
10280                 if (spares == NULL || spares->array.spare_disks < 1) {
10281                         free(u);
10282                         sysfs_free(spares);
10283                         update_memory_size = 0;
10284                         dprintf("error: cannot get spare device for requested migration");
10285                         return 0;
10286                 }
10287                 sysfs_free(spares);
10288         }
10289         dprintf("imsm: reshape update preparation : OK\n");
10290         *updatep = u;
10291
10292         return update_memory_size;
10293 }
10294
10295 static void imsm_update_metadata_locally(struct supertype *st,
10296                                          void *buf, int len)
10297 {
10298         struct metadata_update mu;
10299
10300         mu.buf = buf;
10301         mu.len = len;
10302         mu.space = NULL;
10303         mu.space_list = NULL;
10304         mu.next = NULL;
10305         if (imsm_prepare_update(st, &mu))
10306                 imsm_process_update(st, &mu);
10307
10308         while (mu.space_list) {
10309                 void **space = mu.space_list;
10310                 mu.space_list = *space;
10311                 free(space);
10312         }
10313 }
10314
10315 /***************************************************************************
10316 * Function:     imsm_analyze_change
10317 * Description:  Function analyze change for single volume
10318 *               and validate if transition is supported
10319 * Parameters:   Geometry parameters, supertype structure,
10320 *               metadata change direction (apply/rollback)
10321 * Returns:      Operation type code on success, -1 if fail
10322 ****************************************************************************/
10323 enum imsm_reshape_type imsm_analyze_change(struct supertype *st,
10324                                            struct geo_params *geo,
10325                                            int direction)
10326 {
10327         struct mdinfo info;
10328         int change = -1;
10329         int check_devs = 0;
10330         int chunk;
10331         /* number of added/removed disks in operation result */
10332         int devNumChange = 0;
10333         /* imsm compatible layout value for array geometry verification */
10334         int imsm_layout = -1;
10335         int data_disks;
10336         struct imsm_dev *dev;
10337         struct intel_super *super;
10338         unsigned long long current_size;
10339         unsigned long long free_size;
10340         unsigned long long max_size;
10341         int rv;
10342
10343         getinfo_super_imsm_volume(st, &info, NULL);
10344         if (geo->level != info.array.level && geo->level >= 0 &&
10345             geo->level != UnSet) {
10346                 switch (info.array.level) {
10347                 case 0:
10348                         if (geo->level == 5) {
10349                                 change = CH_MIGRATION;
10350                                 if (geo->layout != ALGORITHM_LEFT_ASYMMETRIC) {
10351                                         pr_err("Error. Requested Layout not supported (left-asymmetric layout is supported only)!\n");
10352                                         change = -1;
10353                                         goto analyse_change_exit;
10354                                 }
10355                                 imsm_layout =  geo->layout;
10356                                 check_devs = 1;
10357                                 devNumChange = 1; /* parity disk added */
10358                         } else if (geo->level == 10) {
10359                                 change = CH_TAKEOVER;
10360                                 check_devs = 1;
10361                                 devNumChange = 2; /* two mirrors added */
10362                                 imsm_layout = 0x102; /* imsm supported layout */
10363                         }
10364                         break;
10365                 case 1:
10366                 case 10:
10367                         if (geo->level == 0) {
10368                                 change = CH_TAKEOVER;
10369                                 check_devs = 1;
10370                                 devNumChange = -(geo->raid_disks/2);
10371                                 imsm_layout = 0; /* imsm raid0 layout */
10372                         }
10373                         break;
10374                 }
10375                 if (change == -1) {
10376                         pr_err("Error. Level Migration from %d to %d not supported!\n",
10377                                info.array.level, geo->level);
10378                         goto analyse_change_exit;
10379                 }
10380         } else
10381                 geo->level = info.array.level;
10382
10383         if (geo->layout != info.array.layout &&
10384             (geo->layout != UnSet && geo->layout != -1)) {
10385                 change = CH_MIGRATION;
10386                 if (info.array.layout == 0 && info.array.level == 5 &&
10387                     geo->layout == 5) {
10388                         /* reshape 5 -> 4 */
10389                 } else if (info.array.layout == 5 && info.array.level == 5 &&
10390                            geo->layout == 0) {
10391                         /* reshape 4 -> 5 */
10392                         geo->layout = 0;
10393                         geo->level = 5;
10394                 } else {
10395                         pr_err("Error. Layout Migration from %d to %d not supported!\n",
10396                                info.array.layout, geo->layout);
10397                         change = -1;
10398                         goto analyse_change_exit;
10399                 }
10400         } else {
10401                 geo->layout = info.array.layout;
10402                 if (imsm_layout == -1)
10403                         imsm_layout = info.array.layout;
10404         }
10405
10406         if (geo->chunksize > 0 && geo->chunksize != UnSet &&
10407             geo->chunksize != info.array.chunk_size) {
10408                 if (info.array.level == 10) {
10409                         pr_err("Error. Chunk size change for RAID 10 is not supported.\n");
10410                         change = -1;
10411                         goto analyse_change_exit;
10412                 }
10413                 change = CH_MIGRATION;
10414         } else {
10415                 geo->chunksize = info.array.chunk_size;
10416         }
10417
10418         chunk = geo->chunksize / 1024;
10419
10420         super = st->sb;
10421         dev = get_imsm_dev(super, super->current_vol);
10422         data_disks = imsm_num_data_members(dev , MAP_0);
10423         /* compute current size per disk member
10424          */
10425         current_size = info.custom_array_size / data_disks;
10426
10427         if (geo->size > 0 && geo->size != MAX_SIZE) {
10428                 /* align component size
10429                  */
10430                 geo->size = imsm_component_size_aligment_check(
10431                                     get_imsm_raid_level(dev->vol.map),
10432                                     chunk * 1024, super->sector_size,
10433                                     geo->size * 2);
10434                 if (geo->size == 0) {
10435                         pr_err("Error. Size expansion is supported only (current size is %llu, requested size /rounded/ is 0).\n",
10436                                    current_size);
10437                         goto analyse_change_exit;
10438                 }
10439         }
10440
10441         if (current_size != geo->size && geo->size > 0) {
10442                 if (change != -1) {
10443                         pr_err("Error. Size change should be the only one at a time.\n");
10444                         change = -1;
10445                         goto analyse_change_exit;
10446                 }
10447                 if ((super->current_vol + 1) != super->anchor->num_raid_devs) {
10448                         pr_err("Error. The last volume in container can be expanded only (%i/%s).\n",
10449                                super->current_vol, st->devnm);
10450                         goto analyse_change_exit;
10451                 }
10452                 /* check the maximum available size
10453                  */
10454                 rv =  imsm_get_free_size(st, dev->vol.map->num_members,
10455                                          0, chunk, &free_size);
10456                 if (rv == 0)
10457                         /* Cannot find maximum available space
10458                          */
10459                         max_size = 0;
10460                 else {
10461                         max_size = free_size + current_size;
10462                         /* align component size
10463                          */
10464                         max_size = imsm_component_size_aligment_check(
10465                                         get_imsm_raid_level(dev->vol.map),
10466                                         chunk * 1024, super->sector_size,
10467                                         max_size);
10468                 }
10469                 if (geo->size == MAX_SIZE) {
10470                         /* requested size change to the maximum available size
10471                          */
10472                         if (max_size == 0) {
10473                                 pr_err("Error. Cannot find maximum available space.\n");
10474                                 change = -1;
10475                                 goto analyse_change_exit;
10476                         } else
10477                                 geo->size = max_size;
10478                 }
10479
10480                 if (direction == ROLLBACK_METADATA_CHANGES) {
10481                         /* accept size for rollback only
10482                         */
10483                 } else {
10484                         /* round size due to metadata compatibility
10485                         */
10486                         geo->size = (geo->size >> SECT_PER_MB_SHIFT)
10487                                     << SECT_PER_MB_SHIFT;
10488                         dprintf("Prepare update for size change to %llu\n",
10489                                 geo->size );
10490                         if (current_size >= geo->size) {
10491                                 pr_err("Error. Size expansion is supported only (current size is %llu, requested size /rounded/ is %llu).\n",
10492                                        current_size, geo->size);
10493                                 goto analyse_change_exit;
10494                         }
10495                         if (max_size && geo->size > max_size) {
10496                                 pr_err("Error. Requested size is larger than maximum available size (maximum available size is %llu, requested size /rounded/ is %llu).\n",
10497                                        max_size, geo->size);
10498                                 goto analyse_change_exit;
10499                         }
10500                 }
10501                 geo->size *= data_disks;
10502                 geo->raid_disks = dev->vol.map->num_members;
10503                 change = CH_ARRAY_SIZE;
10504         }
10505         if (!validate_geometry_imsm(st,
10506                                     geo->level,
10507                                     imsm_layout,
10508                                     geo->raid_disks + devNumChange,
10509                                     &chunk,
10510                                     geo->size, INVALID_SECTORS,
10511                                     0, 0, 1))
10512                 change = -1;
10513
10514         if (check_devs) {
10515                 struct intel_super *super = st->sb;
10516                 struct imsm_super *mpb = super->anchor;
10517
10518                 if (mpb->num_raid_devs > 1) {
10519                         pr_err("Error. Cannot perform operation on %s- for this operation it MUST be single array in container\n",
10520                                geo->dev_name);
10521                         change = -1;
10522                 }
10523         }
10524
10525 analyse_change_exit:
10526         if (direction == ROLLBACK_METADATA_CHANGES &&
10527             (change == CH_MIGRATION || change == CH_TAKEOVER)) {
10528                 dprintf("imsm: Metadata changes rollback is not supported for migration and takeover operations.\n");
10529                 change = -1;
10530         }
10531         return change;
10532 }
10533
10534 int imsm_takeover(struct supertype *st, struct geo_params *geo)
10535 {
10536         struct intel_super *super = st->sb;
10537         struct imsm_update_takeover *u;
10538
10539         u = xmalloc(sizeof(struct imsm_update_takeover));
10540
10541         u->type = update_takeover;
10542         u->subarray = super->current_vol;
10543
10544         /* 10->0 transition */
10545         if (geo->level == 0)
10546                 u->direction = R10_TO_R0;
10547
10548         /* 0->10 transition */
10549         if (geo->level == 10)
10550                 u->direction = R0_TO_R10;
10551
10552         /* update metadata locally */
10553         imsm_update_metadata_locally(st, u,
10554                                         sizeof(struct imsm_update_takeover));
10555         /* and possibly remotely */
10556         if (st->update_tail)
10557                 append_metadata_update(st, u,
10558                                         sizeof(struct imsm_update_takeover));
10559         else
10560                 free(u);
10561
10562         return 0;
10563 }
10564
10565 static int imsm_reshape_super(struct supertype *st, unsigned long long size,
10566                               int level,
10567                               int layout, int chunksize, int raid_disks,
10568                               int delta_disks, char *backup, char *dev,
10569                               int direction, int verbose)
10570 {
10571         int ret_val = 1;
10572         struct geo_params geo;
10573
10574         dprintf("(enter)\n");
10575
10576         memset(&geo, 0, sizeof(struct geo_params));
10577
10578         geo.dev_name = dev;
10579         strcpy(geo.devnm, st->devnm);
10580         geo.size = size;
10581         geo.level = level;
10582         geo.layout = layout;
10583         geo.chunksize = chunksize;
10584         geo.raid_disks = raid_disks;
10585         if (delta_disks != UnSet)
10586                 geo.raid_disks += delta_disks;
10587
10588         dprintf("for level      : %i\n", geo.level);
10589         dprintf("for raid_disks : %i\n", geo.raid_disks);
10590
10591         if (experimental() == 0)
10592                 return ret_val;
10593
10594         if (strcmp(st->container_devnm, st->devnm) == 0) {
10595                 /* On container level we can only increase number of devices. */
10596                 dprintf("imsm: info: Container operation\n");
10597                 int old_raid_disks = 0;
10598
10599                 if (imsm_reshape_is_allowed_on_container(
10600                             st, &geo, &old_raid_disks, direction)) {
10601                         struct imsm_update_reshape *u = NULL;
10602                         int len;
10603
10604                         len = imsm_create_metadata_update_for_reshape(
10605                                 st, &geo, old_raid_disks, &u);
10606
10607                         if (len <= 0) {
10608                                 dprintf("imsm: Cannot prepare update\n");
10609                                 goto exit_imsm_reshape_super;
10610                         }
10611
10612                         ret_val = 0;
10613                         /* update metadata locally */
10614                         imsm_update_metadata_locally(st, u, len);
10615                         /* and possibly remotely */
10616                         if (st->update_tail)
10617                                 append_metadata_update(st, u, len);
10618                         else
10619                                 free(u);
10620
10621                 } else {
10622                         pr_err("(imsm) Operation is not allowed on this container\n");
10623                 }
10624         } else {
10625                 /* On volume level we support following operations
10626                  * - takeover: raid10 -> raid0; raid0 -> raid10
10627                  * - chunk size migration
10628                  * - migration: raid5 -> raid0; raid0 -> raid5
10629                  */
10630                 struct intel_super *super = st->sb;
10631                 struct intel_dev *dev = super->devlist;
10632                 int change;
10633                 dprintf("imsm: info: Volume operation\n");
10634                 /* find requested device */
10635                 while (dev) {
10636                         char *devnm =
10637                                 imsm_find_array_devnm_by_subdev(
10638                                         dev->index, st->container_devnm);
10639                         if (devnm && strcmp(devnm, geo.devnm) == 0)
10640                                 break;
10641                         dev = dev->next;
10642                 }
10643                 if (dev == NULL) {
10644                         pr_err("Cannot find %s (%s) subarray\n",
10645                                 geo.dev_name, geo.devnm);
10646                         goto exit_imsm_reshape_super;
10647                 }
10648                 super->current_vol = dev->index;
10649                 change = imsm_analyze_change(st, &geo, direction);
10650                 switch (change) {
10651                 case CH_TAKEOVER:
10652                         ret_val = imsm_takeover(st, &geo);
10653                         break;
10654                 case CH_MIGRATION: {
10655                         struct imsm_update_reshape_migration *u = NULL;
10656                         int len =
10657                                 imsm_create_metadata_update_for_migration(
10658                                         st, &geo, &u);
10659                         if (len < 1) {
10660                                 dprintf("imsm: Cannot prepare update\n");
10661                                 break;
10662                         }
10663                         ret_val = 0;
10664                         /* update metadata locally */
10665                         imsm_update_metadata_locally(st, u, len);
10666                         /* and possibly remotely */
10667                         if (st->update_tail)
10668                                 append_metadata_update(st, u, len);
10669                         else
10670                                 free(u);
10671                 }
10672                 break;
10673                 case CH_ARRAY_SIZE: {
10674                         struct imsm_update_size_change *u = NULL;
10675                         int len =
10676                                 imsm_create_metadata_update_for_size_change(
10677                                         st, &geo, &u);
10678                         if (len < 1) {
10679                                 dprintf("imsm: Cannot prepare update\n");
10680                                 break;
10681                         }
10682                         ret_val = 0;
10683                         /* update metadata locally */
10684                         imsm_update_metadata_locally(st, u, len);
10685                         /* and possibly remotely */
10686                         if (st->update_tail)
10687                                 append_metadata_update(st, u, len);
10688                         else
10689                                 free(u);
10690                 }
10691                 break;
10692                 default:
10693                         ret_val = 1;
10694                 }
10695         }
10696
10697 exit_imsm_reshape_super:
10698         dprintf("imsm: reshape_super Exit code = %i\n", ret_val);
10699         return ret_val;
10700 }
10701
10702 #define COMPLETED_OK            0
10703 #define COMPLETED_NONE          1
10704 #define COMPLETED_DELAYED       2
10705
10706 static int read_completed(int fd, unsigned long long *val)
10707 {
10708         int ret;
10709         char buf[50];
10710
10711         ret = sysfs_fd_get_str(fd, buf, 50);
10712         if (ret < 0)
10713                 return ret;
10714
10715         ret = COMPLETED_OK;
10716         if (strncmp(buf, "none", 4) == 0) {
10717                 ret = COMPLETED_NONE;
10718         } else if (strncmp(buf, "delayed", 7) == 0) {
10719                 ret = COMPLETED_DELAYED;
10720         } else {
10721                 char *ep;
10722                 *val = strtoull(buf, &ep, 0);
10723                 if (ep == buf || (*ep != 0 && *ep != '\n' && *ep != ' '))
10724                         ret = -1;
10725         }
10726         return ret;
10727 }
10728
10729 /*******************************************************************************
10730  * Function:    wait_for_reshape_imsm
10731  * Description: Function writes new sync_max value and waits until
10732  *              reshape process reach new position
10733  * Parameters:
10734  *      sra             : general array info
10735  *      ndata           : number of disks in new array's layout
10736  * Returns:
10737  *       0 : success,
10738  *       1 : there is no reshape in progress,
10739  *      -1 : fail
10740  ******************************************************************************/
10741 int wait_for_reshape_imsm(struct mdinfo *sra, int ndata)
10742 {
10743         int fd = sysfs_get_fd(sra, NULL, "sync_completed");
10744         int retry = 3;
10745         unsigned long long completed;
10746         /* to_complete : new sync_max position */
10747         unsigned long long to_complete = sra->reshape_progress;
10748         unsigned long long position_to_set = to_complete / ndata;
10749
10750         if (fd < 0) {
10751                 dprintf("cannot open reshape_position\n");
10752                 return 1;
10753         }
10754
10755         do {
10756                 if (sysfs_fd_get_ll(fd, &completed) < 0) {
10757                         if (!retry) {
10758                                 dprintf("cannot read reshape_position (no reshape in progres)\n");
10759                                 close(fd);
10760                                 return 1;
10761                         }
10762                         usleep(30000);
10763                 } else
10764                         break;
10765         } while (retry--);
10766
10767         if (completed > position_to_set) {
10768                 dprintf("wrong next position to set %llu (%llu)\n",
10769                         to_complete, position_to_set);
10770                 close(fd);
10771                 return -1;
10772         }
10773         dprintf("Position set: %llu\n", position_to_set);
10774         if (sysfs_set_num(sra, NULL, "sync_max",
10775                           position_to_set) != 0) {
10776                 dprintf("cannot set reshape position to %llu\n",
10777                         position_to_set);
10778                 close(fd);
10779                 return -1;
10780         }
10781
10782         do {
10783                 int rc;
10784                 char action[20];
10785                 int timeout = 3000;
10786
10787                 sysfs_wait(fd, &timeout);
10788                 if (sysfs_get_str(sra, NULL, "sync_action",
10789                                   action, 20) > 0 &&
10790                                 strncmp(action, "reshape", 7) != 0) {
10791                         if (strncmp(action, "idle", 4) == 0)
10792                                 break;
10793                         close(fd);
10794                         return -1;
10795                 }
10796
10797                 rc = read_completed(fd, &completed);
10798                 if (rc < 0) {
10799                         dprintf("cannot read reshape_position (in loop)\n");
10800                         close(fd);
10801                         return 1;
10802                 } else if (rc == COMPLETED_NONE)
10803                         break;
10804         } while (completed < position_to_set);
10805
10806         close(fd);
10807         return 0;
10808 }
10809
10810 /*******************************************************************************
10811  * Function:    check_degradation_change
10812  * Description: Check that array hasn't become failed.
10813  * Parameters:
10814  *      info    : for sysfs access
10815  *      sources : source disks descriptors
10816  *      degraded: previous degradation level
10817  * Returns:
10818  *      degradation level
10819  ******************************************************************************/
10820 int check_degradation_change(struct mdinfo *info,
10821                              int *sources,
10822                              int degraded)
10823 {
10824         unsigned long long new_degraded;
10825         int rv;
10826
10827         rv = sysfs_get_ll(info, NULL, "degraded", &new_degraded);
10828         if (rv == -1 || (new_degraded != (unsigned long long)degraded)) {
10829                 /* check each device to ensure it is still working */
10830                 struct mdinfo *sd;
10831                 new_degraded = 0;
10832                 for (sd = info->devs ; sd ; sd = sd->next) {
10833                         if (sd->disk.state & (1<<MD_DISK_FAULTY))
10834                                 continue;
10835                         if (sd->disk.state & (1<<MD_DISK_SYNC)) {
10836                                 char sbuf[100];
10837
10838                                 if (sysfs_get_str(info,
10839                                         sd, "state", sbuf, sizeof(sbuf)) < 0 ||
10840                                         strstr(sbuf, "faulty") ||
10841                                         strstr(sbuf, "in_sync") == NULL) {
10842                                         /* this device is dead */
10843                                         sd->disk.state = (1<<MD_DISK_FAULTY);
10844                                         if (sd->disk.raid_disk >= 0 &&
10845                                             sources[sd->disk.raid_disk] >= 0) {
10846                                                 close(sources[
10847                                                         sd->disk.raid_disk]);
10848                                                 sources[sd->disk.raid_disk] =
10849                                                         -1;
10850                                         }
10851                                         new_degraded++;
10852                                 }
10853                         }
10854                 }
10855         }
10856
10857         return new_degraded;
10858 }
10859
10860 /*******************************************************************************
10861  * Function:    imsm_manage_reshape
10862  * Description: Function finds array under reshape and it manages reshape
10863  *              process. It creates stripes backups (if required) and sets
10864  *              checkpoints.
10865  * Parameters:
10866  *      afd             : Backup handle (nattive) - not used
10867  *      sra             : general array info
10868  *      reshape         : reshape parameters - not used
10869  *      st              : supertype structure
10870  *      blocks          : size of critical section [blocks]
10871  *      fds             : table of source device descriptor
10872  *      offsets         : start of array (offest per devices)
10873  *      dests           : not used
10874  *      destfd          : table of destination device descriptor
10875  *      destoffsets     : table of destination offsets (per device)
10876  * Returns:
10877  *      1 : success, reshape is done
10878  *      0 : fail
10879  ******************************************************************************/
10880 static int imsm_manage_reshape(
10881         int afd, struct mdinfo *sra, struct reshape *reshape,
10882         struct supertype *st, unsigned long backup_blocks,
10883         int *fds, unsigned long long *offsets,
10884         int dests, int *destfd, unsigned long long *destoffsets)
10885 {
10886         int ret_val = 0;
10887         struct intel_super *super = st->sb;
10888         struct intel_dev *dv;
10889         unsigned int sector_size = super->sector_size;
10890         struct imsm_dev *dev = NULL;
10891         struct imsm_map *map_src;
10892         int migr_vol_qan = 0;
10893         int ndata, odata; /* [bytes] */
10894         int chunk; /* [bytes] */
10895         struct migr_record *migr_rec;
10896         char *buf = NULL;
10897         unsigned int buf_size; /* [bytes] */
10898         unsigned long long max_position; /* array size [bytes] */
10899         unsigned long long next_step; /* [blocks]/[bytes] */
10900         unsigned long long old_data_stripe_length;
10901         unsigned long long start_src; /* [bytes] */
10902         unsigned long long start; /* [bytes] */
10903         unsigned long long start_buf_shift; /* [bytes] */
10904         int degraded = 0;
10905         int source_layout = 0;
10906
10907         if (!sra)
10908                 return ret_val;
10909
10910         if (!fds || !offsets)
10911                 goto abort;
10912
10913         /* Find volume during the reshape */
10914         for (dv = super->devlist; dv; dv = dv->next) {
10915                 if (dv->dev->vol.migr_type == MIGR_GEN_MIGR
10916                     && dv->dev->vol.migr_state == 1) {
10917                         dev = dv->dev;
10918                         migr_vol_qan++;
10919                 }
10920         }
10921         /* Only one volume can migrate at the same time */
10922         if (migr_vol_qan != 1) {
10923                 pr_err("%s", migr_vol_qan ?
10924                         "Number of migrating volumes greater than 1\n" :
10925                         "There is no volume during migrationg\n");
10926                 goto abort;
10927         }
10928
10929         map_src = get_imsm_map(dev, MAP_1);
10930         if (map_src == NULL)
10931                 goto abort;
10932
10933         ndata = imsm_num_data_members(dev, MAP_0);
10934         odata = imsm_num_data_members(dev, MAP_1);
10935
10936         chunk = __le16_to_cpu(map_src->blocks_per_strip) * 512;
10937         old_data_stripe_length = odata * chunk;
10938
10939         migr_rec = super->migr_rec;
10940
10941         /* initialize migration record for start condition */
10942         if (sra->reshape_progress == 0)
10943                 init_migr_record_imsm(st, dev, sra);
10944         else {
10945                 if (__le32_to_cpu(migr_rec->rec_status) != UNIT_SRC_NORMAL) {
10946                         dprintf("imsm: cannot restart migration when data are present in copy area.\n");
10947                         goto abort;
10948                 }
10949                 /* Save checkpoint to update migration record for current
10950                  * reshape position (in md). It can be farther than current
10951                  * reshape position in metadata.
10952                  */
10953                 if (save_checkpoint_imsm(st, sra, UNIT_SRC_NORMAL) == 1) {
10954                         /* ignore error == 2, this can mean end of reshape here
10955                          */
10956                         dprintf("imsm: Cannot write checkpoint to migration record (UNIT_SRC_NORMAL, initial save)\n");
10957                         goto abort;
10958                 }
10959         }
10960
10961         /* size for data */
10962         buf_size = __le32_to_cpu(migr_rec->blocks_per_unit) * 512;
10963         /* extend  buffer size for parity disk */
10964         buf_size += __le32_to_cpu(migr_rec->dest_depth_per_unit) * 512;
10965         /* add space for stripe aligment */
10966         buf_size += old_data_stripe_length;
10967         if (posix_memalign((void **)&buf, MAX_SECTOR_SIZE, buf_size)) {
10968                 dprintf("imsm: Cannot allocate checkpoint buffer\n");
10969                 goto abort;
10970         }
10971
10972         max_position = sra->component_size * ndata;
10973         source_layout = imsm_level_to_layout(map_src->raid_level);
10974
10975         while (__le32_to_cpu(migr_rec->curr_migr_unit) <
10976                __le32_to_cpu(migr_rec->num_migr_units)) {
10977                 /* current reshape position [blocks] */
10978                 unsigned long long current_position =
10979                         __le32_to_cpu(migr_rec->blocks_per_unit)
10980                         * __le32_to_cpu(migr_rec->curr_migr_unit);
10981                 unsigned long long border;
10982
10983                 /* Check that array hasn't become failed.
10984                  */
10985                 degraded = check_degradation_change(sra, fds, degraded);
10986                 if (degraded > 1) {
10987                         dprintf("imsm: Abort reshape due to degradation level (%i)\n", degraded);
10988                         goto abort;
10989                 }
10990
10991                 next_step = __le32_to_cpu(migr_rec->blocks_per_unit);
10992
10993                 if ((current_position + next_step) > max_position)
10994                         next_step = max_position - current_position;
10995
10996                 start = current_position * 512;
10997
10998                 /* align reading start to old geometry */
10999                 start_buf_shift = start % old_data_stripe_length;
11000                 start_src = start - start_buf_shift;
11001
11002                 border = (start_src / odata) - (start / ndata);
11003                 border /= 512;
11004                 if (border <= __le32_to_cpu(migr_rec->dest_depth_per_unit)) {
11005                         /* save critical stripes to buf
11006                          * start     - start address of current unit
11007                          *             to backup [bytes]
11008                          * start_src - start address of current unit
11009                          *             to backup alligned to source array
11010                          *             [bytes]
11011                          */
11012                         unsigned long long next_step_filler;
11013                         unsigned long long copy_length = next_step * 512;
11014
11015                         /* allign copy area length to stripe in old geometry */
11016                         next_step_filler = ((copy_length + start_buf_shift)
11017                                             % old_data_stripe_length);
11018                         if (next_step_filler)
11019                                 next_step_filler = (old_data_stripe_length
11020                                                     - next_step_filler);
11021                         dprintf("save_stripes() parameters: start = %llu,\tstart_src = %llu,\tnext_step*512 = %llu,\tstart_in_buf_shift = %llu,\tnext_step_filler = %llu\n",
11022                                 start, start_src, copy_length,
11023                                 start_buf_shift, next_step_filler);
11024
11025                         if (save_stripes(fds, offsets, map_src->num_members,
11026                                          chunk, map_src->raid_level,
11027                                          source_layout, 0, NULL, start_src,
11028                                          copy_length +
11029                                          next_step_filler + start_buf_shift,
11030                                          buf)) {
11031                                 dprintf("imsm: Cannot save stripes to buffer\n");
11032                                 goto abort;
11033                         }
11034                         /* Convert data to destination format and store it
11035                          * in backup general migration area
11036                          */
11037                         if (save_backup_imsm(st, dev, sra,
11038                                 buf + start_buf_shift, copy_length)) {
11039                                 dprintf("imsm: Cannot save stripes to target devices\n");
11040                                 goto abort;
11041                         }
11042                         if (save_checkpoint_imsm(st, sra,
11043                                                  UNIT_SRC_IN_CP_AREA)) {
11044                                 dprintf("imsm: Cannot write checkpoint to migration record (UNIT_SRC_IN_CP_AREA)\n");
11045                                 goto abort;
11046                         }
11047                 } else {
11048                         /* set next step to use whole border area */
11049                         border /= next_step;
11050                         if (border > 1)
11051                                 next_step *= border;
11052                 }
11053                 /* When data backed up, checkpoint stored,
11054                  * kick the kernel to reshape unit of data
11055                  */
11056                 next_step = next_step + sra->reshape_progress;
11057                 /* limit next step to array max position */
11058                 if (next_step > max_position)
11059                         next_step = max_position;
11060                 sysfs_set_num(sra, NULL, "suspend_lo", sra->reshape_progress);
11061                 sysfs_set_num(sra, NULL, "suspend_hi", next_step);
11062                 sra->reshape_progress = next_step;
11063
11064                 /* wait until reshape finish */
11065                 if (wait_for_reshape_imsm(sra, ndata)) {
11066                         dprintf("wait_for_reshape_imsm returned error!\n");
11067                         goto abort;
11068                 }
11069                 if (sigterm)
11070                         goto abort;
11071
11072                 if (save_checkpoint_imsm(st, sra, UNIT_SRC_NORMAL) == 1) {
11073                         /* ignore error == 2, this can mean end of reshape here
11074                          */
11075                         dprintf("imsm: Cannot write checkpoint to migration record (UNIT_SRC_NORMAL)\n");
11076                         goto abort;
11077                 }
11078
11079         }
11080
11081         /* clear migr_rec on disks after successful migration */
11082         struct dl *d;
11083
11084         memset(super->migr_rec_buf, 0, MIGR_REC_BUF_SECTORS*sector_size);
11085         for (d = super->disks; d; d = d->next) {
11086                 if (d->index < 0 || is_failed(&d->disk))
11087                         continue;
11088                 unsigned long long dsize;
11089
11090                 get_dev_size(d->fd, NULL, &dsize);
11091                 if (lseek64(d->fd, dsize - MIGR_REC_SECTOR_POSITION*sector_size,
11092                             SEEK_SET) >= 0) {
11093                         if (write(d->fd, super->migr_rec_buf,
11094                             MIGR_REC_BUF_SECTORS*sector_size) !=
11095                             MIGR_REC_BUF_SECTORS*sector_size)
11096                                 perror("Write migr_rec failed");
11097                 }
11098         }
11099
11100         /* return '1' if done */
11101         ret_val = 1;
11102 abort:
11103         free(buf);
11104         /* See Grow.c: abort_reshape() for further explanation */
11105         sysfs_set_num(sra, NULL, "suspend_lo", 0x7FFFFFFFFFFFFFFFULL);
11106         sysfs_set_num(sra, NULL, "suspend_hi", 0);
11107         sysfs_set_num(sra, NULL, "suspend_lo", 0);
11108
11109         return ret_val;
11110 }
11111
11112 #endif /* MDASSEMBLE */
11113
11114 struct superswitch super_imsm = {
11115 #ifndef MDASSEMBLE
11116         .examine_super  = examine_super_imsm,
11117         .brief_examine_super = brief_examine_super_imsm,
11118         .brief_examine_subarrays = brief_examine_subarrays_imsm,
11119         .export_examine_super = export_examine_super_imsm,
11120         .detail_super   = detail_super_imsm,
11121         .brief_detail_super = brief_detail_super_imsm,
11122         .write_init_super = write_init_super_imsm,
11123         .validate_geometry = validate_geometry_imsm,
11124         .add_to_super   = add_to_super_imsm,
11125         .remove_from_super = remove_from_super_imsm,
11126         .detail_platform = detail_platform_imsm,
11127         .export_detail_platform = export_detail_platform_imsm,
11128         .kill_subarray = kill_subarray_imsm,
11129         .update_subarray = update_subarray_imsm,
11130         .load_container = load_container_imsm,
11131         .default_geometry = default_geometry_imsm,
11132         .get_disk_controller_domain = imsm_get_disk_controller_domain,
11133         .reshape_super  = imsm_reshape_super,
11134         .manage_reshape = imsm_manage_reshape,
11135         .recover_backup = recover_backup_imsm,
11136         .copy_metadata = copy_metadata_imsm,
11137 #endif
11138         .match_home     = match_home_imsm,
11139         .uuid_from_super= uuid_from_super_imsm,
11140         .getinfo_super  = getinfo_super_imsm,
11141         .getinfo_super_disks = getinfo_super_disks_imsm,
11142         .update_super   = update_super_imsm,
11143
11144         .avail_size     = avail_size_imsm,
11145         .min_acceptable_spare_size = min_acceptable_spare_size_imsm,
11146
11147         .compare_super  = compare_super_imsm,
11148
11149         .load_super     = load_super_imsm,
11150         .init_super     = init_super_imsm,
11151         .store_super    = store_super_imsm,
11152         .free_super     = free_super_imsm,
11153         .match_metadata_desc = match_metadata_desc_imsm,
11154         .container_content = container_content_imsm,
11155         .validate_container = validate_container_imsm,
11156
11157         .external       = 1,
11158         .name = "imsm",
11159
11160 #ifndef MDASSEMBLE
11161 /* for mdmon */
11162         .open_new       = imsm_open_new,
11163         .set_array_state= imsm_set_array_state,
11164         .set_disk       = imsm_set_disk,
11165         .sync_metadata  = imsm_sync_metadata,
11166         .activate_spare = imsm_activate_spare,
11167         .process_update = imsm_process_update,
11168         .prepare_update = imsm_prepare_update,
11169 #endif /* MDASSEMBLE */
11170 };