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