New method: load_container
[thirdparty/mdadm.git] / util.c
CommitLineData
64c4757e 1/*
9a9dab36 2 * mdadm - manage Linux "md" devices aka RAID arrays.
64c4757e 3 *
e736b623 4 * Copyright (C) 2001-2009 Neil Brown <neilb@suse.de>
64c4757e
NB
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
e736b623 22 * Email: <neilb@suse.de>
64c4757e
NB
23 */
24
9a9dab36 25#include "mdadm.h"
64c4757e 26#include "md_p.h"
edd8d13c 27#include <sys/socket.h>
64c4757e 28#include <sys/utsname.h>
9fe32043 29#include <sys/wait.h>
edd8d13c 30#include <sys/un.h>
98c6faba 31#include <ctype.h>
a322f70c 32#include <dirent.h>
a931db9e 33#include <signal.h>
0a816ef9
NB
34
35/*
36 * following taken from linux/blkpg.h because they aren't
37 * anywhere else and it isn't safe to #include linux/ * stuff.
38 */
39
40#define BLKPG _IO(0x12,105)
41
42/* The argument structure */
43struct blkpg_ioctl_arg {
44 int op;
45 int flags;
46 int datalen;
47 void *data;
48};
49
50/* The subfunctions (for the op field) */
51#define BLKPG_ADD_PARTITION 1
52#define BLKPG_DEL_PARTITION 2
53
54/* Sizes of name fields. Unused at present. */
55#define BLKPG_DEVNAMELTH 64
56#define BLKPG_VOLNAMELTH 64
57
58/* The data structure for ADD_PARTITION and DEL_PARTITION */
59struct blkpg_partition {
60 long long start; /* starting offset in bytes */
61 long long length; /* length in bytes */
62 int pno; /* partition number */
63 char devname[BLKPG_DEVNAMELTH]; /* partition name, like sda5 or c0d1p2,
64 to be used in kernel messages */
65 char volname[BLKPG_VOLNAMELTH]; /* volume label */
66};
64c4757e 67
0f22b998 68#include "part.h"
056b331e
N
69
70/* Force a compilation error if condition is true */
71#define BUILD_BUG_ON(condition) ((void)BUILD_BUG_ON_ZERO(condition))
72
73/* Force a compilation error if condition is true, but also produce a
74 result (of value 0 and type size_t), so the expression can be used
75 e.g. in a structure initializer (or where-ever else comma expressions
76 aren't permitted). */
77#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
78
64c4757e
NB
79/*
80 * Parse a 128 bit uuid in 4 integers
81 * format is 32 hexx nibbles with options :.<space> separator
82 * If not exactly 32 hex digits are found, return 0
83 * else return 1
84 */
85int parse_uuid(char *str, int uuid[4])
86{
aba69144
NB
87 int hit = 0; /* number of Hex digIT */
88 int i;
89 char c;
90 for (i=0; i<4; i++) uuid[i]=0;
91
92 while ((c= *str++)) {
93 int n;
94 if (c>='0' && c<='9')
95 n = c-'0';
96 else if (c>='a' && c <= 'f')
97 n = 10 + c - 'a';
98 else if (c>='A' && c <= 'F')
99 n = 10 + c - 'A';
100 else if (strchr(":. -", c))
101 continue;
102 else return 0;
103
104 if (hit<32) {
105 uuid[hit/8] <<= 4;
106 uuid[hit/8] += n;
107 }
108 hit++;
82b27616 109 }
aba69144
NB
110 if (hit == 32)
111 return 1;
112 return 0;
64c4757e
NB
113}
114
115
116/*
117 * Get the md version number.
118 * We use the RAID_VERSION ioctl if it is supported
119 * If not, but we have a block device with major '9', we assume
120 * 0.36.0
121 *
122 * Return version number as 24 but number - assume version parts
123 * always < 255
124 */
125
126int md_get_version(int fd)
127{
128 struct stat stb;
129 mdu_version_t vers;
130
131 if (fstat(fd, &stb)<0)
132 return -1;
133 if ((S_IFMT&stb.st_mode) != S_IFBLK)
134 return -1;
135
136 if (ioctl(fd, RAID_VERSION, &vers) == 0)
682c7051 137 return (vers.major*10000) + (vers.minor*100) + vers.patchlevel;
5787fa49
NB
138 if (errno == EACCES)
139 return -1;
0df46c2a 140 if (major(stb.st_rdev) == MD_MAJOR)
682c7051 141 return (3600);
64c4757e
NB
142 return -1;
143}
144
64c4757e
NB
145int get_linux_version()
146{
147 struct utsname name;
98c6faba 148 char *cp;
64c4757e
NB
149 int a,b,c;
150 if (uname(&name) <0)
151 return -1;
152
98c6faba
NB
153 cp = name.release;
154 a = strtoul(cp, &cp, 10);
155 if (*cp != '.') return -1;
156 b = strtoul(cp+1, &cp, 10);
157 if (*cp != '.') return -1;
158 c = strtoul(cp+1, NULL, 10);
159
682c7051 160 return (a*1000000)+(b*1000)+c;
64c4757e
NB
161}
162
eb3929a4 163#ifndef MDASSEMBLE
84e11361
N
164long long parse_size(char *size)
165{
166 /* parse 'size' which should be a number optionally
167 * followed by 'K', 'M', or 'G'.
168 * Without a suffix, K is assumed.
169 * Number returned is in sectors (half-K)
170 */
171 char *c;
172 long long s = strtoll(size, &c, 10);
173 if (s > 0) {
174 switch (*c) {
175 case 'K':
176 c++;
177 default:
178 s *= 2;
179 break;
180 case 'M':
181 c++;
182 s *= 1024 * 2;
183 break;
184 case 'G':
185 c++;
186 s *= 1024 * 1024 * 2;
187 break;
188 }
189 }
190 if (*c)
191 s = 0;
192 return s;
193}
194
4a06e2c2
N
195int parse_layout_10(char *layout)
196{
197 int copies, rv;
198 char *cp;
199 /* Parse the layout string for raid10 */
200 /* 'f', 'o' or 'n' followed by a number <= raid_disks */
201 if ((layout[0] != 'n' && layout[0] != 'f' && layout[0] != 'o') ||
202 (copies = strtoul(layout+1, &cp, 10)) < 1 ||
203 copies > 200 ||
204 *cp)
205 return -1;
206 if (layout[0] == 'n')
207 rv = 256 + copies;
208 else if (layout[0] == 'o')
209 rv = 0x10000 + (copies<<8) + 1;
210 else
211 rv = 1 + (copies<<8);
212 return rv;
213}
214
215int parse_layout_faulty(char *layout)
216{
217 /* Parse the layout string for 'faulty' */
218 int ln = strcspn(layout, "0123456789");
219 char *m = strdup(layout);
220 int mode;
221 m[ln] = 0;
222 mode = map_name(faultylayout, m);
223 if (mode == UnSet)
224 return -1;
225
226 return mode | (atoi(layout+ln)<< ModeShift);
227}
eb3929a4 228#endif
4a06e2c2 229
0430ed48
NB
230void remove_partitions(int fd)
231{
232 /* remove partitions from this block devices.
233 * This is used for components added to an array
234 */
235#ifdef BLKPG_DEL_PARTITION
236 struct blkpg_ioctl_arg a;
237 struct blkpg_partition p;
238
239 a.op = BLKPG_DEL_PARTITION;
240 a.data = (void*)&p;
241 a.datalen = sizeof(p);
242 a.flags = 0;
243 memset(a.data, 0, a.datalen);
244 for (p.pno=0; p.pno < 16; p.pno++)
245 ioctl(fd, BLKPG, &a);
246#endif
247}
248
691c6ee1
N
249int test_partition(int fd)
250{
251 /* Check if fd is a whole-disk or a partition.
252 * BLKPG will return EINVAL on a partition, and BLKPG_DEL_PARTITION
253 * will return ENXIO on an invalid partition number.
254 */
255 struct blkpg_ioctl_arg a;
256 struct blkpg_partition p;
257 a.op = BLKPG_DEL_PARTITION;
258 a.data = (void*)&p;
259 a.datalen = sizeof(p);
260 a.flags = 0;
261 memset(a.data, 0, a.datalen);
262 p.pno = 1<<30;
263 if (ioctl(fd, BLKPG, &a) == 0)
264 /* Very unlikely, but not a partition */
265 return 0;
266 if (errno == ENXIO)
267 /* not a partition */
268 return 0;
269
270 return 1;
271}
272
273
583315d9 274int enough(int level, int raid_disks, int layout, int clean,
265e0f17 275 char *avail, int avail_disks)
64c4757e 276{
265e0f17 277 int copies, first;
64c4757e 278 switch (level) {
265e0f17
NB
279 case 10:
280 /* This is the tricky one - we need to check
281 * which actual disks are present.
282 */
702b557b 283 copies = (layout&255)* ((layout>>8) & 255);
265e0f17
NB
284 first=0;
285 do {
286 /* there must be one of the 'copies' form 'first' */
287 int n = copies;
288 int cnt=0;
289 while (n--) {
290 if (avail[first])
291 cnt++;
292 first = (first+1) % raid_disks;
293 }
294 if (cnt == 0)
295 return 0;
296
297 } while (first != 0);
298 return 1;
e5329c37 299
df0d4ea0 300 case LEVEL_MULTIPATH:
e0d19036 301 return avail_disks>= 1;
df0d4ea0 302 case LEVEL_LINEAR:
64c4757e
NB
303 case 0:
304 return avail_disks == raid_disks;
305 case 1:
306 return avail_disks >= 1;
307 case 4:
308 case 5:
583315d9
NB
309 if (clean)
310 return avail_disks >= raid_disks-1;
311 else
312 return avail_disks >= raid_disks;
98c6faba 313 case 6:
583315d9
NB
314 if (clean)
315 return avail_disks >= raid_disks-2;
316 else
317 return avail_disks >= raid_disks;
64c4757e
NB
318 default:
319 return 0;
320 }
321}
322
8453e704
N
323int enough_fd(int fd)
324{
325 struct mdu_array_info_s array;
326 struct mdu_disk_info_s disk;
327 int avail_disks = 0;
328 int i;
329 char *avail;
330
331 if (ioctl(fd, GET_ARRAY_INFO, &array) != 0 ||
332 array.raid_disks <= 0)
333 return 0;
334 avail = calloc(array.raid_disks, 1);
335 for (i=0; i<array.raid_disks + array.nr_disks; i++) {
336 disk.number = i;
337 if (ioctl(fd, GET_DISK_INFO, &disk) != 0)
338 continue;
339 if (! (disk.state & (1<<MD_DISK_SYNC)))
340 continue;
341 if (disk.raid_disk < 0 || disk.raid_disk >= array.raid_disks)
342 continue;
343 avail_disks++;
344 avail[disk.raid_disk] = 1;
345 }
346 /* This is used on an active array, so assume it is clean */
347 return enough(array.level, array.raid_disks, array.layout,
348 1,
349 avail, avail_disks);
350}
351
352
36ba7d48 353const int uuid_match_any[4] = { ~0, ~0, ~0, ~0 };
f277ce36 354int same_uuid(int a[4], int b[4], int swapuuid)
64c4757e 355{
36ba7d48
DW
356 if (memcmp(a, uuid_match_any, sizeof(int[4])) == 0 ||
357 memcmp(b, uuid_match_any, sizeof(int[4])) == 0)
358 return 1;
359
f277ce36
NB
360 if (swapuuid) {
361 /* parse uuids are hostendian.
362 * uuid's from some superblocks are big-ending
aba69144 363 * if there is a difference, we need to swap..
f277ce36
NB
364 */
365 unsigned char *ac = (unsigned char *)a;
366 unsigned char *bc = (unsigned char *)b;
367 int i;
368 for (i=0; i<16; i+= 4) {
369 if (ac[i+0] != bc[i+3] ||
370 ac[i+1] != bc[i+2] ||
371 ac[i+2] != bc[i+1] ||
372 ac[i+3] != bc[i+0])
373 return 0;
374 }
375 return 1;
376 } else {
377 if (a[0]==b[0] &&
378 a[1]==b[1] &&
379 a[2]==b[2] &&
380 a[3]==b[3])
381 return 1;
382 return 0;
383 }
64c4757e 384}
350f29f9
NB
385void copy_uuid(void *a, int b[4], int swapuuid)
386{
387 if (swapuuid) {
388 /* parse uuids are hostendian.
389 * uuid's from some superblocks are big-ending
390 * if there is a difference, we need to swap..
391 */
392 unsigned char *ac = (unsigned char *)a;
393 unsigned char *bc = (unsigned char *)b;
394 int i;
395 for (i=0; i<16; i+= 4) {
396 ac[i+0] = bc[i+3];
397 ac[i+1] = bc[i+2];
398 ac[i+2] = bc[i+1];
399 ac[i+3] = bc[i+0];
400 }
401 } else
402 memcpy(a, b, 16);
403}
64c4757e 404
aae5a112 405char *__fname_from_uuid(int id[4], int swap, char *buf, char sep)
d7288ddc 406{
9968e376 407 int i, j;
d7288ddc
N
408 char uuid[16];
409 char *c = buf;
410 strcpy(c, "UUID-");
411 c += strlen(c);
aae5a112 412 copy_uuid(uuid, id, swap);
9968e376 413 for (i = 0; i < 4; i++) {
9968e376 414 if (i)
ff54de6e 415 *c++ = sep;
9968e376
DW
416 for (j = 3; j >= 0; j--) {
417 sprintf(c,"%02x", (unsigned char) uuid[j+4*i]);
418 c+= 2;
419 }
d7288ddc
N
420 }
421 return buf;
aae5a112
DW
422
423}
424
425char *fname_from_uuid(struct supertype *st, struct mdinfo *info, char *buf, char sep)
426{
86983cce
N
427 // dirty hack to work around an issue with super1 superblocks...
428 // super1 superblocks need swapuuid set in order for assembly to
429 // work, but can't have it set if we want this printout to match
430 // all the other uuid printouts in super1.c, so we force swapuuid
431 // to 1 to make our printout match the rest of super1
432 return __fname_from_uuid(info->uuid, (st->ss == &super1) ? 1 : st->ss->swapuuid, buf, sep);
d7288ddc
N
433}
434
435d4ebb 435#ifndef MDASSEMBLE
682c7051
NB
436int check_ext2(int fd, char *name)
437{
438 /*
439 * Check for an ext2fs file system.
440 * Superblock is always 1K at 1K offset
441 *
442 * s_magic is le16 at 56 == 0xEF53
443 * report mtime - le32 at 44
444 * blocks - le32 at 4
445 * logblksize - le32 at 24
446 */
447 unsigned char sb[1024];
448 time_t mtime;
449 int size, bsize;
450 if (lseek(fd, 1024,0)!= 1024)
451 return 0;
452 if (read(fd, sb, 1024)!= 1024)
453 return 0;
454 if (sb[56] != 0x53 || sb[57] != 0xef)
455 return 0;
456
457 mtime = sb[44]|(sb[45]|(sb[46]|sb[47]<<8)<<8)<<8;
458 bsize = sb[24]|(sb[25]|(sb[26]|sb[27]<<8)<<8)<<8;
459 size = sb[4]|(sb[5]|(sb[6]|sb[7]<<8)<<8)<<8;
460 fprintf(stderr, Name ": %s appears to contain an ext2fs file system\n",
461 name);
462 fprintf(stderr," size=%dK mtime=%s",
463 size*(1<<bsize), ctime(&mtime));
464 return 1;
465}
466
467int check_reiser(int fd, char *name)
468{
469 /*
470 * superblock is at 64K
471 * size is 1024;
472 * Magic string "ReIsErFs" or "ReIsEr2Fs" at 52
473 *
474 */
475 unsigned char sb[1024];
881990a2 476 unsigned long size;
682c7051
NB
477 if (lseek(fd, 64*1024, 0) != 64*1024)
478 return 0;
479 if (read(fd, sb, 1024) != 1024)
480 return 0;
a46f4061
NB
481 if (strncmp((char*)sb+52, "ReIsErFs",8)!=0 &&
482 strncmp((char*)sb+52, "ReIsEr2Fs",9)!=0)
682c7051
NB
483 return 0;
484 fprintf(stderr, Name ": %s appears to contain a reiserfs file system\n",name);
485 size = sb[0]|(sb[1]|(sb[2]|sb[3]<<8)<<8)<<8;
881990a2 486 fprintf(stderr, " size = %luK\n", size*4);
aba69144 487
682c7051
NB
488 return 1;
489}
490
491int check_raid(int fd, char *name)
492{
4b1ac34b 493 struct mdinfo info;
682c7051 494 time_t crtime;
d078d77c 495 char *level;
82d9eba6 496 struct supertype *st = guess_super(fd);
f9ce90ba 497
82d9eba6 498 if (!st) return 0;
3da92f27 499 st->ss->load_super(st, fd, name);
82d9eba6
NB
500 /* Looks like a raid array .. */
501 fprintf(stderr, Name ": %s appears to be part of a raid array:\n",
502 name);
a5d85af7 503 st->ss->getinfo_super(st, &info, NULL);
3da92f27 504 st->ss->free_super(st);
82d9eba6 505 crtime = info.array.ctime;
d078d77c
NB
506 level = map_num(pers, info.array.level);
507 if (!level) level = "-unknown-";
508 fprintf(stderr, " level=%s devices=%d ctime=%s",
509 level, info.array.raid_disks, ctime(&crtime));
82d9eba6 510 return 1;
682c7051
NB
511}
512
682c7051
NB
513int ask(char *mesg)
514{
515 char *add = "";
516 int i;
517 for (i=0; i<5; i++) {
518 char buf[100];
519 fprintf(stderr, "%s%s", mesg, add);
520 fflush(stderr);
521 if (fgets(buf, 100, stdin)==NULL)
522 return 0;
523 if (buf[0]=='y' || buf[0]=='Y')
524 return 1;
525 if (buf[0]=='n' || buf[0]=='N')
526 return 0;
527 add = "(y/n) ";
528 }
529 fprintf(stderr, Name ": assuming 'no'\n");
530 return 0;
531}
435d4ebb 532#endif /* MDASSEMBLE */
682c7051
NB
533
534char *map_num(mapping_t *map, int num)
535{
536 while (map->name) {
537 if (map->num == num)
538 return map->name;
539 map++;
540 }
541 return NULL;
542}
543
544int map_name(mapping_t *map, char *name)
545{
546 while (map->name) {
547 if (strcmp(map->name, name)==0)
548 return map->num;
549 map++;
550 }
98c6faba 551 return UnSet;
682c7051 552}
82b27616 553
e5329c37 554
8d80900b 555int is_standard(char *dev, int *nump)
e5329c37
NB
556{
557 /* tests if dev is a "standard" md dev name.
558 * i.e if the last component is "/dNN" or "/mdNN",
aba69144 559 * where NN is a string of digits
598f0d58
NB
560 * Returns 1 if a partitionable standard,
561 * -1 if non-partitonable,
562 * 0 if not a standard name.
e5329c37 563 */
8d80900b
NB
564 char *d = strrchr(dev, '/');
565 int type=0;
566 int num;
567 if (!d)
e5329c37 568 return 0;
8d80900b
NB
569 if (strncmp(d, "/d",2)==0)
570 d += 2, type=1; /* /dev/md/dN{pM} */
571 else if (strncmp(d, "/md_d", 5)==0)
2b4ca8f0 572 d += 5, type=1; /* /dev/md_dN{pM} */
8d80900b
NB
573 else if (strncmp(d, "/md", 3)==0)
574 d += 3, type=-1; /* /dev/mdN */
575 else if (d-dev > 3 && strncmp(d-2, "md/", 3)==0)
5a6d1148 576 d += 1, type=-1; /* /dev/md/N */
e5329c37
NB
577 else
578 return 0;
8d80900b 579 if (!*d)
e5329c37 580 return 0;
8d80900b
NB
581 num = atoi(d);
582 while (isdigit(*d))
583 d++;
584 if (*d)
e5329c37 585 return 0;
8d80900b
NB
586 if (nump) *nump = num;
587
588 return type;
e5329c37
NB
589}
590
591
82b27616
NB
592/*
593 * convert a major/minor pair for a block device into a name in /dev, if possible.
594 * On the first call, walk /dev collecting name.
595 * Put them in a simple linked listfor now.
596 */
597struct devmap {
598 int major, minor;
599 char *name;
600 struct devmap *next;
601} *devlist = NULL;
602int devlist_ready = 0;
603
82b27616
NB
604int add_dev(const char *name, const struct stat *stb, int flag, struct FTW *s)
605{
bed256c2 606 struct stat st;
bf68e9d9 607
bed256c2 608 if (S_ISLNK(stb->st_mode)) {
bf68e9d9
DW
609 if (stat(name, &st) != 0)
610 return 0;
bed256c2 611 stb = &st;
82b27616 612 }
bed256c2
NB
613
614 if ((stb->st_mode&S_IFMT)== S_IFBLK) {
615 char *n = strdup(name);
616 struct devmap *dm = malloc(sizeof(*dm));
617 if (strncmp(n, "/dev/./", 7)==0)
618 strcpy(n+4, name+6);
619 if (dm) {
620 dm->major = major(stb->st_rdev);
621 dm->minor = minor(stb->st_rdev);
622 dm->name = n;
623 dm->next = devlist;
624 devlist = dm;
625 }
626 }
627 return 0;
82b27616
NB
628}
629
45e878bb
NB
630#ifndef HAVE_NFTW
631#ifdef HAVE_FTW
632int add_dev_1(const char *name, const struct stat *stb, int flag)
633{
634 return add_dev(name, stb, flag, NULL);
635}
636int nftw(const char *path, int (*han)(const char *name, const struct stat *stb, int flag, struct FTW *s), int nopenfd, int flags)
637{
638 return ftw(path, add_dev_1, nopenfd);
639}
640#else
45e878bb
NB
641int nftw(const char *path, int (*han)(const char *name, const struct stat *stb, int flag, struct FTW *s), int nopenfd, int flags)
642{
643 return 0;
644}
645#endif /* HAVE_FTW */
646#endif /* HAVE_NFTW */
647
dd0781e5
NB
648/*
649 * Find a block device with the right major/minor number.
b79713f8 650 * If we find multiple names, choose the shortest.
70ef16db 651 * If we find a name in /dev/md/, we prefer that.
b79713f8 652 * This applies only to names for MD devices.
dd0781e5 653 */
16c6fa80 654char *map_dev(int major, int minor, int create)
82b27616 655{
dd0781e5 656 struct devmap *p;
70ef16db 657 char *regular = NULL, *preferred=NULL;
e7bb5d23 658 int did_check = 0;
eed35d66 659
e81cdd9f 660 if (major == 0 && minor == 0)
eed35d66 661 return NULL;
e81cdd9f 662
e7bb5d23 663 retry:
dd0781e5 664 if (!devlist_ready) {
0a416ec3
NB
665 char *dev = "/dev";
666 struct stat stb;
eed35d66
NB
667 while(devlist) {
668 struct devmap *d = devlist;
669 devlist = d->next;
670 free(d->name);
671 free(d);
672 }
0a416ec3
NB
673 if (lstat(dev, &stb)==0 &&
674 S_ISLNK(stb.st_mode))
675 dev = "/dev/.";
676 nftw(dev, add_dev, 10, FTW_PHYS);
dd0781e5 677 devlist_ready=1;
e7bb5d23 678 did_check = 1;
dd0781e5 679 }
82b27616 680
dd0781e5
NB
681 for (p=devlist; p; p=p->next)
682 if (p->major == major &&
683 p->minor == minor) {
70ef16db
N
684 if (strncmp(p->name, "/dev/md/",8) == 0) {
685 if (preferred == NULL ||
686 strlen(p->name) < strlen(preferred))
687 preferred = p->name;
b79713f8 688 } else {
70ef16db
N
689 if (regular == NULL ||
690 strlen(p->name) < strlen(regular))
691 regular = p->name;
b79713f8 692 }
dd0781e5 693 }
70ef16db 694 if (!regular && !preferred && !did_check) {
e7bb5d23
NB
695 devlist_ready = 0;
696 goto retry;
697 }
70ef16db 698 if (create && !regular && !preferred) {
16c6fa80 699 static char buf[30];
382245c3 700 snprintf(buf, sizeof(buf), "%d:%d", major, minor);
70ef16db 701 regular = buf;
16c6fa80
NB
702 }
703
70ef16db 704 return preferred ? preferred : regular;
82b27616
NB
705}
706
4b1ac34b 707unsigned long calc_csum(void *super, int bytes)
82b27616 708{
56eb10c0 709 unsigned long long newcsum = 0;
82b27616 710 int i;
4b1ac34b
NB
711 unsigned int csum;
712 unsigned int *superc = (unsigned int*) super;
82b27616 713
4b1ac34b 714 for(i=0; i<bytes/4; i++)
82b27616
NB
715 newcsum+= superc[i];
716 csum = (newcsum& 0xffffffff) + (newcsum>>32);
570c0542 717#ifdef __alpha__
aba69144 718/* The in-kernel checksum calculation is always 16bit on
570c0542
NB
719 * the alpha, though it is 32 bit on i386...
720 * I wonder what it is elsewhere... (it uses and API in
721 * a way that it shouldn't).
722 */
723 csum = (csum & 0xffff) + (csum >> 16);
724 csum = (csum & 0xffff) + (csum >> 16);
725#endif
82b27616
NB
726 return csum;
727}
cd29a5c8 728
435d4ebb 729#ifndef MDASSEMBLE
56eb10c0 730char *human_size(long long bytes)
cd29a5c8
NB
731{
732 static char buf[30];
d5d3721e
NB
733
734 /* We convert bytes to either centi-M{ega,ibi}bytes or
735 * centi-G{igi,ibi}bytes, with appropriate rounding,
736 * and then print 1/100th of those as a decimal.
737 * We allow upto 2048Megabytes before converting to
738 * gigabytes, as that shows more precision and isn't
739 * too large a number.
740 * Terrabytes are not yet handled.
741 */
cd29a5c8 742
56eb10c0 743 if (bytes < 5000*1024)
cd29a5c8 744 buf[0]=0;
d5d3721e
NB
745 else if (bytes < 2*1024LL*1024LL*1024LL) {
746 long cMiB = (bytes / ( (1LL<<20) / 200LL ) +1) /2;
747 long cMB = (bytes / ( 1000000LL / 200LL ) +1) /2;
8f23b0b3 748 snprintf(buf, sizeof(buf), " (%ld.%02ld MiB %ld.%02ld MB)",
d5d3721e
NB
749 cMiB/100 , cMiB % 100,
750 cMB/100, cMB % 100);
751 } else {
752 long cGiB = (bytes / ( (1LL<<30) / 200LL ) +1) /2;
753 long cGB = (bytes / (1000000000LL/200LL ) +1) /2;
8f23b0b3 754 snprintf(buf, sizeof(buf), " (%ld.%02ld GiB %ld.%02ld GB)",
d5d3721e
NB
755 cGiB/100 , cGiB % 100,
756 cGB/100, cGB % 100);
757 }
cd29a5c8
NB
758 return buf;
759}
e0d19036
NB
760
761char *human_size_brief(long long bytes)
762{
763 static char buf[30];
e0d19036
NB
764
765 if (bytes < 5000*1024)
8f23b0b3 766 snprintf(buf, sizeof(buf), "%ld.%02ldKiB",
bd526cee 767 (long)(bytes>>10), (long)(((bytes&1023)*100+512)/1024)
e0d19036
NB
768 );
769 else if (bytes < 2*1024LL*1024LL*1024LL)
8f23b0b3 770 snprintf(buf, sizeof(buf), "%ld.%02ldMiB",
e0d19036 771 (long)(bytes>>20),
bd526cee 772 (long)((bytes&0xfffff)+0x100000/200)/(0x100000/100)
e0d19036
NB
773 );
774 else
8f23b0b3 775 snprintf(buf, sizeof(buf), "%ld.%02ldGiB",
e0d19036 776 (long)(bytes>>30),
bd526cee 777 (long)(((bytes>>10)&0xfffff)+0x100000/200)/(0x100000/100)
e0d19036
NB
778 );
779 return buf;
780}
e4965ef8
N
781
782void print_r10_layout(int layout)
783{
784 int near = layout & 255;
785 int far = (layout >> 8) & 255;
786 int offset = (layout&0x10000);
787 char *sep = "";
788
789 if (near != 1) {
790 printf("%s near=%d", sep, near);
791 sep = ",";
792 }
793 if (far != 1)
794 printf("%s %s=%d", sep, offset?"offset":"far", far);
795 if (near*far == 1)
796 printf("NO REDUNDANCY");
797}
435d4ebb 798#endif
e0d19036 799
5f8097be
NB
800unsigned long long calc_array_size(int level, int raid_disks, int layout,
801 int chunksize, unsigned long long devsize)
802{
803 int data_disks = 0;
804 switch (level) {
805 case 0: data_disks = raid_disks; break;
806 case 1: data_disks = 1; break;
807 case 4:
808 case 5: data_disks = raid_disks - 1; break;
809 case 6: data_disks = raid_disks - 2; break;
810 case 10: data_disks = raid_disks / (layout & 255) / ((layout>>8)&255);
811 break;
812 }
813 devsize &= ~(unsigned long long)((chunksize>>9)-1);
814 return data_disks * devsize;
815}
816
dd0781e5 817int get_mdp_major(void)
98c6faba 818{
dd0781e5
NB
819static int mdp_major = -1;
820 FILE *fl;
98c6faba
NB
821 char *w;
822 int have_block = 0;
823 int have_devices = 0;
824 int last_num = -1;
dd0781e5
NB
825
826 if (mdp_major != -1)
827 return mdp_major;
828 fl = fopen("/proc/devices", "r");
98c6faba 829 if (!fl)
dd0781e5 830 return -1;
98c6faba
NB
831 while ((w = conf_word(fl, 1))) {
832 if (have_block && strcmp(w, "devices:")==0)
833 have_devices = 1;
834 have_block = (strcmp(w, "Block")==0);
835 if (isdigit(w[0]))
836 last_num = atoi(w);
837 if (have_devices && strcmp(w, "mdp")==0)
838 mdp_major = last_num;
839 free(w);
840 }
841 fclose(fl);
dd0781e5 842 return mdp_major;
98c6faba
NB
843}
844
0e600426 845#if !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO)
e0d19036
NB
846char *get_md_name(int dev)
847{
848 /* find /dev/md%d or /dev/md/%d or make a device /dev/.tmp.md%d */
98c6faba 849 /* if dev < 0, want /dev/md/d%d or find mdp in /proc/devices ... */
e0d19036
NB
850 static char devname[50];
851 struct stat stb;
98c6faba 852 dev_t rdev;
dd0781e5 853 char *dn;
98c6faba
NB
854
855 if (dev < 0) {
dd0781e5
NB
856 int mdp = get_mdp_major();
857 if (mdp < 0) return NULL;
0df46c2a 858 rdev = makedev(mdp, (-1-dev)<<6);
8f23b0b3 859 snprintf(devname, sizeof(devname), "/dev/md/d%d", -1-dev);
98c6faba
NB
860 if (stat(devname, &stb) == 0
861 && (S_IFMT&stb.st_mode) == S_IFBLK
862 && (stb.st_rdev == rdev))
863 return devname;
864 } else {
0df46c2a 865 rdev = makedev(MD_MAJOR, dev);
8f23b0b3 866 snprintf(devname, sizeof(devname), "/dev/md%d", dev);
98c6faba
NB
867 if (stat(devname, &stb) == 0
868 && (S_IFMT&stb.st_mode) == S_IFBLK
869 && (stb.st_rdev == rdev))
870 return devname;
871
8f23b0b3 872 snprintf(devname, sizeof(devname), "/dev/md/%d", dev);
98c6faba
NB
873 if (stat(devname, &stb) == 0
874 && (S_IFMT&stb.st_mode) == S_IFBLK
875 && (stb.st_rdev == rdev))
876 return devname;
877 }
16c6fa80 878 dn = map_dev(major(rdev), minor(rdev), 0);
dd0781e5
NB
879 if (dn)
880 return dn;
8f23b0b3 881 snprintf(devname, sizeof(devname), "/dev/.tmp.md%d", dev);
e0d19036 882 if (mknod(devname, S_IFBLK | 0600, rdev) == -1)
dd0781e5
NB
883 if (errno != EEXIST)
884 return NULL;
e0d19036
NB
885
886 if (stat(devname, &stb) == 0
887 && (S_IFMT&stb.st_mode) == S_IFBLK
888 && (stb.st_rdev == rdev))
889 return devname;
890 unlink(devname);
891 return NULL;
892}
893
894void put_md_name(char *name)
895{
896 if (strncmp(name, "/dev/.tmp.md", 12)==0)
897 unlink(name);
898}
ea24acd0 899
ea24acd0
NB
900int find_free_devnum(int use_partitions)
901{
902 int devnum;
903 for (devnum = 127; devnum != 128;
a56fb7ec 904 devnum = devnum ? devnum-1 : (1<<20)-1) {
ea24acd0
NB
905 char *dn;
906 int _devnum;
907
908 _devnum = use_partitions ? (-1-devnum) : devnum;
909 if (mddev_busy(_devnum))
910 continue;
911 /* make sure it is new to /dev too, at least as a
912 * non-standard */
913 dn = map_dev(dev2major(_devnum), dev2minor(_devnum), 0);
914 if (dn && ! is_standard(dn, NULL))
915 continue;
916 break;
917 }
918 if (devnum == 128)
919 return NoMdDev;
920 return use_partitions ? (-1-devnum) : devnum;
921}
435d4ebb 922#endif /* !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO) */
f9ce90ba 923
8b0dabea
NB
924int dev_open(char *dev, int flags)
925{
926 /* like 'open', but if 'dev' matches %d:%d, create a temp
927 * block device and open that
928 */
929 char *e;
930 int fd = -1;
931 char devname[32];
e81cdd9f 932 int major;
8b0dabea 933 int minor;
e81cdd9f
NB
934
935 if (!dev) return -1;
6df6a774 936 flags |= O_DIRECT;
e81cdd9f
NB
937
938 major = strtoul(dev, &e, 0);
8b0dabea
NB
939 if (e > dev && *e == ':' && e[1] &&
940 (minor = strtoul(e+1, &e, 0)) >= 0 &&
941 *e == 0) {
6df6a774
N
942 char *path = map_dev(major, minor, 0);
943 if (path)
944 fd = open(path, flags);
945 if (fd < 0) {
946 snprintf(devname, sizeof(devname), "/dev/.tmp.md.%d:%d:%d",
947 (int)getpid(), major, minor);
948 if (mknod(devname, S_IFBLK|0600, makedev(major, minor))==0) {
949 fd = open(devname, flags);
950 unlink(devname);
951 }
952 }
953 if (fd < 0) {
954 snprintf(devname, sizeof(devname), "/tmp/.tmp.md.%d:%d:%d",
955 (int)getpid(), major, minor);
956 if (mknod(devname, S_IFBLK|0600, makedev(major, minor))==0) {
957 fd = open(devname, flags);
958 unlink(devname);
959 }
8b0dabea
NB
960 }
961 } else
6df6a774 962 fd = open(dev, flags);
8b0dabea
NB
963 return fd;
964}
f9ce90ba 965
e8a70c89
N
966int open_dev(int devnum)
967{
968 char buf[20];
969
970 sprintf(buf, "%d:%d", dev2major(devnum), dev2minor(devnum));
971 return dev_open(buf, O_RDWR);
972}
973
a931db9e
NB
974int open_dev_excl(int devnum)
975{
976 char buf[20];
977 int i;
978
979 sprintf(buf, "%d:%d", dev2major(devnum), dev2minor(devnum));
980 for (i=0 ; i<25 ; i++) {
981 int fd = dev_open(buf, O_RDWR|O_EXCL);
982 if (fd >= 0)
983 return fd;
984 if (errno != EBUSY)
985 return fd;
986 usleep(200000);
987 }
988 return -1;
989}
990
9008ed1c
N
991int same_dev(char *one, char *two)
992{
993 struct stat st1, st2;
994 if (stat(one, &st1) != 0)
995 return 0;
996 if (stat(two, &st2) != 0)
997 return 0;
998 if ((st1.st_mode & S_IFMT) != S_IFBLK)
999 return 0;
1000 if ((st2.st_mode & S_IFMT) != S_IFBLK)
1001 return 0;
1002 return st1.st_rdev == st2.st_rdev;
1003}
1004
a7c6e3fb 1005void wait_for(char *dev, int fd)
a714580e
N
1006{
1007 int i;
a7c6e3fb
N
1008 struct stat stb_want;
1009
1010 if (fstat(fd, &stb_want) != 0 ||
1011 (stb_want.st_mode & S_IFMT) != S_IFBLK)
1012 return;
a714580e
N
1013
1014 for (i=0 ; i<25 ; i++) {
1015 struct stat stb;
a7c6e3fb
N
1016 if (stat(dev, &stb) == 0 &&
1017 (stb.st_mode & S_IFMT) == S_IFBLK &&
1018 (stb.st_rdev == stb_want.st_rdev))
a714580e
N
1019 return;
1020 usleep(200000);
1021 }
436305c6
DW
1022 if (i == 25)
1023 dprintf("%s: timeout waiting for %s\n", __func__, dev);
a714580e
N
1024}
1025
0f22b998
N
1026struct superswitch *superlist[] =
1027{
1028 &super0, &super1,
1029 &super_ddf, &super_imsm,
0592faeb 1030 &mbr, &gpt,
0f22b998 1031 NULL };
f9ce90ba 1032
ea24acd0 1033#if !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO)
f7dd881f 1034
4725bc31 1035struct supertype *super_by_fd(int fd, char **subarrayp)
f9ce90ba 1036{
1686dc25
NB
1037 mdu_array_info_t array;
1038 int vers;
1039 int minor;
1040 struct supertype *st = NULL;
7e0f6979 1041 struct mdinfo *sra;
142cb9e1 1042 char *verstr;
1686dc25
NB
1043 char version[20];
1044 int i;
f7e7067b 1045 char *subarray = NULL;
1686dc25
NB
1046
1047 sra = sysfs_read(fd, 0, GET_VERSION);
1048
1049 if (sra) {
7e0f6979
NB
1050 vers = sra->array.major_version;
1051 minor = sra->array.minor_version;
142cb9e1 1052 verstr = sra->text_version;
1686dc25
NB
1053 } else {
1054 if (ioctl(fd, GET_ARRAY_INFO, &array))
1055 array.major_version = array.minor_version = 0;
1056 vers = array.major_version;
1057 minor = array.minor_version;
142cb9e1 1058 verstr = "";
6fbba4c9 1059 }
82d9eba6 1060
1686dc25
NB
1061 if (vers != -1) {
1062 sprintf(version, "%d.%d", vers, minor);
1063 verstr = version;
6fbba4c9 1064 }
3c558363 1065 if (minor == -2 && is_subarray(verstr)) {
f7e7067b
NB
1066 char *dev = verstr+1;
1067 subarray = strchr(dev, '/');
1068 int devnum;
1069 if (subarray)
1070 *subarray++ = '\0';
77472ff8 1071 devnum = devname2devnum(dev);
f7e7067b
NB
1072 subarray = strdup(subarray);
1073 if (sra)
1074 sysfs_free(sra);
1075 sra = sysfs_read(-1, devnum, GET_VERSION);
603f24a0
N
1076 if (sra && sra->text_version[0])
1077 verstr = sra->text_version;
1078 else
1079 verstr = "-no-metadata-";
f7e7067b
NB
1080 }
1081
1082 for (i = 0; st == NULL && superlist[i] ; i++)
1083 st = superlist[i]->match_metadata_desc(verstr);
1686dc25
NB
1084
1085 if (sra)
1086 sysfs_free(sra);
f7e7067b 1087 if (st) {
3b0896f8 1088 st->sb = NULL;
4725bc31
N
1089 *subarrayp = subarray;
1090 } else
1091 free(subarray);
82d9eba6 1092 return st;
f9ce90ba 1093}
ea24acd0
NB
1094#endif /* !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO) */
1095
f9ce90ba 1096
159c3a1a 1097struct supertype *dup_super(struct supertype *orig)
3da92f27 1098{
159c3a1a 1099 struct supertype *st;
1686dc25 1100
d2ca6449
NB
1101 if (!orig)
1102 return orig;
159c3a1a 1103 st = malloc(sizeof(*st));
3da92f27
NB
1104 if (!st)
1105 return st;
ef609477 1106 memset(st, 0, sizeof(*st));
159c3a1a
NB
1107 st->ss = orig->ss;
1108 st->max_devs = orig->max_devs;
1109 st->minor_version = orig->minor_version;
1110 st->sb = NULL;
1111 st->info = NULL;
1112 return st;
3da92f27
NB
1113}
1114
54887ad8 1115struct supertype *guess_super_type(int fd, enum guess_types guess_type)
f9ce90ba
NB
1116{
1117 /* try each load_super to find the best match,
1118 * and return the best superswitch
1119 */
82d9eba6
NB
1120 struct superswitch *ss;
1121 struct supertype *st;
f21e18ca 1122 time_t besttime = 0;
570c0542 1123 int bestsuper = -1;
f9ce90ba
NB
1124 int i;
1125
82d9eba6 1126 st = malloc(sizeof(*st));
d1d599ea
N
1127 memset(st, 0, sizeof(*st));
1128 st->container_dev = NoMdDev;
1129
f9ce90ba
NB
1130 for (i=0 ; superlist[i]; i++) {
1131 int rv;
1132 ss = superlist[i];
54887ad8
N
1133 if (guess_type == guess_array && ss->add_to_super == NULL)
1134 continue;
1135 if (guess_type == guess_partitions && ss->add_to_super != NULL)
1136 continue;
ef609477 1137 memset(st, 0, sizeof(*st));
3da92f27 1138 rv = ss->load_super(st, fd, NULL);
570c0542
NB
1139 if (rv == 0) {
1140 struct mdinfo info;
a5d85af7 1141 st->ss->getinfo_super(st, &info, NULL);
570c0542
NB
1142 if (bestsuper == -1 ||
1143 besttime < info.array.ctime) {
1144 bestsuper = i;
1145 besttime = info.array.ctime;
570c0542 1146 }
3da92f27 1147 ss->free_super(st);
570c0542
NB
1148 }
1149 }
1150 if (bestsuper != -1) {
1151 int rv;
ef609477 1152 memset(st, 0, sizeof(*st));
3da92f27 1153 rv = superlist[bestsuper]->load_super(st, fd, NULL);
f9ce90ba 1154 if (rv == 0) {
5e747af2 1155 superlist[bestsuper]->free_super(st);
82d9eba6 1156 return st;
f9ce90ba
NB
1157 }
1158 }
570c0542 1159 free(st);
f9ce90ba
NB
1160 return NULL;
1161}
fe6729fa 1162
beae1dfe
NB
1163/* Return size of device in bytes */
1164int get_dev_size(int fd, char *dname, unsigned long long *sizep)
1165{
1166 unsigned long long ldsize;
c2c9bb6f
NB
1167 struct stat st;
1168
1169 if (fstat(fd, &st) != -1 && S_ISREG(st.st_mode))
1170 ldsize = (unsigned long long)st.st_size;
1171 else
beae1dfe
NB
1172#ifdef BLKGETSIZE64
1173 if (ioctl(fd, BLKGETSIZE64, &ldsize) != 0)
1174#endif
1175 {
1176 unsigned long dsize;
1177 if (ioctl(fd, BLKGETSIZE, &dsize) == 0) {
1178 ldsize = dsize;
1179 ldsize <<= 9;
1180 } else {
1181 if (dname)
1182 fprintf(stderr, Name ": Cannot get size of %s: %s\b",
1183 dname, strerror(errno));
1184 return 0;
1185 }
1186 }
1187 *sizep = ldsize;
1188 return 1;
1189}
8fac0577 1190
034b203a
TM
1191
1192/* Sets endofpart parameter to the last block used by the last GPT partition on the device.
1193 * Returns: 1 if successful
1194 * -1 for unknown partition type
1195 * 0 for other errors
1196 */
1197static int get_gpt_last_partition_end(int fd, unsigned long long *endofpart)
1198{
056b331e 1199 struct GPT gpt;
034b203a
TM
1200 unsigned char buf[512];
1201 unsigned char empty_gpt_entry[16]= {0};
1202 struct GPT_part_entry *part;
1203 unsigned long long curr_part_end;
1204 unsigned all_partitions, entry_size;
f21e18ca 1205 unsigned part_nr;
034b203a
TM
1206
1207 *endofpart = 0;
1208
056b331e 1209 BUILD_BUG_ON(sizeof(gpt) != 512);
034b203a
TM
1210 /* read GPT header */
1211 lseek(fd, 512, SEEK_SET);
056b331e 1212 if (read(fd, &gpt, 512) != 512)
034b203a
TM
1213 return 0;
1214
1215 /* get the number of partition entries and the entry size */
056b331e
N
1216 all_partitions = __le32_to_cpu(gpt.part_cnt);
1217 entry_size = __le32_to_cpu(gpt.part_size);
034b203a
TM
1218
1219 /* Check GPT signature*/
056b331e 1220 if (gpt.magic != GPT_SIGNATURE_MAGIC)
034b203a
TM
1221 return -1;
1222
1223 /* sanity checks */
1224 if (all_partitions > 1024 ||
1225 entry_size > 512)
1226 return -1;
1227
1228 /* read first GPT partition entries */
1229 if (read(fd, buf, 512) != 512)
1230 return 0;
1231
1232 part = (struct GPT_part_entry*)buf;
1233
1234 for (part_nr=0; part_nr < all_partitions; part_nr++) {
1235 /* is this valid partition? */
1236 if (memcmp(part->type_guid, empty_gpt_entry, 16) != 0) {
1237 /* check the last lba for the current partition */
056b331e 1238 curr_part_end = __le64_to_cpu(part->ending_lba);
034b203a
TM
1239 if (curr_part_end > *endofpart)
1240 *endofpart = curr_part_end;
1241 }
1242
1243 part = (struct GPT_part_entry*)((unsigned char*)part + entry_size);
1244
1245 if ((unsigned char *)part >= buf + 512) {
1246 if (read(fd, buf, 512) != 512)
1247 return 0;
1248 part = (struct GPT_part_entry*)buf;
1249 }
1250 }
1251 return 1;
1252}
1253
1254/* Sets endofpart parameter to the last block used by the last partition on the device.
1255 * Returns: 1 if successful
1256 * -1 for unknown partition type
1257 * 0 for other errors
1258 */
1259static int get_last_partition_end(int fd, unsigned long long *endofpart)
1260{
056b331e 1261 struct MBR boot_sect;
034b203a
TM
1262 struct MBR_part_record *part;
1263 unsigned long long curr_part_end;
f21e18ca 1264 unsigned part_nr;
034b203a
TM
1265 int retval = 0;
1266
1267 *endofpart = 0;
1268
056b331e 1269 BUILD_BUG_ON(sizeof(boot_sect) != 512);
034b203a
TM
1270 /* read MBR */
1271 lseek(fd, 0, 0);
056b331e 1272 if (read(fd, &boot_sect, 512) != 512)
034b203a
TM
1273 goto abort;
1274
1275 /* check MBP signature */
056b331e 1276 if (boot_sect.magic == MBR_SIGNATURE_MAGIC) {
034b203a
TM
1277 retval = 1;
1278 /* found the correct signature */
056b331e 1279 part = boot_sect.parts;
034b203a
TM
1280
1281 for (part_nr=0; part_nr < MBR_PARTITIONS; part_nr++) {
1282 /* check for GPT type */
1283 if (part->part_type == MBR_GPT_PARTITION_TYPE) {
1284 retval = get_gpt_last_partition_end(fd, endofpart);
1285 break;
1286 }
1287 /* check the last used lba for the current partition */
1288 curr_part_end = __le32_to_cpu(part->first_sect_lba) +
1289 __le32_to_cpu(part->blocks_num);
1290 if (curr_part_end > *endofpart)
1291 *endofpart = curr_part_end;
1292
1293 part++;
1294 }
1295 } else {
1296 /* Unknown partition table */
1297 retval = -1;
1298 }
1299 abort:
1300 return retval;
1301}
1302
1303int check_partitions(int fd, char *dname, unsigned long long freesize)
1304{
1305 /*
1306 * Check where the last partition ends
1307 */
1308 unsigned long long endofpart;
1309 int ret;
1310
1311 if ((ret = get_last_partition_end(fd, &endofpart)) > 0) {
1312 /* There appears to be a partition table here */
1313 if (freesize == 0) {
1314 /* partitions will not be visible in new device */
1315 fprintf(stderr,
1316 Name ": partition table exists on %s but will be lost or\n"
1317 " meaningless after creating array\n",
1318 dname);
1319 return 1;
1320 } else if (endofpart > freesize) {
1321 /* last partition overlaps metadata */
1322 fprintf(stderr,
1323 Name ": metadata will over-write last partition on %s.\n",
1324 dname);
1325 return 1;
1326 }
1327 }
1328 return 0;
1329}
1330
8382f19b
NB
1331void get_one_disk(int mdfd, mdu_array_info_t *ainf, mdu_disk_info_t *disk)
1332{
1333 int d;
1334 ioctl(mdfd, GET_ARRAY_INFO, ainf);
1335 for (d = 0 ; d < ainf->raid_disks + ainf->nr_disks ; d++)
1336 if (ioctl(mdfd, GET_DISK_INFO, disk) == 0)
1337 return;
1338}
63152c1b 1339
a322f70c
DW
1340int open_container(int fd)
1341{
1342 /* 'fd' is a block device. Find out if it is in use
1343 * by a container, and return an open fd on that container.
1344 */
1345 char path[256];
1346 char *e;
1347 DIR *dir;
1348 struct dirent *de;
1349 int dfd, n;
1350 char buf[200];
1351 int major, minor;
1352 struct stat st;
1353
1354 if (fstat(fd, &st) != 0)
1355 return -1;
1356 sprintf(path, "/sys/dev/block/%d:%d/holders",
1357 (int)major(st.st_rdev), (int)minor(st.st_rdev));
1358 e = path + strlen(path);
1359
1360 dir = opendir(path);
1361 if (!dir)
1362 return -1;
1363 while ((de = readdir(dir))) {
1364 if (de->d_ino == 0)
1365 continue;
1366 if (de->d_name[0] == '.')
1367 continue;
1368 sprintf(e, "/%s/dev", de->d_name);
1369 dfd = open(path, O_RDONLY);
1370 if (dfd < 0)
1371 continue;
1372 n = read(dfd, buf, sizeof(buf));
1373 close(dfd);
f21e18ca 1374 if (n <= 0 || (unsigned)n >= sizeof(buf))
a322f70c
DW
1375 continue;
1376 buf[n] = 0;
1377 if (sscanf(buf, "%d:%d", &major, &minor) != 2)
1378 continue;
1379 sprintf(buf, "%d:%d", major, minor);
1380 dfd = dev_open(buf, O_RDONLY);
1381 if (dfd >= 0) {
1382 closedir(dir);
1383 return dfd;
1384 }
1385 }
355726fa 1386 closedir(dir);
a322f70c
DW
1387 return -1;
1388}
1389
33414a01
DW
1390struct superswitch *version_to_superswitch(char *vers)
1391{
1392 int i;
1393
1394 for (i = 0; superlist[i]; i++) {
1395 struct superswitch *ss = superlist[i];
1396
1397 if (strcmp(vers, ss->name) == 0)
1398 return ss;
1399 }
1400
1401 return NULL;
1402}
1403
1404int is_container_member(struct mdstat_ent *mdstat, char *container)
1405{
1406 if (mdstat->metadata_version == NULL ||
1407 strncmp(mdstat->metadata_version, "external:", 9) != 0 ||
1408 !is_subarray(mdstat->metadata_version+9) ||
1409 strncmp(mdstat->metadata_version+10, container, strlen(container)) != 0 ||
1410 mdstat->metadata_version[10+strlen(container)] != '/')
1411 return 0;
1412
1413 return 1;
1414}
1415
1416int is_subarray_active(char *subarray, char *container)
1417{
1418 struct mdstat_ent *mdstat = mdstat_read(0, 0);
1419 struct mdstat_ent *ent;
1420
1421 for (ent = mdstat; ent; ent = ent->next) {
1422 if (is_container_member(ent, container)) {
1423 char *inst = &ent->metadata_version[10+strlen(container)+1];
1424
1dccfff9 1425 if (!subarray || strcmp(inst, subarray) == 0)
33414a01
DW
1426 break;
1427 }
1428 }
1429
1430 free_mdstat(mdstat);
1431
1432 return ent != NULL;
1433}
1434
1dccfff9
DW
1435int is_container_active(char *container)
1436{
1437 return is_subarray_active(NULL, container);
1438}
1439
33414a01
DW
1440/* open_subarray - opens a subarray in a container
1441 * @dev: container device name
feab51f8 1442 * @st: empty supertype
33414a01
DW
1443 * @quiet: block reporting errors flag
1444 *
1445 * On success returns an fd to a container and fills in *st
1446 */
feab51f8 1447int open_subarray(char *dev, char *subarray, struct supertype *st, int quiet)
33414a01
DW
1448{
1449 struct mdinfo *mdi;
a951a4f7 1450 struct mdinfo *info;
33414a01
DW
1451 int fd, err = 1;
1452
1453 fd = open(dev, O_RDWR|O_EXCL);
1454 if (fd < 0) {
1455 if (!quiet)
1456 fprintf(stderr, Name ": Couldn't open %s, aborting\n",
1457 dev);
1458 return 2;
1459 }
1460
1461 st->devnum = fd2devnum(fd);
1462 if (st->devnum == NoMdDev) {
1463 if (!quiet)
1464 fprintf(stderr,
1465 Name ": Failed to determine device number for %s\n",
1466 dev);
1467 goto close_fd;
1468 }
1469
1470 mdi = sysfs_read(fd, st->devnum, GET_VERSION|GET_LEVEL);
1471 if (!mdi) {
1472 if (!quiet)
1473 fprintf(stderr, Name ": Failed to read sysfs for %s\n",
1474 dev);
1475 goto close_fd;
1476 }
1477
1478 if (mdi->array.level != UnSet) {
1479 if (!quiet)
1480 fprintf(stderr, Name ": %s is not a container\n", dev);
1481 goto free_sysfs;
1482 }
1483
1484 st->ss = version_to_superswitch(mdi->text_version);
1485 if (!st->ss) {
1486 if (!quiet)
1487 fprintf(stderr,
1488 Name ": Operation not supported for %s metadata\n",
1489 mdi->text_version);
1490 goto free_sysfs;
1491 }
1492
1493 st->devname = devnum2devname(st->devnum);
1494 if (!st->devname) {
1495 if (!quiet)
1496 fprintf(stderr, Name ": Failed to allocate device name\n");
1497 goto free_sysfs;
1498 }
1499
1500 if (st->ss->load_super(st, fd, NULL)) {
1501 if (!quiet)
a951a4f7
N
1502 fprintf(stderr, Name ": Failed to load metadata for %s\n",
1503 dev);
33414a01
DW
1504 goto free_name;
1505 }
1506
1507 if (!st->loaded_container) {
1508 if (!quiet)
1509 fprintf(stderr, Name ": %s is not a container\n", dev);
1510 goto free_super;
1511 }
1512
a951a4f7
N
1513 info = st->ss->container_content(st, subarray);
1514 if (!info) {
1515 if (!quiet)
1516 fprintf(stderr, Name ": Failed to find subarray-%s in %s\n",
1517 subarray, dev);
1518 goto free_super;
1519 }
1520 free(info);
1521
33414a01
DW
1522 err = 0;
1523
1524 free_super:
1525 if (err)
1526 st->ss->free_super(st);
1527 free_name:
1528 if (err)
1529 free(st->devname);
1530 free_sysfs:
1531 sysfs_free(mdi);
1532 close_fd:
1533 if (err)
1534 close(fd);
1535
1536 if (err)
1537 return -1;
1538 else
1539 return fd;
1540}
1541
7801ac20
N
1542int add_disk(int mdfd, struct supertype *st,
1543 struct mdinfo *sra, struct mdinfo *info)
1544{
1545 /* Add a device to an array, in one of 2 ways. */
1546 int rv;
1547#ifndef MDASSEMBLE
1548 if (st->ss->external) {
d23534e4
DW
1549 if (info->disk.state & (1<<MD_DISK_SYNC))
1550 info->recovery_start = MaxSector;
1551 else
1552 info->recovery_start = 0;
2904b26f 1553 rv = sysfs_add_disk(sra, info, 0);
7801ac20
N
1554 if (! rv) {
1555 struct mdinfo *sd2;
f35f2525
N
1556 for (sd2 = sra->devs; sd2; sd2=sd2->next)
1557 if (sd2 == info)
1558 break;
1559 if (sd2 == NULL) {
1560 sd2 = malloc(sizeof(*sd2));
1561 *sd2 = *info;
1562 sd2->next = sra->devs;
1563 sra->devs = sd2;
1564 }
7801ac20
N
1565 }
1566 } else
1567#endif
1568 rv = ioctl(mdfd, ADD_NEW_DISK, &info->disk);
1569 return rv;
1570}
1571
f35f2525
N
1572int set_array_info(int mdfd, struct supertype *st, struct mdinfo *info)
1573{
1574 /* Initialise kernel's knowledge of array.
1575 * This varies between externally managed arrays
1576 * and older kernels
1577 */
1578 int vers = md_get_version(mdfd);
1579 int rv;
1580
1581#ifndef MDASSEMBLE
1582 if (st->ss->external)
1583 rv = sysfs_set_array(info, vers);
1584 else
1585#endif
1586 if ((vers % 100) >= 1) { /* can use different versions */
1587 mdu_array_info_t inf;
1588 memset(&inf, 0, sizeof(inf));
1589 inf.major_version = info->array.major_version;
1590 inf.minor_version = info->array.minor_version;
1591 rv = ioctl(mdfd, SET_ARRAY_INFO, &inf);
1592 } else
1593 rv = ioctl(mdfd, SET_ARRAY_INFO, NULL);
1594 return rv;
1595}
1596
1e5c6983
DW
1597unsigned long long min_recovery_start(struct mdinfo *array)
1598{
1599 /* find the minimum recovery_start in an array for metadata
1600 * formats that only record per-array recovery progress instead
1601 * of per-device
1602 */
1603 unsigned long long recovery_start = MaxSector;
1604 struct mdinfo *d;
1605
1606 for (d = array->devs; d; d = d->next)
1607 recovery_start = min(recovery_start, d->recovery_start);
1608
1609 return recovery_start;
1610}
1611
2f6079dc
NB
1612char *devnum2devname(int num)
1613{
1614 char name[100];
1f0769d7 1615 if (num >= 0)
2f6079dc
NB
1616 sprintf(name, "md%d", num);
1617 else
1618 sprintf(name, "md_d%d", -1-num);
1619 return strdup(name);
1620}
1621
77472ff8
NB
1622int devname2devnum(char *name)
1623{
1624 char *ep;
1625 int num;
1626 if (strncmp(name, "md_d", 4)==0)
1627 num = -1-strtoul(name+4, &ep, 10);
1628 else
1629 num = strtoul(name+2, &ep, 10);
1630 return num;
1631}
1632
c94709e8 1633int stat2devnum(struct stat *st)
2f6079dc 1634{
d7ab966b
N
1635 char path[30];
1636 char link[200];
1637 char *cp;
1638 int n;
1639
c94709e8
DW
1640 if ((S_IFMT & st->st_mode) == S_IFBLK) {
1641 if (major(st->st_rdev) == MD_MAJOR)
1642 return minor(st->st_rdev);
f21e18ca 1643 else if (major(st->st_rdev) == (unsigned)get_mdp_major())
d7ab966b
N
1644 return -1- (minor(st->st_rdev)>>MdpMinorShift);
1645
1646 /* must be an extended-minor partition. Look at the
1647 * /sys/dev/block/%d:%d link which must look like
1648 * ../../block/mdXXX/mdXXXpYY
1649 */
1650 sprintf(path, "/sys/dev/block/%d:%d", major(st->st_rdev),
1651 minor(st->st_rdev));
1652 n = readlink(path, link, sizeof(link)-1);
1653 if (n <= 0)
1654 return NoMdDev;
1655 link[n] = 0;
1656 cp = strrchr(link, '/');
1657 if (cp) *cp = 0;
1658 cp = strchr(link, '/');
1659 if (cp && strncmp(cp, "/md", 3) == 0)
1660 return devname2devnum(cp+1);
2f6079dc 1661 }
d7ab966b 1662 return NoMdDev;
c94709e8
DW
1663
1664}
1665
1666int fd2devnum(int fd)
1667{
1668 struct stat stb;
1669 if (fstat(fd, &stb) == 0)
1670 return stat2devnum(&stb);
d7ab966b 1671 return NoMdDev;
2f6079dc
NB
1672}
1673
24f6f99b 1674int mdmon_pid(int devnum)
a931db9e
NB
1675{
1676 char path[100];
1677 char pid[10];
1678 int fd;
1679 int n;
10013317
PHC
1680 char *devname = devnum2devname(devnum);
1681
753cf905 1682 sprintf(path, "%s/%s.pid", MDMON_DIR, devname);
10013317
PHC
1683 free(devname);
1684
24f6f99b 1685 fd = open(path, O_RDONLY | O_NOATIME, 0);
a931db9e
NB
1686
1687 if (fd < 0)
cf556303 1688 return -1;
a931db9e
NB
1689 n = read(fd, pid, 9);
1690 close(fd);
1691 if (n <= 0)
cf556303 1692 return -1;
24f6f99b 1693 return atoi(pid);
a931db9e
NB
1694}
1695
24f6f99b 1696int mdmon_running(int devnum)
a931db9e 1697{
24f6f99b
N
1698 int pid = mdmon_pid(devnum);
1699 if (pid <= 0)
a931db9e 1700 return 0;
24f6f99b 1701 if (kill(pid, 0) == 0)
a931db9e
NB
1702 return 1;
1703 return 0;
1704}
1705
8850ee3e
N
1706int start_mdmon(int devnum)
1707{
1708 int i;
44d2e365 1709 int len;
9fe32043
N
1710 pid_t pid;
1711 int status;
44d2e365
N
1712 char pathbuf[1024];
1713 char *paths[4] = {
1714 pathbuf,
1715 "/sbin/mdmon",
1716 "mdmon",
1717 NULL
1718 };
8850ee3e 1719
40ebbb9c 1720 if (check_env("MDADM_NO_MDMON"))
8850ee3e
N
1721 return 0;
1722
44d2e365
N
1723 len = readlink("/proc/self/exe", pathbuf, sizeof(pathbuf));
1724 if (len > 0) {
1725 char *sl;
1726 pathbuf[len] = 0;
1727 sl = strrchr(pathbuf, '/');
1728 if (sl)
1729 sl++;
1730 else
1731 sl = pathbuf;
1732 strcpy(sl, "mdmon");
1733 } else
1734 pathbuf[0] = '\0';
1735
8850ee3e
N
1736 switch(fork()) {
1737 case 0:
1738 /* FIXME yuk. CLOSE_EXEC?? */
1739 for (i=3; i < 100; i++)
1740 close(i);
44d2e365
N
1741 for (i=0; paths[i]; i++)
1742 if (paths[i][0])
1743 execl(paths[i], "mdmon",
e8a70c89
N
1744 devnum2devname(devnum),
1745 NULL);
8850ee3e
N
1746 exit(1);
1747 case -1: fprintf(stderr, Name ": cannot run mdmon. "
1748 "Array remains readonly\n");
1749 return -1;
9fe32043
N
1750 default: /* parent - good */
1751 pid = wait(&status);
1752 if (pid < 0 || status != 0)
1753 return -1;
8850ee3e
N
1754 }
1755 return 0;
1756}
1757
40ebbb9c 1758int check_env(char *name)
5dcfcb71 1759{
40ebbb9c 1760 char *val = getenv(name);
5dcfcb71
DW
1761
1762 if (val && atoi(val) == 1)
1763 return 1;
1764
1765 return 0;
1766}
1767
148acb7b
DW
1768__u32 random32(void)
1769{
1770 __u32 rv;
1771 int rfd = open("/dev/urandom", O_RDONLY);
1772 if (rfd < 0 || read(rfd, &rv, 4) != 4)
1773 rv = random();
1774 if (rfd >= 0)
1775 close(rfd);
1776 return rv;
1777}
1778
0e600426 1779#ifndef MDASSEMBLE
edd8d13c
NB
1780int flush_metadata_updates(struct supertype *st)
1781{
1782 int sfd;
1783 if (!st->updates) {
1784 st->update_tail = NULL;
1785 return -1;
1786 }
1787
1788 sfd = connect_monitor(devnum2devname(st->container_dev));
1789 if (sfd < 0)
1790 return -1;
1791
1792 while (st->updates) {
1793 struct metadata_update *mu = st->updates;
1794 st->updates = mu->next;
1795
1796 send_message(sfd, mu, 0);
1797 wait_reply(sfd, 0);
1798 free(mu->buf);
1799 free(mu);
1800 }
1801 ack(sfd, 0);
1802 wait_reply(sfd, 0);
1803 close(sfd);
1804 st->update_tail = NULL;
1805 return 0;
1806}
1807
1808void append_metadata_update(struct supertype *st, void *buf, int len)
1809{
1810
1811 struct metadata_update *mu = malloc(sizeof(*mu));
1812
1813 mu->buf = buf;
1814 mu->len = len;
1815 mu->space = NULL;
1816 mu->next = NULL;
1817 *st->update_tail = mu;
1818 st->update_tail = &mu->next;
1819}
0e600426 1820#endif /* MDASSEMBLE */
a931db9e 1821
fe6729fa
NB
1822#ifdef __TINYC__
1823/* tinyc doesn't optimize this check in ioctl.h out ... */
1824unsigned int __invalid_size_argument_for_IOC = 0;
1825#endif
1826