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