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