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