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