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