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