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