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