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