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