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