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