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