Create: add support for RAID0 layouts.
[thirdparty/mdadm.git] / super1.c
1 /*
2  * mdadm - manage Linux "md" devices aka RAID arrays.
3  *
4  * Copyright (C) 2001-2016 Neil Brown <neilb@suse.com>
5  *
6  *
7  *    This program is free software; you can redistribute it and/or modify
8  *    it under the terms of the GNU General Public License as published by
9  *    the Free Software Foundation; either version 2 of the License, or
10  *    (at your option) any later version.
11  *
12  *    This program is distributed in the hope that it will be useful,
13  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *    GNU General Public License for more details.
16  *
17  *    You should have received a copy of the GNU General Public License
18  *    along with this program; if not, write to the Free Software
19  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  *    Author: Neil Brown
22  *    Email: <neilb@suse.de>
23  */
24
25 #include <stddef.h>
26 #include "mdadm.h"
27 /*
28  * The version-1 superblock :
29  * All numeric fields are little-endian.
30  *
31  * total size: 256 bytes plus 2 per device.
32  *  1K allows 384 devices.
33  */
34 struct mdp_superblock_1 {
35         /* constant array information - 128 bytes */
36         __u32   magic;          /* MD_SB_MAGIC: 0xa92b4efc - little endian */
37         __u32   major_version;  /* 1 */
38         __u32   feature_map;    /* 0 for now */
39         __u32   pad0;           /* always set to 0 when writing */
40
41         __u8    set_uuid[16];   /* user-space generated. */
42         char    set_name[32];   /* set and interpreted by user-space */
43
44         __u64   ctime;          /* lo 40 bits are seconds, top 24 are microseconds or 0*/
45         __u32   level;          /* -4 (multipath), -1 (linear), 0,1,4,5 */
46         __u32   layout;         /* used for raid5, raid6, raid10, and raid0 */
47         __u64   size;           /* used size of component devices, in 512byte sectors */
48
49         __u32   chunksize;      /* in 512byte sectors */
50         __u32   raid_disks;
51         union {
52                 __u32   bitmap_offset;  /* sectors after start of superblock that bitmap starts
53                                          * NOTE: signed, so bitmap can be before superblock
54                                          * only meaningful of feature_map[0] is set.
55                                          */
56
57                 /* only meaningful when feature_map[MD_FEATURE_PPL] is set */
58                 struct {
59                         __s16 offset; /* sectors from start of superblock that ppl starts */
60                         __u16 size; /* ppl size in sectors */
61                 } ppl;
62         };
63
64         /* These are only valid with feature bit '4' */
65         __u32   new_level;      /* new level we are reshaping to                */
66         __u64   reshape_position;       /* next address in array-space for reshape */
67         __u32   delta_disks;    /* change in number of raid_disks               */
68         __u32   new_layout;     /* new layout                                   */
69         __u32   new_chunk;      /* new chunk size (sectors)                     */
70         __u32   new_offset;     /* signed number to add to data_offset in new
71                                  * layout.  0 == no-change.  This can be
72                                  * different on each device in the array.
73                                  */
74
75         /* constant this-device information - 64 bytes */
76         __u64   data_offset;    /* sector start of data, often 0 */
77         __u64   data_size;      /* sectors in this device that can be used for data */
78         __u64   super_offset;   /* sector start of this superblock */
79         union {
80                 __u64   recovery_offset;/* sectors before this offset (from data_offset) have been recovered */
81                 __u64   journal_tail;/* journal tail of journal device (from data_offset) */
82         };
83         __u32   dev_number;     /* permanent identifier of this  device - not role in raid */
84         __u32   cnt_corrected_read; /* number of read errors that were corrected by re-writing */
85         __u8    device_uuid[16]; /* user-space setable, ignored by kernel */
86         __u8    devflags;        /* per-device flags.  Only one defined...*/
87 #define WriteMostly1    1        /* mask for writemostly flag in above */
88 #define FailFast1       2        /* Device should get FailFast requests */
89         /* bad block log.  If there are any bad blocks the feature flag is set.
90          * if offset and size are non-zero, that space is reserved and available.
91          */
92         __u8    bblog_shift;    /* shift from sectors to block size for badblock list */
93         __u16   bblog_size;     /* number of sectors reserved for badblock list */
94         __u32   bblog_offset;   /* sector offset from superblock to bblog, signed */
95
96         /* array state information - 64 bytes */
97         __u64   utime;          /* 40 bits second, 24 bits microseconds */
98         __u64   events;         /* incremented when superblock updated */
99         __u64   resync_offset;  /* data before this offset (from data_offset) known to be in sync */
100         __u32   sb_csum;        /* checksum upto dev_roles[max_dev] */
101         __u32   max_dev;        /* size of dev_roles[] array to consider */
102         __u8    pad3[64-32];    /* set to 0 when writing */
103
104         /* device state information. Indexed by dev_number.
105          * 2 bytes per device
106          * Note there are no per-device state flags. State information is rolled
107          * into the 'roles' value.  If a device is spare or faulty, then it doesn't
108          * have a meaningful role.
109          */
110         __u16   dev_roles[0];   /* role in array, or 0xffff for a spare, or 0xfffe for faulty */
111 };
112
113 #define MAX_SB_SIZE 4096
114 /* bitmap super size is 256, but we round up to a sector for alignment */
115 #define BM_SUPER_SIZE 512
116 #define MAX_DEVS ((int)(MAX_SB_SIZE - sizeof(struct mdp_superblock_1)) / 2)
117 #define SUPER1_SIZE     (MAX_SB_SIZE + BM_SUPER_SIZE \
118                          + sizeof(struct misc_dev_info))
119
120 struct misc_dev_info {
121         __u64 device_size;
122 };
123
124 #define MULTIPLE_PPL_AREA_SIZE_SUPER1 (1024 * 1024) /* Size of the whole
125                                                      * mutliple PPL area
126                                                      */
127 /* feature_map bits */
128 #define MD_FEATURE_BITMAP_OFFSET        1
129 #define MD_FEATURE_RECOVERY_OFFSET      2 /* recovery_offset is present and
130                                            * must be honoured
131                                            */
132 #define MD_FEATURE_RESHAPE_ACTIVE       4
133 #define MD_FEATURE_BAD_BLOCKS           8 /* badblock list is not empty */
134 #define MD_FEATURE_REPLACEMENT          16 /* This device is replacing an
135                                             * active device with same 'role'.
136                                             * 'recovery_offset' is also set.
137                                             */
138 #define MD_FEATURE_RESHAPE_BACKWARDS    32 /* Reshape doesn't change number
139                                             * of devices, but is going
140                                             * backwards anyway.
141                                             */
142 #define MD_FEATURE_NEW_OFFSET           64 /* new_offset must be honoured */
143 #define MD_FEATURE_BITMAP_VERSIONED     256 /* bitmap version number checked properly */
144 #define MD_FEATURE_JOURNAL              512 /* support write journal */
145 #define MD_FEATURE_PPL                  1024 /* support PPL */
146 #define MD_FEATURE_MUTLIPLE_PPLS        2048 /* support for multiple PPLs */
147 #define MD_FEATURE_RAID0_LAYOUT         4096 /* layout is meaningful in RAID0 */
148 #define MD_FEATURE_ALL                  (MD_FEATURE_BITMAP_OFFSET       \
149                                         |MD_FEATURE_RECOVERY_OFFSET     \
150                                         |MD_FEATURE_RESHAPE_ACTIVE      \
151                                         |MD_FEATURE_BAD_BLOCKS          \
152                                         |MD_FEATURE_REPLACEMENT         \
153                                         |MD_FEATURE_RESHAPE_BACKWARDS   \
154                                         |MD_FEATURE_NEW_OFFSET          \
155                                         |MD_FEATURE_BITMAP_VERSIONED    \
156                                         |MD_FEATURE_JOURNAL             \
157                                         |MD_FEATURE_PPL                 \
158                                         |MD_FEATURE_MULTIPLE_PPLS       \
159                                         |MD_FEATURE_RAID0_LAYOUT        \
160                                         )
161
162 static int role_from_sb(struct mdp_superblock_1 *sb)
163 {
164         unsigned int d;
165         int role;
166
167         d = __le32_to_cpu(sb->dev_number);
168         if (d < __le32_to_cpu(sb->max_dev))
169                 role = __le16_to_cpu(sb->dev_roles[d]);
170         else
171                 role = MD_DISK_ROLE_SPARE;
172         return role;
173 }
174
175 /* return how many bytes are needed for bitmap, for cluster-md each node
176  * should have it's own bitmap */
177 static unsigned int calc_bitmap_size(bitmap_super_t *bms, unsigned int boundary)
178 {
179         unsigned long long bits, bytes;
180
181         bits = bitmap_bits(__le64_to_cpu(bms->sync_size),
182                            __le32_to_cpu(bms->chunksize));
183         bytes = (bits+7) >> 3;
184         bytes += sizeof(bitmap_super_t);
185         bytes = ROUND_UP(bytes, boundary);
186
187         return bytes;
188 }
189
190 static unsigned int calc_sb_1_csum(struct mdp_superblock_1 * sb)
191 {
192         unsigned int disk_csum, csum;
193         unsigned long long newcsum;
194         int size = sizeof(*sb) + __le32_to_cpu(sb->max_dev)*2;
195         unsigned int *isuper = (unsigned int*)sb;
196
197 /* make sure I can count... */
198         if (offsetof(struct mdp_superblock_1,data_offset) != 128 ||
199             offsetof(struct mdp_superblock_1, utime) != 192 ||
200             sizeof(struct mdp_superblock_1) != 256) {
201                 fprintf(stderr, "WARNING - superblock isn't sized correctly\n");
202         }
203
204         disk_csum = sb->sb_csum;
205         sb->sb_csum = 0;
206         newcsum = 0;
207         for (; size>=4; size -= 4 ) {
208                 newcsum += __le32_to_cpu(*isuper);
209                 isuper++;
210         }
211
212         if (size == 2)
213                 newcsum += __le16_to_cpu(*(unsigned short*) isuper);
214
215         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
216         sb->sb_csum = disk_csum;
217         return __cpu_to_le32(csum);
218 }
219
220 /*
221  * Information related to file descriptor used for aligned reads/writes.
222  * Cache the block size.
223  */
224 struct align_fd {
225         int fd;
226         int blk_sz;
227 };
228
229 static void init_afd(struct align_fd *afd, int fd)
230 {
231         afd->fd = fd;
232         if (!get_dev_sector_size(afd->fd, NULL, (unsigned int *)&afd->blk_sz))
233                 afd->blk_sz = 512;
234 }
235
236 static char abuf[4096+4096];
237
238 static int aread(struct align_fd *afd, void *buf, int len)
239 {
240         /* aligned read.
241          * On devices with a 4K sector size, we need to read
242          * the full sector and copy relevant bits into
243          * the buffer
244          */
245         int bsize, iosize;
246         char *b;
247         int n;
248
249         bsize = afd->blk_sz;
250
251         if (!bsize || bsize > 4096 || len > 4096) {
252                 if (!bsize)
253                         fprintf(stderr, "WARNING - aread() called with invalid block size\n");
254                 return -1;
255         }
256         b = ROUND_UP_PTR((char *)abuf, 4096);
257
258         for (iosize = 0; iosize < len; iosize += bsize)
259                 ;
260         n = read(afd->fd, b, iosize);
261         if (n <= 0)
262                 return n;
263         lseek(afd->fd, len - n, 1);
264         if (n > len)
265                 n = len;
266         memcpy(buf, b, n);
267         return n;
268 }
269
270 static int awrite(struct align_fd *afd, void *buf, int len)
271 {
272         /* aligned write.
273          * On devices with a 4K sector size, we need to write
274          * the full sector.  We pre-read if the sector is larger
275          * than the write.
276          * The address must be sector-aligned.
277          */
278         int bsize, iosize;
279         char *b;
280         int n;
281
282         bsize = afd->blk_sz;
283         if (!bsize || bsize > 4096 || len > 4096) {
284                 if (!bsize)
285                         fprintf(stderr, "WARNING - awrite() called with invalid block size\n");
286                 return -1;
287         }
288         b = ROUND_UP_PTR((char *)abuf, 4096);
289
290         for (iosize = 0; iosize < len ; iosize += bsize)
291                 ;
292
293         if (len != iosize) {
294                 n = read(afd->fd, b, iosize);
295                 if (n <= 0)
296                         return n;
297                 lseek(afd->fd, -n, 1);
298         }
299
300         memcpy(b, buf, len);
301         n = write(afd->fd, b, iosize);
302         if (n <= 0)
303                 return n;
304         lseek(afd->fd, len - n, 1);
305         return len;
306 }
307
308 static inline unsigned int md_feature_any_ppl_on(__u32 feature_map)
309 {
310         return ((__cpu_to_le32(feature_map) &
311             (MD_FEATURE_PPL | MD_FEATURE_MUTLIPLE_PPLS)));
312 }
313
314 static inline unsigned int choose_ppl_space(int chunk)
315 {
316         return (PPL_HEADER_SIZE >> 9) + (chunk > 128*2 ? chunk : 128*2);
317 }
318
319 static void examine_super1(struct supertype *st, char *homehost)
320 {
321         struct mdp_superblock_1 *sb = st->sb;
322         bitmap_super_t *bms = (bitmap_super_t*)(((char*)sb)+MAX_SB_SIZE);
323         time_t atime;
324         unsigned int d;
325         int role;
326         int delta_extra = 0;
327         int i;
328         char *c;
329         int l = homehost ? strlen(homehost) : 0;
330         int layout;
331         unsigned long long sb_offset;
332         struct mdinfo info;
333
334         printf("          Magic : %08x\n", __le32_to_cpu(sb->magic));
335         printf("        Version : 1");
336         sb_offset = __le64_to_cpu(sb->super_offset);
337         if (sb_offset <= 4)
338                 printf(".1\n");
339         else if (sb_offset <= 8)
340                 printf(".2\n");
341         else
342                 printf(".0\n");
343         printf("    Feature Map : 0x%x\n", __le32_to_cpu(sb->feature_map));
344         printf("     Array UUID : ");
345         for (i=0; i<16; i++) {
346                 if ((i&3)==0 && i != 0) printf(":");
347                 printf("%02x", sb->set_uuid[i]);
348         }
349         printf("\n");
350         printf("           Name : %.32s", sb->set_name);
351         if (l > 0 && l < 32 &&
352             sb->set_name[l] == ':' &&
353             strncmp(sb->set_name, homehost, l) == 0)
354                 printf("  (local to host %s)", homehost);
355         printf("\n");
356         if (bms->nodes > 0 &&
357             (__le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET))
358                 printf("   Cluster Name : %-64s\n", bms->cluster_name);
359         atime = __le64_to_cpu(sb->ctime) & 0xFFFFFFFFFFULL;
360         printf("  Creation Time : %.24s\n", ctime(&atime));
361         c=map_num(pers, __le32_to_cpu(sb->level));
362         printf("     Raid Level : %s\n", c?c:"-unknown-");
363         printf("   Raid Devices : %d\n", __le32_to_cpu(sb->raid_disks));
364         printf("\n");
365         printf(" Avail Dev Size : %llu sectors%s\n",
366                (unsigned long long)__le64_to_cpu(sb->data_size),
367                human_size(__le64_to_cpu(sb->data_size)<<9));
368         if (__le32_to_cpu(sb->level) > 0) {
369                 int ddsks = 0, ddsks_denom = 1;
370                 switch(__le32_to_cpu(sb->level)) {
371                 case 1: ddsks=1;break;
372                 case 4:
373                 case 5: ddsks = __le32_to_cpu(sb->raid_disks)-1; break;
374                 case 6: ddsks = __le32_to_cpu(sb->raid_disks)-2; break;
375                 case 10:
376                         layout = __le32_to_cpu(sb->layout);
377                         ddsks = __le32_to_cpu(sb->raid_disks);
378                         ddsks_denom = (layout&255) * ((layout>>8)&255);
379                 }
380                 if (ddsks) {
381                         long long asize = __le64_to_cpu(sb->size);
382                         asize = (asize << 9) * ddsks / ddsks_denom;
383                         printf("     Array Size : %llu KiB%s\n",
384                                asize >> 10,  human_size(asize));
385                 }
386                 if (sb->size != sb->data_size)
387                         printf("  Used Dev Size : %llu sectors%s\n",
388                                (unsigned long long)__le64_to_cpu(sb->size),
389                                human_size(__le64_to_cpu(sb->size)<<9));
390         }
391         if (sb->data_offset)
392                 printf("    Data Offset : %llu sectors\n",
393                        (unsigned long long)__le64_to_cpu(sb->data_offset));
394         if (sb->new_offset &&
395             (__le32_to_cpu(sb->feature_map) & MD_FEATURE_NEW_OFFSET)) {
396                 unsigned long long offset = __le64_to_cpu(sb->data_offset);
397                 offset += (signed)(int32_t)__le32_to_cpu(sb->new_offset);
398                 printf("     New Offset : %llu sectors\n", offset);
399         }
400         printf("   Super Offset : %llu sectors\n",
401                (unsigned long long)__le64_to_cpu(sb->super_offset));
402         if (__le32_to_cpu(sb->feature_map) & MD_FEATURE_RECOVERY_OFFSET)
403                 printf("Recovery Offset : %llu sectors\n",
404                        (unsigned long long)__le64_to_cpu(sb->recovery_offset));
405
406         st->ss->getinfo_super(st, &info, NULL);
407         if (info.space_after != 1 &&
408             !(__le32_to_cpu(sb->feature_map) & MD_FEATURE_NEW_OFFSET))
409                 printf("   Unused Space : before=%llu sectors, after=%llu sectors\n",
410                        info.space_before, info.space_after);
411
412         printf("          State : %s\n",
413                (__le64_to_cpu(sb->resync_offset)+1)? "active":"clean");
414         printf("    Device UUID : ");
415         for (i=0; i<16; i++) {
416                 if ((i&3)==0 && i != 0)
417                         printf(":");
418                 printf("%02x", sb->device_uuid[i]);
419         }
420         printf("\n");
421         printf("\n");
422         if (sb->feature_map & __cpu_to_le32(MD_FEATURE_BITMAP_OFFSET)) {
423                 printf("Internal Bitmap : %ld sectors from superblock\n",
424                        (long)(int32_t)__le32_to_cpu(sb->bitmap_offset));
425         } else if (md_feature_any_ppl_on(sb->feature_map)) {
426                 printf("            PPL : %u sectors at offset %d sectors from superblock\n",
427                        __le16_to_cpu(sb->ppl.size),
428                        __le16_to_cpu(sb->ppl.offset));
429         }
430         if (sb->feature_map & __cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE)) {
431                 printf("  Reshape pos'n : %llu%s\n", (unsigned long long)
432                        __le64_to_cpu(sb->reshape_position)/2,
433                        human_size(__le64_to_cpu(sb->reshape_position)<<9));
434                 if (__le32_to_cpu(sb->delta_disks)) {
435                         printf("  Delta Devices : %d",
436                                __le32_to_cpu(sb->delta_disks));
437                         printf(" (%d->%d)\n",
438                                __le32_to_cpu(sb->raid_disks) -
439                                __le32_to_cpu(sb->delta_disks),
440                                __le32_to_cpu(sb->raid_disks));
441                         if ((int)__le32_to_cpu(sb->delta_disks) < 0)
442                                 delta_extra = -__le32_to_cpu(sb->delta_disks);
443                 }
444                 if (__le32_to_cpu(sb->new_level) != __le32_to_cpu(sb->level)) {
445                         c = map_num(pers, __le32_to_cpu(sb->new_level));
446                         printf("      New Level : %s\n", c?c:"-unknown-");
447                 }
448                 if (__le32_to_cpu(sb->new_layout) !=
449                     __le32_to_cpu(sb->layout)) {
450                         if (__le32_to_cpu(sb->level) == 5) {
451                                 c = map_num(r5layout,
452                                             __le32_to_cpu(sb->new_layout));
453                                 printf("     New Layout : %s\n", c?c:"-unknown-");
454                         }
455                         if (__le32_to_cpu(sb->level) == 6) {
456                                 c = map_num(r6layout,
457                                             __le32_to_cpu(sb->new_layout));
458                                 printf("     New Layout : %s\n", c?c:"-unknown-");
459                         }
460                         if (__le32_to_cpu(sb->level) == 10) {
461                                 printf("     New Layout :");
462                                 print_r10_layout(__le32_to_cpu(sb->new_layout));
463                                 printf("\n");
464                         }
465                 }
466                 if (__le32_to_cpu(sb->new_chunk) !=
467                     __le32_to_cpu(sb->chunksize))
468                         printf("  New Chunksize : %dK\n",
469                                __le32_to_cpu(sb->new_chunk)/2);
470                 printf("\n");
471         }
472         if (sb->devflags) {
473                 printf("          Flags :");
474                 if (sb->devflags & WriteMostly1)
475                         printf(" write-mostly");
476                 if (sb->devflags & FailFast1)
477                         printf(" failfast");
478                 printf("\n");
479         }
480
481         atime = __le64_to_cpu(sb->utime) & 0xFFFFFFFFFFULL;
482         printf("    Update Time : %.24s\n", ctime(&atime));
483
484         if (sb->bblog_size && sb->bblog_offset) {
485                 printf("  Bad Block Log : %d entries available at offset %ld sectors",
486                        __le16_to_cpu(sb->bblog_size)*512/8,
487                        (long)(int32_t)__le32_to_cpu(sb->bblog_offset));
488                 if (sb->feature_map & __cpu_to_le32(MD_FEATURE_BAD_BLOCKS))
489                         printf(" - bad blocks present.");
490                 printf("\n");
491         }
492
493         if (calc_sb_1_csum(sb) == sb->sb_csum)
494                 printf("       Checksum : %x - correct\n",
495                        __le32_to_cpu(sb->sb_csum));
496         else
497                 printf("       Checksum : %x - expected %x\n",
498                        __le32_to_cpu(sb->sb_csum),
499                        __le32_to_cpu(calc_sb_1_csum(sb)));
500         printf("         Events : %llu\n",
501                (unsigned long long)__le64_to_cpu(sb->events));
502         printf("\n");
503         if (__le32_to_cpu(sb->level) == 0 &&
504             (sb->feature_map & __cpu_to_le32(MD_FEATURE_RAID0_LAYOUT))) {
505                 c = map_num(r0layout, __le32_to_cpu(sb->layout));
506                 printf("         Layout : %s\n", c?c:"-unknown-");
507         }
508         if (__le32_to_cpu(sb->level) == 5) {
509                 c = map_num(r5layout, __le32_to_cpu(sb->layout));
510                 printf("         Layout : %s\n", c?c:"-unknown-");
511         }
512         if (__le32_to_cpu(sb->level) == 6) {
513                 c = map_num(r6layout, __le32_to_cpu(sb->layout));
514                 printf("         Layout : %s\n", c?c:"-unknown-");
515         }
516         if (__le32_to_cpu(sb->level) == 10) {
517                 int lo = __le32_to_cpu(sb->layout);
518                 printf("         Layout :");
519                 print_r10_layout(lo);
520                 printf("\n");
521         }
522         switch(__le32_to_cpu(sb->level)) {
523         case 0:
524         case 4:
525         case 5:
526         case 6:
527         case 10:
528                 printf("     Chunk Size : %dK\n",
529                        __le32_to_cpu(sb->chunksize)/2);
530                 break;
531         case -1:
532                 printf("       Rounding : %dK\n",
533                        __le32_to_cpu(sb->chunksize)/2);
534                 break;
535         default:
536                 break;
537         }
538         printf("\n");
539 #if 0
540         /* This turns out to just be confusing */
541         printf("    Array Slot : %d (", __le32_to_cpu(sb->dev_number));
542         for (i = __le32_to_cpu(sb->max_dev); i> 0 ; i--)
543                 if (__le16_to_cpu(sb->dev_roles[i-1]) != MD_DISK_ROLE_SPARE)
544                         break;
545         for (d = 0; d < i; d++) {
546                 int role = __le16_to_cpu(sb->dev_roles[d]);
547                 if (d)
548                         printf(", ");
549                 if (role == MD_DISK_ROLE_SPARE)
550                         printf("empty");
551                 else
552                         if(role == MD_DISK_ROLE_FAULTY)
553                                 printf("failed");
554                         else
555                                 printf("%d", role);
556         }
557         printf(")\n");
558 #endif
559         printf("   Device Role : ");
560         role = role_from_sb(sb);
561         if (role >= MD_DISK_ROLE_FAULTY)
562                 printf("spare\n");
563         else if (role == MD_DISK_ROLE_JOURNAL)
564                 printf("Journal\n");
565         else if (sb->feature_map & __cpu_to_le32(MD_FEATURE_REPLACEMENT))
566                 printf("Replacement device %d\n", role);
567         else
568                 printf("Active device %d\n", role);
569
570         printf("   Array State : ");
571         for (d = 0; d < __le32_to_cpu(sb->raid_disks) + delta_extra; d++) {
572                 int cnt = 0;
573                 unsigned int i;
574                 for (i = 0; i < __le32_to_cpu(sb->max_dev); i++) {
575                         unsigned int role = __le16_to_cpu(sb->dev_roles[i]);
576                         if (role == d)
577                                 cnt++;
578                 }
579                 if (cnt == 2)
580                         printf("R");
581                 else if (cnt == 1)
582                         printf("A");
583                 else if (cnt == 0)
584                         printf(".");
585                 else
586                         printf("?");
587         }
588 #if 0
589         /* This is confusing too */
590         faulty = 0;
591         for (i = 0; i< __le32_to_cpu(sb->max_dev); i++) {
592                 int role = __le16_to_cpu(sb->dev_roles[i]);
593                 if (role == MD_DISK_ROLE_FAULTY)
594                         faulty++;
595         }
596         if (faulty)
597                 printf(" %d failed", faulty);
598 #endif
599         printf(" ('A' == active, '.' == missing, 'R' == replacing)");
600         printf("\n");
601 }
602
603 static void brief_examine_super1(struct supertype *st, int verbose)
604 {
605         struct mdp_superblock_1 *sb = st->sb;
606         int i;
607         unsigned long long sb_offset;
608         char *nm;
609         char *c = map_num(pers, __le32_to_cpu(sb->level));
610
611         nm = strchr(sb->set_name, ':');
612         if (nm)
613                 nm++;
614         else if (sb->set_name[0])
615                 nm = sb->set_name;
616         else
617                 nm = NULL;
618
619         printf("ARRAY ");
620         if (nm) {
621                 printf("/dev/md/");
622                 print_escape(nm);
623                 putchar(' ');
624         }
625         if (verbose && c)
626                 printf(" level=%s", c);
627         sb_offset = __le64_to_cpu(sb->super_offset);
628         if (sb_offset <= 4)
629                 printf(" metadata=1.1 ");
630         else if (sb_offset <= 8)
631                 printf(" metadata=1.2 ");
632         else
633                 printf(" metadata=1.0 ");
634         if (verbose)
635                 printf("num-devices=%d ", __le32_to_cpu(sb->raid_disks));
636         printf("UUID=");
637         for (i = 0; i < 16; i++) {
638                 if ((i&3)==0 && i != 0)
639                         printf(":");
640                 printf("%02x", sb->set_uuid[i]);
641         }
642         if (sb->set_name[0]) {
643                 printf(" name=");
644                 print_quoted(sb->set_name);
645         }
646         printf("\n");
647 }
648
649 static void export_examine_super1(struct supertype *st)
650 {
651         struct mdp_superblock_1 *sb = st->sb;
652         int i;
653         int len = 32;
654         int layout;
655
656         printf("MD_LEVEL=%s\n", map_num(pers, __le32_to_cpu(sb->level)));
657         printf("MD_DEVICES=%d\n", __le32_to_cpu(sb->raid_disks));
658         for (i = 0; i < 32; i++)
659                 if (sb->set_name[i] == '\n' || sb->set_name[i] == '\0') {
660                         len = i;
661                         break;
662                 }
663         if (len)
664                 printf("MD_NAME=%.*s\n", len, sb->set_name);
665         if (__le32_to_cpu(sb->level) > 0) {
666                 int ddsks = 0, ddsks_denom = 1;
667                 switch(__le32_to_cpu(sb->level)) {
668                         case 1:
669                                 ddsks = 1;
670                                 break;
671                         case 4:
672                         case 5:
673                                 ddsks = __le32_to_cpu(sb->raid_disks)-1;
674                                 break;
675                         case 6:
676                                 ddsks = __le32_to_cpu(sb->raid_disks)-2;
677                                 break;
678                         case 10:
679                                 layout = __le32_to_cpu(sb->layout);
680                                 ddsks = __le32_to_cpu(sb->raid_disks);
681                                 ddsks_denom = (layout&255) * ((layout>>8)&255);
682                         }
683                 if (ddsks) {
684                         long long asize = __le64_to_cpu(sb->size);
685                         asize = (asize << 9) * ddsks / ddsks_denom;
686                         printf("MD_ARRAY_SIZE=%s\n",
687                                human_size_brief(asize, JEDEC));
688                 }
689         }
690         printf("MD_UUID=");
691         for (i = 0; i < 16; i++) {
692                 if ((i&3) == 0 && i != 0)
693                         printf(":");
694                 printf("%02x", sb->set_uuid[i]);
695         }
696         printf("\n");
697         printf("MD_UPDATE_TIME=%llu\n",
698                __le64_to_cpu(sb->utime) & 0xFFFFFFFFFFULL);
699         printf("MD_DEV_UUID=");
700         for (i = 0; i < 16; i++) {
701                 if ((i&3) == 0 && i != 0)
702                         printf(":");
703                 printf("%02x", sb->device_uuid[i]);
704         }
705         printf("\n");
706         printf("MD_EVENTS=%llu\n",
707                (unsigned long long)__le64_to_cpu(sb->events));
708 }
709
710 static int copy_metadata1(struct supertype *st, int from, int to)
711 {
712         /* Read superblock.  If it looks good, write it out.
713          * Then if a bitmap is present, copy that.
714          * And if a bad-block-list is present, copy that too.
715          */
716         void *buf;
717         unsigned long long dsize, sb_offset;
718         const int bufsize = 4*1024;
719         struct mdp_superblock_1 super, *sb;
720
721         if (posix_memalign(&buf, 4096, bufsize) != 0)
722                 return 1;
723
724         if (!get_dev_size(from, NULL, &dsize))
725                 goto err;
726
727         dsize >>= 9;
728         if (dsize < 24)
729                 goto err;
730         switch(st->minor_version) {
731         case 0:
732                 sb_offset = dsize;
733                 sb_offset -= 8*2;
734                 sb_offset &= ~(4*2-1);
735                 break;
736         case 1:
737                 sb_offset = 0;
738                 break;
739         case 2:
740                 sb_offset = 4*2;
741                 break;
742         default:
743                 goto err;
744         }
745
746         if (lseek64(from, sb_offset << 9, 0) < 0LL)
747                 goto err;
748         if (read(from, buf, bufsize) != bufsize)
749                 goto err;
750
751         sb = buf;
752         super = *sb; // save most of sb for when we reuse buf
753
754         if (__le32_to_cpu(super.magic) != MD_SB_MAGIC ||
755             __le32_to_cpu(super.major_version) != 1 ||
756             __le64_to_cpu(super.super_offset) != sb_offset ||
757             calc_sb_1_csum(sb) != super.sb_csum)
758                 goto err;
759
760         if (lseek64(to, sb_offset << 9, 0) < 0LL)
761                 goto err;
762         if (write(to, buf, bufsize) != bufsize)
763                 goto err;
764
765         if (super.feature_map & __le32_to_cpu(MD_FEATURE_BITMAP_OFFSET)) {
766                 unsigned long long bitmap_offset = sb_offset;
767                 int bytes = 4096; // just an estimate.
768                 int written = 0;
769                 struct align_fd afrom, ato;
770
771                 init_afd(&afrom, from);
772                 init_afd(&ato, to);
773
774                 bitmap_offset += (int32_t)__le32_to_cpu(super.bitmap_offset);
775
776                 if (lseek64(from, bitmap_offset<<9, 0) < 0)
777                         goto err;
778                 if (lseek64(to, bitmap_offset<<9, 0) < 0)
779                         goto err;
780
781                 for (written = 0; written < bytes ; ) {
782                         int n = bytes - written;
783                         if (n > 4096)
784                                 n = 4096;
785                         if (aread(&afrom, buf, n) != n)
786                                 goto err;
787                         if (written == 0) {
788                                 /* have the header, can calculate
789                                  * correct bitmap bytes */
790                                 bitmap_super_t *bms;
791                                 bms = (void*)buf;
792                                 bytes = calc_bitmap_size(bms, 512);
793                                 if (n > bytes)
794                                         n =  bytes;
795                         }
796                         if (awrite(&ato, buf, n) != n)
797                                 goto err;
798                         written += n;
799                 }
800         }
801
802         if (super.bblog_size != 0 &&
803             __le16_to_cpu(super.bblog_size) <= 100 &&
804             super.bblog_offset != 0 &&
805             (super.feature_map & __le32_to_cpu(MD_FEATURE_BAD_BLOCKS))) {
806                 /* There is a bad block log */
807                 unsigned long long bb_offset = sb_offset;
808                 int bytes = __le16_to_cpu(super.bblog_size) * 512;
809                 int written = 0;
810                 struct align_fd afrom, ato;
811
812                 init_afd(&afrom, from);
813                 init_afd(&ato, to);
814
815                 bb_offset += (int32_t)__le32_to_cpu(super.bblog_offset);
816
817                 if (lseek64(from, bb_offset<<9, 0) < 0)
818                         goto err;
819                 if (lseek64(to, bb_offset<<9, 0) < 0)
820                         goto err;
821
822                 for (written = 0; written < bytes ; ) {
823                         int n = bytes - written;
824                         if (n > 4096)
825                                 n = 4096;
826                         if (aread(&afrom, buf, n) != n)
827                                 goto err;
828
829                         if (awrite(&ato, buf, n) != n)
830                                 goto err;
831                         written += n;
832                 }
833         }
834
835         free(buf);
836         return 0;
837
838 err:
839         free(buf);
840         return 1;
841 }
842
843 static void detail_super1(struct supertype *st, char *homehost, char *subarray)
844 {
845         struct mdp_superblock_1 *sb = st->sb;
846         bitmap_super_t *bms = (bitmap_super_t*)(((char*)sb) + MAX_SB_SIZE);
847         int i;
848         int l = homehost ? strlen(homehost) : 0;
849
850         printf("              Name : %.32s", sb->set_name);
851         if (l > 0 && l < 32 && sb->set_name[l] == ':' &&
852             strncmp(sb->set_name, homehost, l) == 0)
853                 printf("  (local to host %s)", homehost);
854         if (bms->nodes > 0 &&
855             (__le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET))
856                 printf("\n      Cluster Name : %-64s", bms->cluster_name);
857         printf("\n              UUID : ");
858         for (i = 0; i < 16; i++) {
859                 if ((i&3) == 0 && i != 0)
860                         printf(":");
861                 printf("%02x", sb->set_uuid[i]);
862         }
863         printf("\n            Events : %llu\n\n",
864                (unsigned long long)__le64_to_cpu(sb->events));
865 }
866
867 static void brief_detail_super1(struct supertype *st, char *subarray)
868 {
869         struct mdp_superblock_1 *sb = st->sb;
870         int i;
871
872         if (sb->set_name[0]) {
873                 printf(" name=");
874                 print_quoted(sb->set_name);
875         }
876         printf(" UUID=");
877         for (i = 0; i < 16; i++) {
878                 if ((i & 3) == 0 && i != 0)
879                         printf(":");
880                 printf("%02x", sb->set_uuid[i]);
881         }
882 }
883
884 static void export_detail_super1(struct supertype *st)
885 {
886         struct mdp_superblock_1 *sb = st->sb;
887         int i;
888         int len = 32;
889
890         for (i = 0; i < 32; i++)
891                 if (sb->set_name[i] == '\n' || sb->set_name[i] == '\0') {
892                         len = i;
893                         break;
894                 }
895         if (len)
896                 printf("MD_NAME=%.*s\n", len, sb->set_name);
897 }
898
899 static int examine_badblocks_super1(struct supertype *st, int fd, char *devname)
900 {
901         struct mdp_superblock_1 *sb = st->sb;
902         unsigned long long offset;
903         int size;
904         __u64 *bbl, *bbp;
905         int i;
906
907         if  (!sb->bblog_size || __le16_to_cpu(sb->bblog_size) > 100 ||
908              !sb->bblog_offset){
909                 printf("No bad-blocks list configured on %s\n", devname);
910                 return 0;
911         }
912         if ((sb->feature_map & __cpu_to_le32(MD_FEATURE_BAD_BLOCKS)) == 0) {
913                 printf("Bad-blocks list is empty in %s\n", devname);
914                 return 0;
915         }
916
917         size = __le16_to_cpu(sb->bblog_size)* 512;
918         if (posix_memalign((void**)&bbl, 4096, size) != 0) {
919                 pr_err("could not allocate badblocks list\n");
920                 return 0;
921         }
922         offset = __le64_to_cpu(sb->super_offset) +
923                 (int)__le32_to_cpu(sb->bblog_offset);
924         offset <<= 9;
925         if (lseek64(fd, offset, 0) < 0) {
926                 pr_err("Cannot seek to bad-blocks list\n");
927                 return 1;
928         }
929         if (read(fd, bbl, size) != size) {
930                 pr_err("Cannot read bad-blocks list\n");
931                 return 1;
932         }
933         /* 64bits per entry. 10 bits is block-count, 54 bits is block
934          * offset.  Blocks are sectors unless bblog->shift makes them bigger
935          */
936         bbp = (__u64*)bbl;
937         printf("Bad-blocks on %s:\n", devname);
938         for (i = 0; i < size/8; i++, bbp++) {
939                 __u64 bb = __le64_to_cpu(*bbp);
940                 int count = bb & 0x3ff;
941                 unsigned long long sector = bb >> 10;
942
943                 if (bb + 1 == 0)
944                         break;
945
946                 sector <<= sb->bblog_shift;
947                 count <<= sb->bblog_shift;
948
949                 printf("%20llu for %d sectors\n", sector, count);
950         }
951         return 0;
952 }
953
954 static int match_home1(struct supertype *st, char *homehost)
955 {
956         struct mdp_superblock_1 *sb = st->sb;
957         int l = homehost ? strlen(homehost) : 0;
958
959         return (l > 0 && l < 32 && sb->set_name[l] == ':' &&
960                 strncmp(sb->set_name, homehost, l) == 0);
961 }
962
963 static void uuid_from_super1(struct supertype *st, int uuid[4])
964 {
965         struct mdp_superblock_1 *super = st->sb;
966         char *cuuid = (char*)uuid;
967         int i;
968         for (i = 0; i < 16; i++)
969                 cuuid[i] = super->set_uuid[i];
970 }
971
972 static void getinfo_super1(struct supertype *st, struct mdinfo *info, char *map)
973 {
974         struct mdp_superblock_1 *sb = st->sb;
975         struct bitmap_super_s *bsb = (void*)(((char*)sb)+MAX_SB_SIZE);
976         struct misc_dev_info *misc =
977                 (void*)(((char*)sb)+MAX_SB_SIZE+BM_SUPER_SIZE);
978         int working = 0;
979         unsigned int i;
980         unsigned int role;
981         unsigned int map_disks = info->array.raid_disks;
982         unsigned long long super_offset;
983         unsigned long long data_size;
984
985         memset(info, 0, sizeof(*info));
986         info->array.major_version = 1;
987         info->array.minor_version = st->minor_version;
988         info->array.patch_version = 0;
989         info->array.raid_disks = __le32_to_cpu(sb->raid_disks);
990         info->array.level = __le32_to_cpu(sb->level);
991         info->array.layout = __le32_to_cpu(sb->layout);
992         info->array.md_minor = -1;
993         info->array.ctime = __le64_to_cpu(sb->ctime);
994         info->array.utime = __le64_to_cpu(sb->utime);
995         info->array.chunk_size = __le32_to_cpu(sb->chunksize)*512;
996         info->array.state =
997                 (__le64_to_cpu(sb->resync_offset) == MaxSector) ? 1 : 0;
998
999         super_offset = __le64_to_cpu(sb->super_offset);
1000         info->data_offset = __le64_to_cpu(sb->data_offset);
1001         info->component_size = __le64_to_cpu(sb->size);
1002         if (sb->feature_map & __le32_to_cpu(MD_FEATURE_BITMAP_OFFSET)) {
1003                 info->bitmap_offset = (int32_t)__le32_to_cpu(sb->bitmap_offset);
1004                 if (__le32_to_cpu(bsb->nodes) > 1)
1005                         info->array.state |= (1 << MD_SB_CLUSTERED);
1006         } else if (md_feature_any_ppl_on(sb->feature_map)) {
1007                 info->ppl_offset = __le16_to_cpu(sb->ppl.offset);
1008                 info->ppl_size = __le16_to_cpu(sb->ppl.size);
1009                 info->ppl_sector = super_offset + info->ppl_offset;
1010         }
1011
1012         info->disk.major = 0;
1013         info->disk.minor = 0;
1014         info->disk.number = __le32_to_cpu(sb->dev_number);
1015         if (__le32_to_cpu(sb->dev_number) >= __le32_to_cpu(sb->max_dev) ||
1016             __le32_to_cpu(sb->dev_number) >= MAX_DEVS)
1017                 role = MD_DISK_ROLE_FAULTY;
1018         else
1019                 role = __le16_to_cpu(sb->dev_roles[__le32_to_cpu(sb->dev_number)]);
1020
1021         if (info->array.level <= 0)
1022                 data_size = __le64_to_cpu(sb->data_size);
1023         else
1024                 data_size = __le64_to_cpu(sb->size);
1025         if (info->data_offset < super_offset) {
1026                 unsigned long long end;
1027                 info->space_before = info->data_offset;
1028                 end = super_offset;
1029
1030                 if (sb->bblog_offset && sb->bblog_size) {
1031                         unsigned long long bboffset = super_offset;
1032                         bboffset += (int32_t)__le32_to_cpu(sb->bblog_offset);
1033                         if (bboffset < end)
1034                                 end = bboffset;
1035                 }
1036
1037                 if (super_offset + info->bitmap_offset + info->ppl_offset < end)
1038                         end = super_offset + info->bitmap_offset +
1039                                 info->ppl_offset;
1040
1041                 if (info->data_offset + data_size < end)
1042                         info->space_after = end - data_size - info->data_offset;
1043                 else
1044                         info->space_after = 0;
1045         } else {
1046                 unsigned long long earliest;
1047                 earliest = super_offset + (32+4)*2; /* match kernel */
1048                 if (info->bitmap_offset > 0) {
1049                         unsigned long long bmend = info->bitmap_offset;
1050                         unsigned long long size = calc_bitmap_size(bsb, 4096);
1051                         size /= 512;
1052                         bmend += size;
1053                         if (bmend > earliest)
1054                                 earliest = bmend;
1055                 } else if (info->ppl_offset > 0) {
1056                         unsigned long long pplend;
1057
1058                         pplend = info->ppl_offset + info->ppl_size;
1059                         if (pplend > earliest)
1060                                 earliest = pplend;
1061                 }
1062                 if (sb->bblog_offset && sb->bblog_size) {
1063                         unsigned long long bbend = super_offset;
1064                         bbend += (int32_t)__le32_to_cpu(sb->bblog_offset);
1065                         bbend += __le16_to_cpu(sb->bblog_size);
1066                         if (bbend > earliest)
1067                                 earliest = bbend;
1068                 }
1069                 if (earliest < info->data_offset)
1070                         info->space_before = info->data_offset - earliest;
1071                 else
1072                         info->space_before = 0;
1073                 info->space_after = misc->device_size - data_size -
1074                         info->data_offset;
1075         }
1076         if (info->space_before == 0 && info->space_after == 0) {
1077                 /* It will look like we don't support data_offset changes,
1078                  * be we do - it's just that there is no room.
1079                  * A change that reduced the number of devices should
1080                  * still be allowed, so set the otherwise useless value of '1'
1081                  */
1082                 info->space_after = 1;
1083         }
1084
1085         info->disk.raid_disk = -1;
1086         switch(role) {
1087         case MD_DISK_ROLE_SPARE:
1088                 /* spare: not active, not sync, not faulty */
1089                 info->disk.state = 0;
1090                 break;
1091         case MD_DISK_ROLE_FAULTY:
1092                 info->disk.state = (1 << MD_DISK_FAULTY); /* faulty */
1093                 break;
1094         case MD_DISK_ROLE_JOURNAL:
1095                 info->disk.state = (1 << MD_DISK_JOURNAL);
1096                 info->disk.raid_disk = role;
1097                 /* journal uses all 4kB blocks*/
1098                 info->space_after = (misc->device_size - info->data_offset) % 8;
1099                 break;
1100         default:
1101                 info->disk.state = 6; /* active and in sync */
1102                 info->disk.raid_disk = role;
1103         }
1104         if (sb->devflags & WriteMostly1)
1105                 info->disk.state |= (1 << MD_DISK_WRITEMOSTLY);
1106         if (sb->devflags & FailFast1)
1107                 info->disk.state |= (1 << MD_DISK_FAILFAST);
1108         info->events = __le64_to_cpu(sb->events);
1109         sprintf(info->text_version, "1.%d", st->minor_version);
1110         info->safe_mode_delay = 200;
1111
1112         memcpy(info->uuid, sb->set_uuid, 16);
1113
1114         strncpy(info->name, sb->set_name, 32);
1115         info->name[32] = 0;
1116
1117         if ((__le32_to_cpu(sb->feature_map)&MD_FEATURE_REPLACEMENT)) {
1118                 info->disk.state &= ~(1 << MD_DISK_SYNC);
1119                 info->disk.state |=  1 << MD_DISK_REPLACEMENT;
1120         }
1121
1122         if (sb->feature_map & __le32_to_cpu(MD_FEATURE_RECOVERY_OFFSET))
1123                 info->recovery_start = __le32_to_cpu(sb->recovery_offset);
1124         else
1125                 info->recovery_start = MaxSector;
1126
1127         if (sb->feature_map & __le32_to_cpu(MD_FEATURE_RESHAPE_ACTIVE)) {
1128                 info->reshape_active = 1;
1129                 if ((sb->feature_map & __le32_to_cpu(MD_FEATURE_NEW_OFFSET)) &&
1130                     sb->new_offset != 0)
1131                         info->reshape_active |= RESHAPE_NO_BACKUP;
1132                 info->reshape_progress = __le64_to_cpu(sb->reshape_position);
1133                 info->new_level = __le32_to_cpu(sb->new_level);
1134                 info->delta_disks = __le32_to_cpu(sb->delta_disks);
1135                 info->new_layout = __le32_to_cpu(sb->new_layout);
1136                 info->new_chunk = __le32_to_cpu(sb->new_chunk)<<9;
1137                 if (info->delta_disks < 0)
1138                         info->array.raid_disks -= info->delta_disks;
1139         } else
1140                 info->reshape_active = 0;
1141
1142         info->recovery_blocked = info->reshape_active;
1143
1144         if (map)
1145                 for (i=0; i<map_disks; i++)
1146                         map[i] = 0;
1147         for (i = 0; i < __le32_to_cpu(sb->max_dev); i++) {
1148                 role = __le16_to_cpu(sb->dev_roles[i]);
1149                 if (/*role == MD_DISK_ROLE_SPARE || */role < (unsigned) info->array.raid_disks) {
1150                         working++;
1151                         if (map && role < map_disks)
1152                                 map[role] = 1;
1153                 }
1154         }
1155
1156         info->array.working_disks = working;
1157
1158         if (sb->feature_map & __le32_to_cpu(MD_FEATURE_JOURNAL)) {
1159                 info->journal_device_required = 1;
1160                 info->consistency_policy = CONSISTENCY_POLICY_JOURNAL;
1161         } else if (md_feature_any_ppl_on(sb->feature_map)) {
1162                 info->consistency_policy = CONSISTENCY_POLICY_PPL;
1163         } else if (sb->feature_map & __le32_to_cpu(MD_FEATURE_BITMAP_OFFSET)) {
1164                 info->consistency_policy = CONSISTENCY_POLICY_BITMAP;
1165         } else if (info->array.level <= 0) {
1166                 info->consistency_policy = CONSISTENCY_POLICY_NONE;
1167         } else {
1168                 info->consistency_policy = CONSISTENCY_POLICY_RESYNC;
1169         }
1170
1171         info->journal_clean = 0;
1172 }
1173
1174 static struct mdinfo *container_content1(struct supertype *st, char *subarray)
1175 {
1176         struct mdinfo *info;
1177
1178         if (subarray)
1179                 return NULL;
1180
1181         info = xmalloc(sizeof(*info));
1182         getinfo_super1(st, info, NULL);
1183         return info;
1184 }
1185
1186 static int update_super1(struct supertype *st, struct mdinfo *info,
1187                          char *update, char *devname, int verbose,
1188                          int uuid_set, char *homehost)
1189 {
1190         /* NOTE: for 'assemble' and 'force' we need to return non-zero
1191          * if any change was made.  For others, the return value is
1192          * ignored.
1193          */
1194         int rv = 0;
1195         struct mdp_superblock_1 *sb = st->sb;
1196         bitmap_super_t *bms = (bitmap_super_t*)(((char*)sb) + MAX_SB_SIZE);
1197
1198         if (strcmp(update, "homehost") == 0 &&
1199             homehost) {
1200                 /* Note that 'homehost' is special as it is really
1201                  * a "name" update.
1202                  */
1203                 char *c;
1204                 update = "name";
1205                 c = strchr(sb->set_name, ':');
1206                 if (c)
1207                         strncpy(info->name, c+1, 31 - (c-sb->set_name));
1208                 else
1209                         strncpy(info->name, sb->set_name, 32);
1210                 info->name[32] = 0;
1211         }
1212
1213         if (strcmp(update, "force-one")==0) {
1214                 /* Not enough devices for a working array,
1215                  * so bring this one up-to-date
1216                  */
1217                 if (sb->events != __cpu_to_le64(info->events))
1218                         rv = 1;
1219                 sb->events = __cpu_to_le64(info->events);
1220         } else if (strcmp(update, "force-array")==0) {
1221                 /* Degraded array and 'force' requests to
1222                  * maybe need to mark it 'clean'.
1223                  */
1224                 switch(__le32_to_cpu(sb->level)) {
1225                 case 4:
1226                 case 5:
1227                 case 6:
1228                         /* need to force clean */
1229                         if (sb->resync_offset != MaxSector)
1230                                 rv = 1;
1231                         sb->resync_offset = MaxSector;
1232                 }
1233         } else if (strcmp(update, "assemble")==0) {
1234                 int d = info->disk.number;
1235                 int want;
1236                 if (info->disk.state & (1<<MD_DISK_ACTIVE))
1237                         want = info->disk.raid_disk;
1238                 else if (info->disk.state & (1<<MD_DISK_JOURNAL))
1239                         want = MD_DISK_ROLE_JOURNAL;
1240                 else
1241                         want = MD_DISK_ROLE_SPARE;
1242                 if (sb->dev_roles[d] != __cpu_to_le16(want)) {
1243                         sb->dev_roles[d] = __cpu_to_le16(want);
1244                         rv = 1;
1245                 }
1246                 if (info->reshape_active &&
1247                     sb->feature_map &
1248                     __le32_to_cpu(MD_FEATURE_RESHAPE_ACTIVE) &&
1249                     info->delta_disks >= 0 &&
1250                     info->reshape_progress <
1251                     __le64_to_cpu(sb->reshape_position)) {
1252                         sb->reshape_position =
1253                                 __cpu_to_le64(info->reshape_progress);
1254                         rv = 1;
1255                 }
1256                 if (info->reshape_active &&
1257                     sb->feature_map &
1258                     __le32_to_cpu(MD_FEATURE_RESHAPE_ACTIVE) &&
1259                     info->delta_disks < 0 &&
1260                     info->reshape_progress >
1261                     __le64_to_cpu(sb->reshape_position)) {
1262                         sb->reshape_position =
1263                                 __cpu_to_le64(info->reshape_progress);
1264                         rv = 1;
1265                 }
1266         } else if (strcmp(update, "linear-grow-new") == 0) {
1267                 unsigned int i;
1268                 int fd;
1269                 unsigned int max = __le32_to_cpu(sb->max_dev);
1270
1271                 for (i = 0; i < max; i++)
1272                         if (__le16_to_cpu(sb->dev_roles[i]) >=
1273                             MD_DISK_ROLE_FAULTY)
1274                                 break;
1275                 sb->dev_number = __cpu_to_le32(i);
1276                 info->disk.number = i;
1277                 if (i >= max) {
1278                         sb->max_dev = __cpu_to_le32(max+1);
1279                 }
1280
1281                 random_uuid(sb->device_uuid);
1282
1283                 sb->dev_roles[i] = __cpu_to_le16(info->disk.raid_disk);
1284
1285                 fd = open(devname, O_RDONLY);
1286                 if (fd >= 0) {
1287                         unsigned long long ds;
1288                         get_dev_size(fd, devname, &ds);
1289                         close(fd);
1290                         ds >>= 9;
1291                         if (__le64_to_cpu(sb->super_offset) <
1292                             __le64_to_cpu(sb->data_offset)) {
1293                                 sb->data_size = __cpu_to_le64(
1294                                         ds - __le64_to_cpu(sb->data_offset));
1295                         } else {
1296                                 ds -= 8*2;
1297                                 ds &= ~(unsigned long long)(4*2-1);
1298                                 sb->super_offset = __cpu_to_le64(ds);
1299                                 sb->data_size = __cpu_to_le64(
1300                                         ds - __le64_to_cpu(sb->data_offset));
1301                         }
1302                 }
1303         } else if (strcmp(update, "linear-grow-update") == 0) {
1304                 int max = __le32_to_cpu(sb->max_dev);
1305                 sb->raid_disks = __cpu_to_le32(info->array.raid_disks);
1306                 if (info->array.raid_disks > max) {
1307                         sb->max_dev = __cpu_to_le32(max+1);
1308                 }
1309                 sb->dev_roles[info->disk.number] =
1310                         __cpu_to_le16(info->disk.raid_disk);
1311         } else if (strcmp(update, "resync") == 0) {
1312                 /* make sure resync happens */
1313                 sb->resync_offset = 0ULL;
1314         } else if (strcmp(update, "uuid") == 0) {
1315                 copy_uuid(sb->set_uuid, info->uuid, super1.swapuuid);
1316
1317                 if (__le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET)
1318                         memcpy(bms->uuid, sb->set_uuid, 16);
1319         } else if (strcmp(update, "no-bitmap") == 0) {
1320                 sb->feature_map &= ~__cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1321         } else if (strcmp(update, "bbl") == 0) {
1322                 /* only possible if there is room after the bitmap, or if
1323                  * there is no bitmap
1324                  */
1325                 unsigned long long sb_offset = __le64_to_cpu(sb->super_offset);
1326                 unsigned long long data_offset = __le64_to_cpu(sb->data_offset);
1327                 long bitmap_offset = 0;
1328                 long bm_sectors = 0;
1329                 long space;
1330
1331                 if (sb->feature_map & __cpu_to_le32(MD_FEATURE_BITMAP_OFFSET)) {
1332                         bitmap_offset = (long)__le32_to_cpu(sb->bitmap_offset);
1333                         bm_sectors = calc_bitmap_size(bms, 4096) >> 9;
1334                 } else if (md_feature_any_ppl_on(sb->feature_map)) {
1335                         bitmap_offset = (long)__le16_to_cpu(sb->ppl.offset);
1336                         bm_sectors = (long)__le16_to_cpu(sb->ppl.size);
1337                 }
1338
1339                 if (sb_offset < data_offset) {
1340                         /*
1341                          * 1.1 or 1.2.  Put bbl after bitmap leaving
1342                          * at least 32K
1343                          */
1344                         long bb_offset;
1345                         bb_offset = sb_offset + 8;
1346                         if (bm_sectors && bitmap_offset > 0)
1347                                 bb_offset = bitmap_offset + bm_sectors;
1348                         while (bb_offset < (long)sb_offset + 8 + 32*2 &&
1349                                bb_offset + 8+8 <= (long)data_offset)
1350                                 /* too close to bitmap, and room to grow */
1351                                 bb_offset += 8;
1352                         if (bb_offset + 8 <= (long)data_offset) {
1353                                 sb->bblog_size = __cpu_to_le16(8);
1354                                 sb->bblog_offset = __cpu_to_le32(bb_offset);
1355                         }
1356                 } else {
1357                         /* 1.0 - Put bbl just before super block */
1358                         if (bm_sectors && bitmap_offset < 0)
1359                                 space = -bitmap_offset - bm_sectors;
1360                         else
1361                                 space = sb_offset - data_offset -
1362                                         __le64_to_cpu(sb->data_size);
1363                         if (space >= 8) {
1364                                 sb->bblog_size = __cpu_to_le16(8);
1365                                 sb->bblog_offset = __cpu_to_le32((unsigned)-8);
1366                         }
1367                 }
1368         } else if (strcmp(update, "no-bbl") == 0) {
1369                 if (sb->feature_map & __cpu_to_le32(MD_FEATURE_BAD_BLOCKS))
1370                         pr_err("Cannot remove active bbl from %s\n",devname);
1371                 else {
1372                         sb->bblog_size = 0;
1373                         sb->bblog_shift = 0;
1374                         sb->bblog_offset = 0;
1375                 }
1376         } else if (strcmp(update, "force-no-bbl") == 0) {
1377                 sb->feature_map &= ~ __cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1378                 sb->bblog_size = 0;
1379                 sb->bblog_shift = 0;
1380                 sb->bblog_offset = 0;
1381         } else if (strcmp(update, "ppl") == 0) {
1382                 unsigned long long sb_offset = __le64_to_cpu(sb->super_offset);
1383                 unsigned long long data_offset = __le64_to_cpu(sb->data_offset);
1384                 unsigned long long data_size = __le64_to_cpu(sb->data_size);
1385                 long bb_offset = __le32_to_cpu(sb->bblog_offset);
1386                 int space;
1387                 int offset;
1388
1389                 if (sb->feature_map & __cpu_to_le32(MD_FEATURE_BITMAP_OFFSET)) {
1390                         pr_err("Cannot add PPL to array with bitmap\n");
1391                         return -2;
1392                 }
1393
1394                 if (sb->feature_map & __cpu_to_le32(MD_FEATURE_JOURNAL)) {
1395                         pr_err("Cannot add PPL to array with journal\n");
1396                         return -2;
1397                 }
1398
1399                 if (sb_offset < data_offset) {
1400                         if (bb_offset)
1401                                 space = bb_offset - 8;
1402                         else
1403                                 space = data_offset - sb_offset - 8;
1404                         offset = 8;
1405                 } else {
1406                         offset = -(sb_offset - data_offset - data_size);
1407                         if (offset < INT16_MIN)
1408                                 offset = INT16_MIN;
1409                         space = -(offset - bb_offset);
1410                 }
1411
1412                 if (space < (PPL_HEADER_SIZE >> 9) + 8) {
1413                         pr_err("Not enough space to add ppl\n");
1414                         return -2;
1415                 }
1416
1417                 if (space >= (MULTIPLE_PPL_AREA_SIZE_SUPER1 >> 9)) {
1418                         space = (MULTIPLE_PPL_AREA_SIZE_SUPER1 >> 9);
1419                 } else {
1420                         int optimal_space = choose_ppl_space(
1421                                                 __le32_to_cpu(sb->chunksize));
1422                         if (space > optimal_space)
1423                                 space = optimal_space;
1424                         if (space > UINT16_MAX)
1425                                 space = UINT16_MAX;
1426                 }
1427
1428                 sb->ppl.offset = __cpu_to_le16(offset);
1429                 sb->ppl.size = __cpu_to_le16(space);
1430                 sb->feature_map |= __cpu_to_le32(MD_FEATURE_PPL);
1431         } else if (strcmp(update, "no-ppl") == 0) {
1432                 sb->feature_map &= ~__cpu_to_le32(MD_FEATURE_PPL |
1433                                                    MD_FEATURE_MUTLIPLE_PPLS);
1434         } else if (strcmp(update, "name") == 0) {
1435                 if (info->name[0] == 0)
1436                         sprintf(info->name, "%d", info->array.md_minor);
1437                 memset(sb->set_name, 0, sizeof(sb->set_name));
1438                 if (homehost &&
1439                     strchr(info->name, ':') == NULL &&
1440                     strlen(homehost)+1+strlen(info->name) < 32) {
1441                         strcpy(sb->set_name, homehost);
1442                         strcat(sb->set_name, ":");
1443                         strcat(sb->set_name, info->name);
1444                 } else {
1445                         int namelen;
1446
1447                         namelen = min((int)strlen(info->name),
1448                                       (int)sizeof(sb->set_name) - 1);
1449                         memcpy(sb->set_name, info->name, namelen);
1450                         memset(&sb->set_name[namelen], '\0',
1451                                sizeof(sb->set_name) - namelen);
1452                 }
1453         } else if (strcmp(update, "devicesize") == 0 &&
1454                    __le64_to_cpu(sb->super_offset) <
1455                    __le64_to_cpu(sb->data_offset)) {
1456                 /* set data_size to device size less data_offset */
1457                 struct misc_dev_info *misc = (struct misc_dev_info*)
1458                         (st->sb + MAX_SB_SIZE + BM_SUPER_SIZE);
1459                 sb->data_size = __cpu_to_le64(
1460                         misc->device_size - __le64_to_cpu(sb->data_offset));
1461         } else if (strncmp(update, "revert-reshape", 14) == 0) {
1462                 rv = -2;
1463                 if (!(sb->feature_map &
1464                       __cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE)))
1465                         pr_err("No active reshape to revert on %s\n",
1466                                devname);
1467                 else {
1468                         __u32 temp;
1469                         unsigned long long reshape_sectors;
1470                         long reshape_chunk;
1471                         rv = 0;
1472                         /* If the reshape hasn't started, just stop it.
1473                          * It is conceivable that a stripe was modified but
1474                          * the metadata not updated.  In that case the backup
1475                          * should have been used to get passed the critical stage.
1476                          * If that couldn't happen, the "-nobackup" version
1477                          * will be used.
1478                          */
1479                         if (strcmp(update, "revert-reshape-nobackup") == 0 &&
1480                             sb->reshape_position == 0 &&
1481                             (__le32_to_cpu(sb->delta_disks) > 0 ||
1482                              (__le32_to_cpu(sb->delta_disks) == 0 &&
1483                               !(sb->feature_map & __cpu_to_le32(MD_FEATURE_RESHAPE_BACKWARDS))))) {
1484                                 sb->feature_map &= ~__cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1485                                 sb->raid_disks = __cpu_to_le32(__le32_to_cpu(sb->raid_disks) -
1486                                                                __le32_to_cpu(sb->delta_disks));
1487                                 sb->delta_disks = 0;
1488                                 goto done;
1489                         }
1490                         /* reshape_position is a little messy.
1491                          * Its value must be a multiple of the larger
1492                          * chunk size, and of the "after" data disks.
1493                          * So when reverting we need to change it to
1494                          * be a multiple of the new "after" data disks,
1495                          * which is the old "before".
1496                          * If it isn't already a multiple of 'before',
1497                          * the only thing we could do would be
1498                          * copy some block around on the disks, which
1499                          * is easy to get wrong.
1500                          * So we reject a revert-reshape unless the
1501                          * alignment is good.
1502                          */
1503                         if (__le32_to_cpu(sb->level) >= 4 &&
1504                             __le32_to_cpu(sb->level) <= 6) {
1505                                 reshape_sectors =
1506                                         __le64_to_cpu(sb->reshape_position);
1507                                 reshape_chunk = __le32_to_cpu(sb->new_chunk);
1508                                 reshape_chunk *= __le32_to_cpu(sb->raid_disks) -
1509                                         __le32_to_cpu(sb->delta_disks) -
1510                                         (__le32_to_cpu(sb->level)==6 ? 2 : 1);
1511                                 if (reshape_sectors % reshape_chunk) {
1512                                         pr_err("Reshape position is not suitably aligned.\n");
1513                                         pr_err("Try normal assembly and stop again\n");
1514                                         return -2;
1515                                 }
1516                         }
1517                         sb->raid_disks =
1518                                 __cpu_to_le32(__le32_to_cpu(sb->raid_disks) -
1519                                               __le32_to_cpu(sb->delta_disks));
1520                         if (sb->delta_disks == 0)
1521                                 sb->feature_map ^= __cpu_to_le32(MD_FEATURE_RESHAPE_BACKWARDS);
1522                         else
1523                                 sb->delta_disks = __cpu_to_le32(-__le32_to_cpu(sb->delta_disks));
1524
1525                         temp = sb->new_layout;
1526                         sb->new_layout = sb->layout;
1527                         sb->layout = temp;
1528
1529                         temp = sb->new_chunk;
1530                         sb->new_chunk = sb->chunksize;
1531                         sb->chunksize = temp;
1532
1533                         if (sb->feature_map &
1534                             __cpu_to_le32(MD_FEATURE_NEW_OFFSET)) {
1535                                 long offset_delta =
1536                                         (int32_t)__le32_to_cpu(sb->new_offset);
1537                                 sb->data_offset = __cpu_to_le64(__le64_to_cpu(sb->data_offset) + offset_delta);
1538                                 sb->new_offset = __cpu_to_le32(-offset_delta);
1539                                 sb->data_size = __cpu_to_le64(__le64_to_cpu(sb->data_size) - offset_delta);
1540                         }
1541                 done:;
1542                 }
1543         } else if (strcmp(update, "_reshape_progress") == 0)
1544                 sb->reshape_position = __cpu_to_le64(info->reshape_progress);
1545         else if (strcmp(update, "writemostly") == 0)
1546                 sb->devflags |= WriteMostly1;
1547         else if (strcmp(update, "readwrite") == 0)
1548                 sb->devflags &= ~WriteMostly1;
1549         else if (strcmp(update, "failfast") == 0)
1550                 sb->devflags |= FailFast1;
1551         else if (strcmp(update, "nofailfast") == 0)
1552                 sb->devflags &= ~FailFast1;
1553         else
1554                 rv = -1;
1555
1556         sb->sb_csum = calc_sb_1_csum(sb);
1557
1558         return rv;
1559 }
1560
1561 static int init_super1(struct supertype *st, mdu_array_info_t *info,
1562                        struct shape *s, char *name, char *homehost,
1563                        int *uuid, unsigned long long data_offset)
1564 {
1565         struct mdp_superblock_1 *sb;
1566         int spares;
1567         char defname[10];
1568         int sbsize;
1569
1570         if (posix_memalign((void**)&sb, 4096, SUPER1_SIZE) != 0) {
1571                 pr_err("could not allocate superblock\n");
1572                 return 0;
1573         }
1574         memset(sb, 0, SUPER1_SIZE);
1575
1576         st->sb = sb;
1577         if (info == NULL) {
1578                 /* zeroing superblock */
1579                 return 0;
1580         }
1581
1582         spares = info->working_disks - info->active_disks;
1583         if (info->raid_disks + spares  > MAX_DEVS) {
1584                 pr_err("too many devices requested: %d+%d > %d\n",
1585                         info->raid_disks , spares, MAX_DEVS);
1586                 return 0;
1587         }
1588
1589         sb->magic = __cpu_to_le32(MD_SB_MAGIC);
1590         sb->major_version = __cpu_to_le32(1);
1591         sb->feature_map = 0;
1592         sb->pad0 = 0;
1593
1594         if (uuid)
1595                 copy_uuid(sb->set_uuid, uuid, super1.swapuuid);
1596         else
1597                 random_uuid(sb->set_uuid);;
1598
1599         if (name == NULL || *name == 0) {
1600                 sprintf(defname, "%d", info->md_minor);
1601                 name = defname;
1602         }
1603         if (homehost &&
1604             strchr(name, ':')== NULL &&
1605             strlen(homehost)+1+strlen(name) < 32) {
1606                 strcpy(sb->set_name, homehost);
1607                 strcat(sb->set_name, ":");
1608                 strcat(sb->set_name, name);
1609         } else {
1610                 int namelen;
1611
1612                 namelen = min((int)strlen(name),
1613                               (int)sizeof(sb->set_name) - 1);
1614                 memcpy(sb->set_name, name, namelen);
1615                 memset(&sb->set_name[namelen], '\0',
1616                        sizeof(sb->set_name) - namelen);
1617         }
1618
1619         sb->ctime = __cpu_to_le64((unsigned long long)time(0));
1620         sb->level = __cpu_to_le32(info->level);
1621         sb->layout = __cpu_to_le32(info->layout);
1622         sb->size = __cpu_to_le64(s->size*2ULL);
1623         sb->chunksize = __cpu_to_le32(info->chunk_size>>9);
1624         sb->raid_disks = __cpu_to_le32(info->raid_disks);
1625
1626         sb->data_offset = __cpu_to_le64(data_offset);
1627         sb->data_size = __cpu_to_le64(0);
1628         sb->super_offset = __cpu_to_le64(0);
1629         sb->recovery_offset = __cpu_to_le64(0);
1630
1631         sb->utime = sb->ctime;
1632         sb->events = __cpu_to_le64(1);
1633         if (info->state & (1<<MD_SB_CLEAN))
1634                 sb->resync_offset = MaxSector;
1635         else
1636                 sb->resync_offset = 0;
1637         sbsize = sizeof(struct mdp_superblock_1) +
1638                 2 * (info->raid_disks + spares);
1639         sbsize = ROUND_UP(sbsize, 512);
1640         sb->max_dev =
1641                 __cpu_to_le32((sbsize - sizeof(struct mdp_superblock_1)) / 2);
1642
1643         memset(sb->dev_roles, 0xff,
1644                MAX_SB_SIZE - sizeof(struct mdp_superblock_1));
1645
1646         if (s->consistency_policy == CONSISTENCY_POLICY_PPL)
1647                 sb->feature_map |= __cpu_to_le32(MD_FEATURE_PPL);
1648
1649         return 1;
1650 }
1651
1652 struct devinfo {
1653         int fd;
1654         char *devname;
1655         long long data_offset;
1656         unsigned long long dev_size;
1657         mdu_disk_info_t disk;
1658         struct devinfo *next;
1659 };
1660
1661 /* Add a device to the superblock being created */
1662 static int add_to_super1(struct supertype *st, mdu_disk_info_t *dk,
1663                          int fd, char *devname, unsigned long long data_offset)
1664 {
1665         struct mdp_superblock_1 *sb = st->sb;
1666         __u16 *rp = sb->dev_roles + dk->number;
1667         struct devinfo *di, **dip;
1668         int dk_state;
1669
1670         dk_state = dk->state & ~(1<<MD_DISK_FAILFAST);
1671         if ((dk_state & (1<<MD_DISK_ACTIVE)) &&
1672             (dk_state & (1<<MD_DISK_SYNC)))/* active, sync */
1673                 *rp = __cpu_to_le16(dk->raid_disk);
1674         else if (dk_state & (1<<MD_DISK_JOURNAL))
1675                 *rp = MD_DISK_ROLE_JOURNAL;
1676         else if ((dk_state & ~(1<<MD_DISK_ACTIVE)) == 0)
1677                 /* active or idle -> spare */
1678                 *rp = MD_DISK_ROLE_SPARE;
1679         else
1680                 *rp = MD_DISK_ROLE_FAULTY;
1681
1682         if (dk->number >= (int)__le32_to_cpu(sb->max_dev) &&
1683             __le32_to_cpu(sb->max_dev) < MAX_DEVS)
1684                 sb->max_dev = __cpu_to_le32(dk->number+1);
1685
1686         sb->dev_number = __cpu_to_le32(dk->number);
1687         sb->devflags = 0; /* don't copy another disks flags */
1688         sb->sb_csum = calc_sb_1_csum(sb);
1689
1690         dip = (struct devinfo **)&st->info;
1691         while (*dip)
1692                 dip = &(*dip)->next;
1693         di = xmalloc(sizeof(struct devinfo));
1694         di->fd = fd;
1695         di->devname = devname;
1696         di->disk = *dk;
1697         di->data_offset = data_offset;
1698         get_dev_size(fd, NULL, &di->dev_size);
1699         di->next = NULL;
1700         *dip = di;
1701
1702         return 0;
1703 }
1704
1705 static int locate_bitmap1(struct supertype *st, int fd, int node_num);
1706
1707 static int store_super1(struct supertype *st, int fd)
1708 {
1709         struct mdp_superblock_1 *sb = st->sb;
1710         unsigned long long sb_offset;
1711         struct align_fd afd;
1712         int sbsize;
1713         unsigned long long dsize;
1714
1715         if (!get_dev_size(fd, NULL, &dsize))
1716                 return 1;
1717
1718         dsize >>= 9;
1719
1720         if (dsize < 24)
1721                 return 2;
1722
1723         init_afd(&afd, fd);
1724
1725         /*
1726          * Calculate the position of the superblock.
1727          * It is always aligned to a 4K boundary and
1728          * depending on minor_version, it can be:
1729          * 0: At least 8K, but less than 12K, from end of device
1730          * 1: At start of device
1731          * 2: 4K from start of device.
1732          */
1733         switch(st->minor_version) {
1734         case 0:
1735                 sb_offset = dsize;
1736                 sb_offset -= 8*2;
1737                 sb_offset &= ~(4*2-1);
1738                 break;
1739         case 1:
1740                 sb_offset = 0;
1741                 break;
1742         case 2:
1743                 sb_offset = 4*2;
1744                 break;
1745         default:
1746                 return -EINVAL;
1747         }
1748
1749         if (sb_offset != __le64_to_cpu(sb->super_offset) &&
1750             0 != __le64_to_cpu(sb->super_offset)
1751                 ) {
1752                 pr_err("internal error - sb_offset is wrong\n");
1753                 abort();
1754         }
1755
1756         if (lseek64(fd, sb_offset << 9, 0)< 0LL)
1757                 return 3;
1758
1759         sbsize = ROUND_UP(sizeof(*sb) + 2 * __le32_to_cpu(sb->max_dev), 512);
1760
1761         if (awrite(&afd, sb, sbsize) != sbsize)
1762                 return 4;
1763
1764         if (sb->feature_map & __cpu_to_le32(MD_FEATURE_BITMAP_OFFSET)) {
1765                 struct bitmap_super_s *bm = (struct bitmap_super_s*)
1766                         (((char*)sb)+MAX_SB_SIZE);
1767                 if (__le32_to_cpu(bm->magic) == BITMAP_MAGIC) {
1768                         locate_bitmap1(st, fd, 0);
1769                         if (awrite(&afd, bm, sizeof(*bm)) != sizeof(*bm))
1770                                 return 5;
1771                 }
1772         }
1773         fsync(fd);
1774
1775         return 0;
1776 }
1777
1778 static int load_super1(struct supertype *st, int fd, char *devname);
1779
1780 static unsigned long choose_bm_space(unsigned long devsize)
1781 {
1782         /* if the device is bigger than 8Gig, save 64k for bitmap usage,
1783          * if bigger than 200Gig, save 128k
1784          * NOTE: result must be multiple of 4K else bad things happen
1785          * on 4K-sector devices.
1786          */
1787         if (devsize < 64*2)
1788                 return 0;
1789         if (devsize - 64*2 >= 200*1024*1024*2)
1790                 return 128*2;
1791         if (devsize - 4*2 > 8*1024*1024*2)
1792                 return 64*2;
1793         return 4*2;
1794 }
1795
1796 static void free_super1(struct supertype *st);
1797
1798 __u32 crc32c_le(__u32 crc, unsigned char const *p, size_t len);
1799
1800 static int write_init_ppl1(struct supertype *st, struct mdinfo *info, int fd)
1801 {
1802         struct mdp_superblock_1 *sb = st->sb;
1803         void *buf;
1804         struct ppl_header *ppl_hdr;
1805         int ret;
1806
1807         /* first clear entire ppl space */
1808         ret = zero_disk_range(fd, info->ppl_sector, info->ppl_size);
1809         if (ret)
1810                 return ret;
1811
1812         ret = posix_memalign(&buf, 4096, PPL_HEADER_SIZE);
1813         if (ret) {
1814                 pr_err("Failed to allocate PPL header buffer\n");
1815                 return ret;
1816         }
1817
1818         memset(buf, 0, PPL_HEADER_SIZE);
1819         ppl_hdr = buf;
1820         memset(ppl_hdr->reserved, 0xff, PPL_HDR_RESERVED);
1821         ppl_hdr->signature = __cpu_to_le32(~crc32c_le(~0, sb->set_uuid,
1822                                                       sizeof(sb->set_uuid)));
1823         ppl_hdr->checksum = __cpu_to_le32(~crc32c_le(~0, buf, PPL_HEADER_SIZE));
1824
1825         if (lseek64(fd, info->ppl_sector * 512, SEEK_SET) < 0) {
1826                 ret = errno;
1827                 perror("Failed to seek to PPL header location");
1828         }
1829
1830         if (!ret && write(fd, buf, PPL_HEADER_SIZE) != PPL_HEADER_SIZE) {
1831                 ret = errno;
1832                 perror("Write PPL header failed");
1833         }
1834
1835         if (!ret)
1836                 fsync(fd);
1837
1838         free(buf);
1839         return ret;
1840 }
1841
1842 #define META_BLOCK_SIZE 4096
1843
1844 static int write_empty_r5l_meta_block(struct supertype *st, int fd)
1845 {
1846         struct r5l_meta_block *mb;
1847         struct mdp_superblock_1 *sb = st->sb;
1848         struct align_fd afd;
1849         __u32 crc;
1850
1851         init_afd(&afd, fd);
1852
1853         if (posix_memalign((void**)&mb, 4096, META_BLOCK_SIZE) != 0) {
1854                 pr_err("Could not allocate memory for the meta block.\n");
1855                 return 1;
1856         }
1857
1858         memset(mb, 0, META_BLOCK_SIZE);
1859
1860         mb->magic = __cpu_to_le32(R5LOG_MAGIC);
1861         mb->version = R5LOG_VERSION;
1862         mb->meta_size = __cpu_to_le32(sizeof(struct r5l_meta_block));
1863         mb->seq = __cpu_to_le64(random32());
1864         mb->position = __cpu_to_le64(0);
1865
1866         crc = crc32c_le(0xffffffff, sb->set_uuid, sizeof(sb->set_uuid));
1867         crc = crc32c_le(crc, (void *)mb, META_BLOCK_SIZE);
1868         mb->checksum = crc;
1869
1870         if (lseek64(fd, __le64_to_cpu(sb->data_offset) * 512, 0) < 0LL) {
1871                 pr_err("cannot seek to offset of the meta block\n");
1872                 goto fail_to_write;
1873         }
1874
1875         if (awrite(&afd, mb, META_BLOCK_SIZE) != META_BLOCK_SIZE) {
1876                 pr_err("failed to store write the meta block \n");
1877                 goto fail_to_write;
1878         }
1879         fsync(fd);
1880
1881         free(mb);
1882         return 0;
1883
1884 fail_to_write:
1885         free(mb);
1886         return 1;
1887 }
1888
1889 static int write_init_super1(struct supertype *st)
1890 {
1891         struct mdp_superblock_1 *sb = st->sb;
1892         struct supertype *refst;
1893         int rv = 0;
1894         unsigned long long bm_space;
1895         struct devinfo *di;
1896         unsigned long long dsize, array_size;
1897         unsigned long long sb_offset;
1898         unsigned long long data_offset;
1899         long bm_offset;
1900         int raid0_need_layout = 0;
1901
1902         for (di = st->info; di; di = di->next) {
1903                 if (di->disk.state & (1 << MD_DISK_JOURNAL))
1904                         sb->feature_map |= __cpu_to_le32(MD_FEATURE_JOURNAL);
1905                 if (sb->level == 0 && sb->layout != 0) {
1906                         struct devinfo *di2 = st->info;
1907                         unsigned long long s1, s2;
1908                         s1 = di->dev_size;
1909                         if (di->data_offset != INVALID_SECTORS)
1910                                 s1 -= di->data_offset;
1911                         s1 /= __le32_to_cpu(sb->chunksize);
1912                         s2 = di2->dev_size;
1913                         if (di2->data_offset != INVALID_SECTORS)
1914                                 s2 -= di2->data_offset;
1915                         s2 /= __le32_to_cpu(sb->chunksize);
1916                         if (s1 != s2)
1917                                 raid0_need_layout = 1;
1918                 }
1919         }
1920
1921         for (di = st->info; di; di = di->next) {
1922                 if (di->disk.state & (1 << MD_DISK_FAULTY))
1923                         continue;
1924                 if (di->fd < 0)
1925                         continue;
1926
1927                 while (Kill(di->devname, NULL, 0, -1, 1) == 0)
1928                         ;
1929
1930                 sb->dev_number = __cpu_to_le32(di->disk.number);
1931                 if (di->disk.state & (1<<MD_DISK_WRITEMOSTLY))
1932                         sb->devflags |= WriteMostly1;
1933                 else
1934                         sb->devflags &= ~WriteMostly1;
1935                 if (di->disk.state & (1<<MD_DISK_FAILFAST))
1936                         sb->devflags |= FailFast1;
1937                 else
1938                         sb->devflags &= ~FailFast1;
1939
1940                 random_uuid(sb->device_uuid);
1941
1942                 if (!(di->disk.state & (1<<MD_DISK_JOURNAL)))
1943                         sb->events = 0;
1944
1945                 refst = dup_super(st);
1946                 if (load_super1(refst, di->fd, NULL)==0) {
1947                         struct mdp_superblock_1 *refsb = refst->sb;
1948
1949                         memcpy(sb->device_uuid, refsb->device_uuid, 16);
1950                         if (memcmp(sb->set_uuid, refsb->set_uuid, 16)==0) {
1951                                 /* same array, so preserve events and
1952                                  * dev_number */
1953                                 sb->events = refsb->events;
1954                                 /* bugs in 2.6.17 and earlier mean the
1955                                  * dev_number chosen in Manage must be preserved
1956                                  */
1957                                 if (get_linux_version() >= 2006018)
1958                                         sb->dev_number = refsb->dev_number;
1959                         }
1960                         free_super1(refst);
1961                 }
1962                 free(refst);
1963
1964                 if (!get_dev_size(di->fd, NULL, &dsize)) {
1965                         rv = 1;
1966                         goto error_out;
1967                 }
1968                 dsize >>= 9;
1969
1970                 if (dsize < 24) {
1971                         close(di->fd);
1972                         rv = 2;
1973                         goto error_out;
1974                 }
1975
1976                 /*
1977                  * Calculate the position of the superblock.
1978                  * It is always aligned to a 4K boundary and
1979                  * depending on minor_version, it can be:
1980                  * 0: At least 8K, but less than 12K, from end of device
1981                  * 1: At start of device
1982                  * 2: 4K from start of device.
1983                  * data_offset has already been set.
1984                  */
1985                 array_size = __le64_to_cpu(sb->size);
1986
1987                 /* work out how much space we left for a bitmap */
1988                 if (sb->feature_map & __cpu_to_le32(MD_FEATURE_BITMAP_OFFSET)) {
1989                         bitmap_super_t *bms = (bitmap_super_t *)
1990                                         (((char *)sb) + MAX_SB_SIZE);
1991                         bm_space = calc_bitmap_size(bms, 4096) >> 9;
1992                         bm_offset = (long)__le32_to_cpu(sb->bitmap_offset);
1993                 } else if (md_feature_any_ppl_on(sb->feature_map)) {
1994                         bm_space = MULTIPLE_PPL_AREA_SIZE_SUPER1 >> 9;
1995                         if (st->minor_version == 0)
1996                                 bm_offset = -bm_space - 8;
1997                         else
1998                                 bm_offset = 8;
1999                         sb->ppl.offset = __cpu_to_le16(bm_offset);
2000                         sb->ppl.size = __cpu_to_le16(bm_space);
2001                 } else {
2002                         bm_space = choose_bm_space(array_size);
2003                         bm_offset = 8;
2004                 }
2005
2006                 data_offset = di->data_offset;
2007                 if (data_offset == INVALID_SECTORS)
2008                         data_offset = st->data_offset;
2009                 switch(st->minor_version) {
2010                 case 0:
2011                         /* Add 8 sectors for bad block log */
2012                         bm_space += 8;
2013                         if (data_offset == INVALID_SECTORS)
2014                                 data_offset = 0;
2015                         sb_offset = dsize;
2016                         sb_offset -= 8*2;
2017                         sb_offset &= ~(4*2-1);
2018                         sb->data_offset = __cpu_to_le64(data_offset);
2019                         sb->super_offset = __cpu_to_le64(sb_offset);
2020                         if (sb_offset < array_size + bm_space)
2021                                 bm_space = sb_offset - array_size;
2022                         sb->data_size = __cpu_to_le64(sb_offset - bm_space);
2023                         if (bm_space >= 8) {
2024                                 sb->bblog_size = __cpu_to_le16(8);
2025                                 sb->bblog_offset = __cpu_to_le32((unsigned)-8);
2026                         }
2027                         break;
2028                 case 1:
2029                 case 2:
2030                         sb_offset = st->minor_version == 2 ? 8 : 0;
2031                         sb->super_offset = __cpu_to_le64(sb_offset);
2032                         if (data_offset == INVALID_SECTORS)
2033                                 data_offset = sb_offset + 16;
2034
2035                         sb->data_offset = __cpu_to_le64(data_offset);
2036                         sb->data_size = __cpu_to_le64(dsize - data_offset);
2037                         if (data_offset >= sb_offset+bm_offset+bm_space+8) {
2038                                 sb->bblog_size = __cpu_to_le16(8);
2039                                 sb->bblog_offset = __cpu_to_le32(bm_offset +
2040                                                                  bm_space);
2041                         } else if (data_offset >= sb_offset + 16) {
2042                                 sb->bblog_size = __cpu_to_le16(8);
2043                                 /* '8' sectors for the bblog, and 'sb_offset'
2044                                  * because we want offset from superblock, not
2045                                  * start of device.
2046                                  */
2047                                 sb->bblog_offset = __cpu_to_le32(data_offset -
2048                                                                  8 - sb_offset);
2049                         }
2050                         break;
2051                 default:
2052                         pr_err("Failed to write invalid metadata format 1.%i to %s\n",
2053                                st->minor_version, di->devname);
2054                         rv = -EINVAL;
2055                         goto out;
2056                 }
2057                 /*
2058                  * Disable badblock log on clusters, or when
2059                  * explicitly requested
2060                  */
2061                 if (st->nodes > 0 || conf_get_create_info()->bblist == 0) {
2062                         sb->bblog_size = 0;
2063                         sb->bblog_offset = 0;
2064                 }
2065
2066                 /* RAID0 needs a layout if devices aren't all the same size */
2067                 if (raid0_need_layout)
2068                         sb->feature_map |= __cpu_to_le32(MD_FEATURE_RAID0_LAYOUT);
2069
2070                 sb->sb_csum = calc_sb_1_csum(sb);
2071                 rv = store_super1(st, di->fd);
2072
2073                 if (rv == 0 && (di->disk.state & (1 << MD_DISK_JOURNAL))) {
2074                         rv = write_empty_r5l_meta_block(st, di->fd);
2075                         if (rv)
2076                                 goto error_out;
2077                 }
2078
2079                 if (rv == 0 &&
2080                     (__le32_to_cpu(sb->feature_map) &
2081                      MD_FEATURE_BITMAP_OFFSET)) {
2082                         rv = st->ss->write_bitmap(st, di->fd, NodeNumUpdate);
2083                 } else if (rv == 0 &&
2084                     md_feature_any_ppl_on(sb->feature_map)) {
2085                         struct mdinfo info;
2086
2087                         st->ss->getinfo_super(st, &info, NULL);
2088                         rv = st->ss->write_init_ppl(st, &info, di->fd);
2089                 }
2090
2091                 close(di->fd);
2092                 di->fd = -1;
2093                 if (rv)
2094                         goto error_out;
2095         }
2096 error_out:
2097         if (rv)
2098                 pr_err("Failed to write metadata to %s\n", di->devname);
2099 out:
2100         return rv;
2101 }
2102
2103 static int compare_super1(struct supertype *st, struct supertype *tst)
2104 {
2105         /*
2106          * return:
2107          *  0 same, or first was empty, and second was copied
2108          *  1 second had wrong number
2109          *  2 wrong uuid
2110          *  3 wrong other info
2111          */
2112         struct mdp_superblock_1 *first = st->sb;
2113         struct mdp_superblock_1 *second = tst->sb;
2114
2115         if (second->magic != __cpu_to_le32(MD_SB_MAGIC))
2116                 return 1;
2117         if (second->major_version != __cpu_to_le32(1))
2118                 return 1;
2119
2120         if (!first) {
2121                 if (posix_memalign((void**)&first, 4096, SUPER1_SIZE) != 0) {
2122                         pr_err("could not allocate superblock\n");
2123                         return 1;
2124                 }
2125                 memcpy(first, second, SUPER1_SIZE);
2126                 st->sb = first;
2127                 return 0;
2128         }
2129         if (memcmp(first->set_uuid, second->set_uuid, 16)!= 0)
2130                 return 2;
2131
2132         if (first->ctime      != second->ctime     ||
2133             first->level      != second->level     ||
2134             first->layout     != second->layout    ||
2135             first->size       != second->size      ||
2136             first->chunksize  != second->chunksize ||
2137             first->raid_disks != second->raid_disks)
2138                 return 3;
2139         return 0;
2140 }
2141
2142 static int load_super1(struct supertype *st, int fd, char *devname)
2143 {
2144         unsigned long long dsize;
2145         unsigned long long sb_offset;
2146         struct mdp_superblock_1 *super;
2147         int uuid[4];
2148         struct bitmap_super_s *bsb;
2149         struct misc_dev_info *misc;
2150         struct align_fd afd;
2151
2152         free_super1(st);
2153
2154         init_afd(&afd, fd);
2155
2156         if (st->ss == NULL || st->minor_version == -1) {
2157                 int bestvers = -1;
2158                 struct supertype tst;
2159                 __u64 bestctime = 0;
2160                 /* guess... choose latest ctime */
2161                 memset(&tst, 0, sizeof(tst));
2162                 tst.ss = &super1;
2163                 for (tst.minor_version = 0; tst.minor_version <= 2;
2164                      tst.minor_version++) {
2165                         switch(load_super1(&tst, fd, devname)) {
2166                         case 0: super = tst.sb;
2167                                 if (bestvers == -1 ||
2168                                     bestctime < __le64_to_cpu(super->ctime)) {
2169                                         bestvers = tst.minor_version;
2170                                         bestctime = __le64_to_cpu(super->ctime);
2171                                 }
2172                                 free(super);
2173                                 tst.sb = NULL;
2174                                 break;
2175                         case 1: return 1; /*bad device */
2176                         case 2: break; /* bad, try next */
2177                         }
2178                 }
2179                 if (bestvers != -1) {
2180                         int rv;
2181                         tst.minor_version = bestvers;
2182                         tst.ss = &super1;
2183                         tst.max_devs = MAX_DEVS;
2184                         rv = load_super1(&tst, fd, devname);
2185                         if (rv == 0)
2186                                 *st = tst;
2187                         return rv;
2188                 }
2189                 return 2;
2190         }
2191         if (!get_dev_size(fd, devname, &dsize))
2192                 return 1;
2193         dsize >>= 9;
2194
2195         if (dsize < 24) {
2196                 if (devname)
2197                         pr_err("%s is too small for md: size is %llu sectors.\n",
2198                                 devname, dsize);
2199                 return 1;
2200         }
2201
2202         /*
2203          * Calculate the position of the superblock.
2204          * It is always aligned to a 4K boundary and
2205          * depending on minor_version, it can be:
2206          * 0: At least 8K, but less than 12K, from end of device
2207          * 1: At start of device
2208          * 2: 4K from start of device.
2209          */
2210         switch(st->minor_version) {
2211         case 0:
2212                 sb_offset = dsize;
2213                 sb_offset -= 8*2;
2214                 sb_offset &= ~(4*2-1);
2215                 break;
2216         case 1:
2217                 sb_offset = 0;
2218                 break;
2219         case 2:
2220                 sb_offset = 4*2;
2221                 break;
2222         default:
2223                 return -EINVAL;
2224         }
2225
2226         if (lseek64(fd, sb_offset << 9, 0)< 0LL) {
2227                 if (devname)
2228                         pr_err("Cannot seek to superblock on %s: %s\n",
2229                                 devname, strerror(errno));
2230                 return 1;
2231         }
2232
2233         if (posix_memalign((void**)&super, 4096, SUPER1_SIZE) != 0) {
2234                 pr_err("could not allocate superblock\n");
2235                 return 1;
2236         }
2237
2238         memset(super, 0, SUPER1_SIZE);
2239
2240         if (aread(&afd, super, MAX_SB_SIZE) != MAX_SB_SIZE) {
2241                 if (devname)
2242                         pr_err("Cannot read superblock on %s\n",
2243                                 devname);
2244                 free(super);
2245                 return 1;
2246         }
2247
2248         if (__le32_to_cpu(super->magic) != MD_SB_MAGIC) {
2249                 if (devname)
2250                         pr_err("No super block found on %s (Expected magic %08x, got %08x)\n",
2251                                 devname, MD_SB_MAGIC,
2252                                __le32_to_cpu(super->magic));
2253                 free(super);
2254                 return 2;
2255         }
2256
2257         if (__le32_to_cpu(super->major_version) != 1) {
2258                 if (devname)
2259                         pr_err("Cannot interpret superblock on %s - version is %d\n",
2260                                 devname, __le32_to_cpu(super->major_version));
2261                 free(super);
2262                 return 2;
2263         }
2264         if (__le64_to_cpu(super->super_offset) != sb_offset) {
2265                 if (devname)
2266                         pr_err("No superblock found on %s (super_offset is wrong)\n",
2267                                 devname);
2268                 free(super);
2269                 return 2;
2270         }
2271         st->sb = super;
2272
2273         bsb = (struct bitmap_super_s *)(((char*)super)+MAX_SB_SIZE);
2274
2275         misc = (struct misc_dev_info*)
2276           (((char*)super)+MAX_SB_SIZE+BM_SUPER_SIZE);
2277         misc->device_size = dsize;
2278         if (st->data_offset == INVALID_SECTORS)
2279                 st->data_offset = __le64_to_cpu(super->data_offset);
2280
2281         /* Now check on the bitmap superblock */
2282         if ((__le32_to_cpu(super->feature_map)&MD_FEATURE_BITMAP_OFFSET) == 0)
2283                 return 0;
2284         /* Read the bitmap superblock and make sure it looks
2285          * valid.  If it doesn't clear the bit.  An --assemble --force
2286          * should get that written out.
2287          */
2288         locate_bitmap1(st, fd, 0);
2289         if (aread(&afd, bsb, 512) != 512)
2290                 goto no_bitmap;
2291
2292         uuid_from_super1(st, uuid);
2293         if (__le32_to_cpu(bsb->magic) != BITMAP_MAGIC ||
2294             memcmp(bsb->uuid, uuid, 16) != 0)
2295                 goto no_bitmap;
2296         return 0;
2297
2298  no_bitmap:
2299         super->feature_map = __cpu_to_le32(__le32_to_cpu(super->feature_map)
2300                                            & ~MD_FEATURE_BITMAP_OFFSET);
2301         return 0;
2302 }
2303
2304 static struct supertype *match_metadata_desc1(char *arg)
2305 {
2306         struct supertype *st = xcalloc(1, sizeof(*st));
2307
2308         st->container_devnm[0] = 0;
2309         st->ss = &super1;
2310         st->max_devs = MAX_DEVS;
2311         st->sb = NULL;
2312         st->data_offset = INVALID_SECTORS;
2313         /* leading zeros can be safely ignored.  --detail generates them. */
2314         while (*arg == '0')
2315                 arg++;
2316         if (strcmp(arg, "1.0") == 0 || strcmp(arg, "1.00") == 0) {
2317                 st->minor_version = 0;
2318                 return st;
2319         }
2320         if (strcmp(arg, "1.1") == 0 || strcmp(arg, "1.01") == 0
2321                 ) {
2322                 st->minor_version = 1;
2323                 return st;
2324         }
2325         if (strcmp(arg, "1.2") == 0 ||
2326 #ifndef DEFAULT_OLD_METADATA /* ifdef in super0.c */
2327             strcmp(arg, "default") == 0 ||
2328 #endif /* DEFAULT_OLD_METADATA */
2329             strcmp(arg, "1.02") == 0) {
2330                 st->minor_version = 2;
2331                 return st;
2332         }
2333         if (strcmp(arg, "1") == 0 || strcmp(arg, "default") == 0) {
2334                 st->minor_version = -1;
2335                 return st;
2336         }
2337
2338         free(st);
2339         return NULL;
2340 }
2341
2342 /* find available size on device with this devsize, using
2343  * superblock type st, and reserving 'reserve' sectors for
2344  * a possible bitmap
2345  */
2346 static __u64 avail_size1(struct supertype *st, __u64 devsize,
2347                          unsigned long long data_offset)
2348 {
2349         struct mdp_superblock_1 *super = st->sb;
2350         int bmspace = 0;
2351         int bbspace = 0;
2352         if (devsize < 24)
2353                 return 0;
2354
2355         if (__le32_to_cpu(super->feature_map) & MD_FEATURE_BITMAP_OFFSET) {
2356                 /* hot-add. allow for actual size of bitmap */
2357                 struct bitmap_super_s *bsb;
2358                 bsb = (struct bitmap_super_s *)(((char*)super)+MAX_SB_SIZE);
2359                 bmspace = calc_bitmap_size(bsb, 4096) >> 9;
2360         } else if (md_feature_any_ppl_on(super->feature_map)) {
2361                 bmspace = __le16_to_cpu(super->ppl.size);
2362         }
2363
2364         /* Allow space for bad block log */
2365         if (super->bblog_size)
2366                 bbspace = __le16_to_cpu(super->bblog_size);
2367
2368         if (st->minor_version < 0)
2369                 /* not specified, so time to set default */
2370                 st->minor_version = 2;
2371
2372         if (data_offset == INVALID_SECTORS)
2373                 data_offset = st->data_offset;
2374
2375         if (data_offset != INVALID_SECTORS)
2376                 switch(st->minor_version) {
2377                 case 0:
2378                         return devsize - data_offset - 8*2 - bbspace;
2379                 case 1:
2380                 case 2:
2381                         return devsize - data_offset;
2382                 default:
2383                         return 0;
2384                 }
2385
2386         devsize -= bmspace;
2387
2388         switch(st->minor_version) {
2389         case 0:
2390                 /* at end */
2391                 return ((devsize - 8*2 - bbspace ) & ~(4*2-1));
2392         case 1:
2393                 /* at start, 4K for superblock and possible bitmap */
2394                 return devsize - 4*2 - bbspace;
2395         case 2:
2396                 /* 4k from start, 4K for superblock and possible bitmap */
2397                 return devsize - (4+4)*2 - bbspace;
2398         }
2399         return 0;
2400 }
2401
2402 static int
2403 add_internal_bitmap1(struct supertype *st,
2404                      int *chunkp, int delay, int write_behind,
2405                      unsigned long long size,
2406                      int may_change, int major)
2407 {
2408         /*
2409          * If not may_change, then this is a 'Grow' without sysfs support for
2410          * bitmaps, and the bitmap must fit after the superblock at 1K offset.
2411          * If may_change, then this is create or a Grow with sysfs support,
2412          * and we can put the bitmap wherever we like.
2413          *
2414          * size is in sectors,  chunk is in bytes !!!
2415          */
2416
2417         unsigned long long bits;
2418         unsigned long long max_bits;
2419         unsigned long long min_chunk;
2420         long offset;
2421         long bbl_offset, bbl_size;
2422         unsigned long long chunk = *chunkp;
2423         int room = 0;
2424         int creating = 0;
2425         int len;
2426         struct mdp_superblock_1 *sb = st->sb;
2427         bitmap_super_t *bms = (bitmap_super_t*)(((char*)sb) + MAX_SB_SIZE);
2428         int uuid[4];
2429
2430         if (__le64_to_cpu(sb->data_size) == 0)
2431                 /*
2432                  * Must be creating the array, else data_size
2433                  * would be non-zero
2434                  */
2435                 creating = 1;
2436         switch(st->minor_version) {
2437         case 0:
2438                 /*
2439                  * either 3K after the superblock (when hot-add),
2440                  * or some amount of space before.
2441                  */
2442                 if (creating) {
2443                         /*
2444                          * We are creating array, so we *know* how much room has
2445                          * been left.
2446                          */
2447                         offset = 0;
2448                         bbl_size = 8;
2449                         room =
2450                           choose_bm_space(__le64_to_cpu(sb->size)) + bbl_size;
2451                 } else {
2452                         room = __le64_to_cpu(sb->super_offset)
2453                                 - __le64_to_cpu(sb->data_offset)
2454                                 - __le64_to_cpu(sb->data_size);
2455                         bbl_size = __le16_to_cpu(sb->bblog_size);
2456                         if (bbl_size < 8)
2457                                 bbl_size = 8;
2458                         bbl_offset = (__s32)__le32_to_cpu(sb->bblog_offset);
2459                         if (bbl_size < -bbl_offset)
2460                                 bbl_size = -bbl_offset;
2461
2462                         if (!may_change ||
2463                             (room < 3*2 && __le32_to_cpu(sb->max_dev) <= 384)) {
2464                                 room = 3*2;
2465                                 offset = 1*2;
2466                                 bbl_size = 0;
2467                         } else {
2468                                 offset = 0; /* means movable offset */
2469                         }
2470                 }
2471                 break;
2472         case 1:
2473         case 2: /* between superblock and data */
2474                 if (creating) {
2475                         offset = 4*2;
2476                         bbl_size = 8;
2477                         room =
2478                           choose_bm_space(__le64_to_cpu(sb->size)) + bbl_size;
2479                 } else {
2480                         room = __le64_to_cpu(sb->data_offset)
2481                                 - __le64_to_cpu(sb->super_offset);
2482                         bbl_size = __le16_to_cpu(sb->bblog_size);
2483                         if (bbl_size)
2484                                 room =
2485                                   __le32_to_cpu(sb->bblog_offset) + bbl_size;
2486                         else
2487                                 bbl_size = 8;
2488
2489                         if (!may_change) {
2490                                 room -= 2; /* Leave 1K for superblock */
2491                                 offset = 2;
2492                                 bbl_size = 0;
2493                         } else {
2494                                 room -= 4*2; /* leave 4K for superblock */
2495                                 offset = 4*2;
2496                         }
2497                 }
2498                 break;
2499         default:
2500                 return -ENOSPC;
2501         }
2502
2503         room -= bbl_size;
2504         if (chunk == UnSet && room > 128*2)
2505                 /* Limit to 128K of bitmap when chunk size not requested */
2506                 room = 128*2;
2507
2508         if (room <= 1)
2509                 /* No room for a bitmap */
2510                 return -ENOSPC;
2511
2512         max_bits = (room * 512 - sizeof(bitmap_super_t)) * 8;
2513
2514         min_chunk = 4096; /* sub-page chunks don't work yet.. */
2515         bits = (size*512)/min_chunk +1;
2516         while (bits > max_bits) {
2517                 min_chunk *= 2;
2518                 bits = (bits+1)/2;
2519         }
2520         if (chunk == UnSet) {
2521                 /* For practical purpose, 64Meg is a good
2522                  * default chunk size for internal bitmaps.
2523                  */
2524                 chunk = min_chunk;
2525                 if (chunk < 64*1024*1024)
2526                         chunk = 64*1024*1024;
2527         } else if (chunk < min_chunk)
2528                 return -EINVAL; /* chunk size too small */
2529         if (chunk == 0) /* rounding problem */
2530                 return -EINVAL;
2531
2532         if (offset == 0) {
2533                 /* start bitmap on a 4K boundary with enough space for
2534                  * the bitmap
2535                  */
2536                 bits = (size*512) / chunk + 1;
2537                 room = ((bits+7)/8 + sizeof(bitmap_super_t) +4095)/4096;
2538                 room *= 8; /* convert 4K blocks to sectors */
2539                 offset = -room - bbl_size;
2540         }
2541
2542         sb->bitmap_offset = (int32_t)__cpu_to_le32(offset);
2543
2544         sb->feature_map = __cpu_to_le32(__le32_to_cpu(sb->feature_map) |
2545                                         MD_FEATURE_BITMAP_OFFSET);
2546         memset(bms, 0, sizeof(*bms));
2547         bms->magic = __cpu_to_le32(BITMAP_MAGIC);
2548         bms->version = __cpu_to_le32(major);
2549         uuid_from_super1(st, uuid);
2550         memcpy(bms->uuid, uuid, 16);
2551         bms->chunksize = __cpu_to_le32(chunk);
2552         bms->daemon_sleep = __cpu_to_le32(delay);
2553         bms->sync_size = __cpu_to_le64(size);
2554         bms->write_behind = __cpu_to_le32(write_behind);
2555         bms->nodes = __cpu_to_le32(st->nodes);
2556         if (st->nodes)
2557                 sb->feature_map = __cpu_to_le32(__le32_to_cpu(sb->feature_map) |
2558                                                 MD_FEATURE_BITMAP_VERSIONED);
2559         if (st->cluster_name) {
2560                 len = sizeof(bms->cluster_name);
2561                 strncpy((char *)bms->cluster_name, st->cluster_name, len);
2562                 bms->cluster_name[len - 1] = '\0';
2563         }
2564
2565         *chunkp = chunk;
2566         return 0;
2567 }
2568
2569 static int locate_bitmap1(struct supertype *st, int fd, int node_num)
2570 {
2571         unsigned long long offset;
2572         struct mdp_superblock_1 *sb;
2573         int mustfree = 0;
2574         int ret;
2575
2576         if (!st->sb) {
2577                 if (st->ss->load_super(st, fd, NULL))
2578                         return -1; /* no error I hope... */
2579                 mustfree = 1;
2580         }
2581         sb = st->sb;
2582
2583         if ((__le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET))
2584                 ret = 0;
2585         else
2586                 ret = -1;
2587         offset = __le64_to_cpu(sb->super_offset);
2588         offset += (int32_t) __le32_to_cpu(sb->bitmap_offset) * (node_num + 1);
2589         if (mustfree)
2590                 free(sb);
2591         lseek64(fd, offset<<9, 0);
2592         return ret;
2593 }
2594
2595 static int write_bitmap1(struct supertype *st, int fd, enum bitmap_update update)
2596 {
2597         struct mdp_superblock_1 *sb = st->sb;
2598         bitmap_super_t *bms = (bitmap_super_t*)(((char*)sb)+MAX_SB_SIZE);
2599         int rv = 0;
2600         void *buf;
2601         int towrite, n, len;
2602         struct align_fd afd;
2603         unsigned int i = 0;
2604         unsigned long long total_bm_space, bm_space_per_node;
2605
2606         switch (update) {
2607         case NameUpdate:
2608                 /* update cluster name */
2609                 if (st->cluster_name) {
2610                         len = sizeof(bms->cluster_name);
2611                         memset((char *)bms->cluster_name, 0, len);
2612                         strncpy((char *)bms->cluster_name,
2613                                 st->cluster_name, len);
2614                         bms->cluster_name[len - 1] = '\0';
2615                 }
2616                 break;
2617         case NodeNumUpdate:
2618                 /* cluster md only supports superblock 1.2 now */
2619                 if (st->minor_version != 2 &&
2620                     bms->version == BITMAP_MAJOR_CLUSTERED) {
2621                         pr_err("Warning: cluster md only works with superblock 1.2\n");
2622                         return -EINVAL;
2623                 }
2624
2625                 if (bms->version == BITMAP_MAJOR_CLUSTERED) {
2626                         if (__cpu_to_le32(st->nodes) < bms->nodes) {
2627                                 /*
2628                                  * Since the nodes num is not increased, no
2629                                  * need to check the space enough or not,
2630                                  * just update bms->nodes
2631                                  */
2632                                 bms->nodes = __cpu_to_le32(st->nodes);
2633                                 break;
2634                         }
2635                 } else {
2636                         /*
2637                          * no need to change bms->nodes for other
2638                          * bitmap types
2639                          */
2640                         if (st->nodes)
2641                                 pr_err("Warning: --nodes option is only suitable for clustered bitmap\n");
2642                         break;
2643                 }
2644
2645                 /*
2646                  * Each node has an independent bitmap, it is necessary to
2647                  * calculate the space is enough or not, first get how many
2648                  * bytes for the total bitmap
2649                  */
2650                 bm_space_per_node = calc_bitmap_size(bms, 4096);
2651
2652                 total_bm_space = 512 * (__le64_to_cpu(sb->data_offset) -
2653                                         __le64_to_cpu(sb->super_offset));
2654                 /* leave another 4k for superblock */
2655                 total_bm_space = total_bm_space - 4096;
2656
2657                 if (bm_space_per_node * st->nodes > total_bm_space) {
2658                         pr_err("Warning: The max num of nodes can't exceed %llu\n",
2659                                 total_bm_space / bm_space_per_node);
2660                         return -ENOMEM;
2661                 }
2662
2663                 bms->nodes = __cpu_to_le32(st->nodes);
2664                 break;
2665         case NoUpdate:
2666         default:
2667                 break;
2668         }
2669
2670         init_afd(&afd, fd);
2671
2672         locate_bitmap1(st, fd, 0);
2673
2674         if (posix_memalign(&buf, 4096, 4096))
2675                 return -ENOMEM;
2676
2677         do {
2678                 /* Only the bitmap[0] should resync
2679                  * whole device on initial assembly
2680                  */
2681                 if (i)
2682                         memset(buf, 0x00, 4096);
2683                 else
2684                         memset(buf, 0xff, 4096);
2685                 memcpy(buf, (char *)bms, sizeof(bitmap_super_t));
2686
2687                 /*
2688                  * use 4096 boundary if bitmap_offset is aligned
2689                  * with 8 sectors, then it should compatible with
2690                  * older mdadm.
2691                  */
2692                 if (__le32_to_cpu(sb->bitmap_offset) & 7)
2693                         towrite = calc_bitmap_size(bms, 512);
2694                 else
2695                         towrite = calc_bitmap_size(bms, 4096);
2696                 while (towrite > 0) {
2697                         n = towrite;
2698                         if (n > 4096)
2699                                 n = 4096;
2700                         n = awrite(&afd, buf, n);
2701                         if (n > 0)
2702                                 towrite -= n;
2703                         else
2704                                 break;
2705                         if (i)
2706                                 memset(buf, 0x00, 4096);
2707                         else
2708                                 memset(buf, 0xff, 4096);
2709                 }
2710                 fsync(fd);
2711                 if (towrite) {
2712                         rv = -2;
2713                         break;
2714                 }
2715         } while (++i < __le32_to_cpu(bms->nodes));
2716
2717         free(buf);
2718         return rv;
2719 }
2720
2721 static void free_super1(struct supertype *st)
2722 {
2723
2724         if (st->sb)
2725                 free(st->sb);
2726         while (st->info) {
2727                 struct devinfo *di = st->info;
2728                 st->info = di->next;
2729                 if (di->fd >= 0)
2730                         close(di->fd);
2731                 free(di);
2732         }
2733         st->sb = NULL;
2734 }
2735
2736 static int validate_geometry1(struct supertype *st, int level,
2737                               int layout, int raiddisks,
2738                               int *chunk, unsigned long long size,
2739                               unsigned long long data_offset,
2740                               char *subdev, unsigned long long *freesize,
2741                               int consistency_policy, int verbose)
2742 {
2743         unsigned long long ldsize, devsize;
2744         int bmspace;
2745         unsigned long long headroom;
2746         int fd;
2747
2748         if (level == LEVEL_CONTAINER) {
2749                 if (verbose)
2750                         pr_err("1.x metadata does not support containers\n");
2751                 return 0;
2752         }
2753         if (*chunk == UnSet)
2754                 *chunk = DEFAULT_CHUNK;
2755
2756         if (!subdev)
2757                 return 1;
2758
2759         if (st->minor_version < 0)
2760                 /* not specified, so time to set default */
2761                 st->minor_version = 2;
2762
2763         fd = open(subdev, O_RDONLY|O_EXCL, 0);
2764         if (fd < 0) {
2765                 if (verbose)
2766                         pr_err("super1.x cannot open %s: %s\n",
2767                                 subdev, strerror(errno));
2768                 return 0;
2769         }
2770
2771         if (!get_dev_size(fd, subdev, &ldsize)) {
2772                 close(fd);
2773                 return 0;
2774         }
2775         close(fd);
2776
2777         devsize = ldsize >> 9;
2778         if (devsize < 24) {
2779                 *freesize = 0;
2780                 return 0;
2781         }
2782
2783         /* creating:  allow suitable space for bitmap or PPL */
2784         if (consistency_policy == CONSISTENCY_POLICY_PPL)
2785                 bmspace = MULTIPLE_PPL_AREA_SIZE_SUPER1 >> 9;
2786         else
2787                 bmspace = choose_bm_space(devsize);
2788
2789         if (data_offset == INVALID_SECTORS)
2790                 data_offset = st->data_offset;
2791         if (data_offset == INVALID_SECTORS)
2792                 switch (st->minor_version) {
2793                 case 0:
2794                         data_offset = 0;
2795                         break;
2796                 case 1:
2797                 case 2:
2798                         /* Choose data offset appropriate for this device
2799                          * and use as default for whole array.
2800                          * The data_offset must allow for bitmap space
2801                          * and base metadata, should allow for some headroom
2802                          * for reshape, and should be rounded to multiple
2803                          * of 1M.
2804                          * Headroom is limited to 128M, but aim for about 0.1%
2805                          */
2806                         headroom = 128*1024*2;
2807                         while ((headroom << 10) > devsize &&
2808                                (*chunk == 0 ||
2809                                 headroom / 2 >= ((unsigned)(*chunk)*2)*2))
2810                                 headroom >>= 1;
2811                         data_offset = 12*2 + bmspace + headroom;
2812                         #define ONE_MEG (2*1024)
2813                         data_offset = ROUND_UP(data_offset, ONE_MEG);
2814                         break;
2815                 }
2816         if (st->data_offset == INVALID_SECTORS)
2817                 st->data_offset = data_offset;
2818         switch(st->minor_version) {
2819         case 0: /* metadata at end.  Round down and subtract space to reserve */
2820                 devsize = (devsize & ~(4ULL*2-1));
2821                 /* space for metadata, bblog, bitmap/ppl */
2822                 devsize -= 8*2 + 8 + bmspace;
2823                 break;
2824         case 1:
2825         case 2:
2826                 devsize -= data_offset;
2827                 break;
2828         }
2829         *freesize = devsize;
2830         return 1;
2831 }
2832
2833 void *super1_make_v0(struct supertype *st, struct mdinfo *info, mdp_super_t *sb0)
2834 {
2835         /* Create a v1.0 superblock based on 'info'*/
2836         void *ret;
2837         struct mdp_superblock_1 *sb;
2838         int i;
2839         unsigned long long offset;
2840
2841         if (posix_memalign(&ret, 4096, 1024) != 0)
2842                 return NULL;
2843         sb = ret;
2844         memset(ret, 0, 1024);
2845         sb->magic = __cpu_to_le32(MD_SB_MAGIC);
2846         sb->major_version = __cpu_to_le32(1);
2847
2848         copy_uuid(sb->set_uuid, info->uuid, super1.swapuuid);
2849         sprintf(sb->set_name, "%d", sb0->md_minor);
2850         sb->ctime = __cpu_to_le32(info->array.ctime+1);
2851         sb->level = __cpu_to_le32(info->array.level);
2852         sb->layout = __cpu_to_le32(info->array.layout);
2853         sb->size = __cpu_to_le64(info->component_size);
2854         sb->chunksize = __cpu_to_le32(info->array.chunk_size/512);
2855         sb->raid_disks = __cpu_to_le32(info->array.raid_disks);
2856         if (info->array.level > 0)
2857                 sb->data_size = sb->size;
2858         else
2859                 sb->data_size = st->ss->avail_size(st, st->devsize/512, 0);
2860         sb->resync_offset = MaxSector;
2861         sb->max_dev = __cpu_to_le32(MD_SB_DISKS);
2862         sb->dev_number = __cpu_to_le32(info->disk.number);
2863         sb->utime = __cpu_to_le64(info->array.utime);
2864
2865         offset = st->devsize/512 - 8*2;
2866         offset &= ~(4*2-1);
2867         sb->super_offset = __cpu_to_le64(offset);
2868         //*(__u64*)(st->other + 128 + 8 + 8) = __cpu_to_le64(offset);
2869
2870         random_uuid(sb->device_uuid);
2871
2872         for (i = 0; i < MD_SB_DISKS; i++) {
2873                 int state = sb0->disks[i].state;
2874                 sb->dev_roles[i] = MD_DISK_ROLE_SPARE;
2875                 if ((state & (1<<MD_DISK_SYNC)) &&
2876                     !(state & (1<<MD_DISK_FAULTY)))
2877                         sb->dev_roles[i] = __cpu_to_le16(sb0->disks[i].raid_disk);
2878         }
2879         sb->sb_csum = calc_sb_1_csum(sb);
2880         return ret;
2881 }
2882
2883 struct superswitch super1 = {
2884         .examine_super = examine_super1,
2885         .brief_examine_super = brief_examine_super1,
2886         .export_examine_super = export_examine_super1,
2887         .detail_super = detail_super1,
2888         .brief_detail_super = brief_detail_super1,
2889         .export_detail_super = export_detail_super1,
2890         .write_init_super = write_init_super1,
2891         .validate_geometry = validate_geometry1,
2892         .add_to_super = add_to_super1,
2893         .examine_badblocks = examine_badblocks_super1,
2894         .copy_metadata = copy_metadata1,
2895         .write_init_ppl = write_init_ppl1,
2896         .match_home = match_home1,
2897         .uuid_from_super = uuid_from_super1,
2898         .getinfo_super = getinfo_super1,
2899         .container_content = container_content1,
2900         .update_super = update_super1,
2901         .init_super = init_super1,
2902         .store_super = store_super1,
2903         .compare_super = compare_super1,
2904         .load_super = load_super1,
2905         .match_metadata_desc = match_metadata_desc1,
2906         .avail_size = avail_size1,
2907         .add_internal_bitmap = add_internal_bitmap1,
2908         .locate_bitmap = locate_bitmap1,
2909         .write_bitmap = write_bitmap1,
2910         .free_super = free_super1,
2911 #if __BYTE_ORDER == BIG_ENDIAN
2912         .swapuuid = 0,
2913 #else
2914         .swapuuid = 1,
2915 #endif
2916         .name = "1.x",
2917 };