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