]> git.ipfire.org Git - thirdparty/mdadm.git/blob - util.c
Set home-cluster while creating an array
[thirdparty/mdadm.git] / util.c
1 /*
2 * mdadm - manage Linux "md" devices aka RAID arrays.
3 *
4 * Copyright (C) 2001-2013 Neil Brown <neilb@suse.de>
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
22 * Email: <neilb@suse.de>
23 */
24
25 #include "mdadm.h"
26 #include "md_p.h"
27 #include <sys/socket.h>
28 #include <sys/utsname.h>
29 #include <sys/wait.h>
30 #include <sys/un.h>
31 #include <sys/resource.h>
32 #include <sys/vfs.h>
33 #include <linux/magic.h>
34 #include <ctype.h>
35 #include <dirent.h>
36 #include <signal.h>
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
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 */
55 struct blkpg_ioctl_arg {
56 int op;
57 int flags;
58 int datalen;
59 void *data;
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 */
71 struct 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 };
79
80 #include "part.h"
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
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 */
97 int parse_uuid(char *str, int uuid[4])
98 {
99 int hit = 0; /* number of Hex digIT */
100 int i;
101 char c;
102 for (i = 0; i < 4; i++)
103 uuid[i] = 0;
104
105 while ((c = *str++) != 0) {
106 int n;
107 if (c >= '0' && c <= '9')
108 n = c-'0';
109 else if (c >= 'a' && c <= 'f')
110 n = 10 + c - 'a';
111 else if (c >= 'A' && c <= 'F')
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++;
122 }
123 if (hit == 32)
124 return 1;
125 return 0;
126 }
127
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
138 int md_get_version(int fd)
139 {
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);
154 return -1;
155 }
156
157 int get_linux_version()
158 {
159 struct utsname name;
160 char *cp;
161 int a = 0, b = 0,c = 0;
162 if (uname(&name) <0)
163 return -1;
164
165 cp = name.release;
166 a = strtoul(cp, &cp, 10);
167 if (*cp == '.')
168 b = strtoul(cp+1, &cp, 10);
169 if (*cp == '.')
170 c = strtoul(cp+1, &cp, 10);
171
172 return (a*1000000)+(b*1000)+c;
173 }
174
175 #ifndef MDASSEMBLE
176 int 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
201 unsigned long long parse_size(char *size)
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)
207 * INVALID_SECTORS returned on error.
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;
226 case 's': /* sectors */
227 c++;
228 break;
229 }
230 } else
231 s = INVALID_SECTORS;
232 if (*c)
233 s = INVALID_SECTORS;
234 return s;
235 }
236
237 int 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
257 int parse_layout_faulty(char *layout)
258 {
259 /* Parse the layout string for 'faulty' */
260 int ln = strcspn(layout, "0123456789");
261 char *m = xstrdup(layout);
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 }
270
271 long 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 }
281 #endif
282
283 void 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);
297 for (p.pno = 0; p.pno < 16; p.pno++)
298 ioctl(fd, BLKPG, &a);
299 #endif
300 }
301
302 int 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;
319 if (errno == ENXIO || errno == ENOTTY)
320 /* not a partition */
321 return 0;
322
323 return 1;
324 }
325
326 int 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 }
339
340 int enough(int level, int raid_disks, int layout, int clean, char *avail)
341 {
342 int copies, first;
343 int i;
344 int avail_disks = 0;
345
346 for (i = 0; i < raid_disks; i++)
347 avail_disks += !!avail[i];
348
349 switch (level) {
350 case 10:
351 /* This is the tricky one - we need to check
352 * which actual disks are present.
353 */
354 copies = (layout&255)* ((layout>>8) & 255);
355 first = 0;
356 do {
357 /* there must be one of the 'copies' form 'first' */
358 int n = copies;
359 int cnt = 0;
360 int this = first;
361 while (n--) {
362 if (avail[this])
363 cnt++;
364 this = (this+1) % raid_disks;
365 }
366 if (cnt == 0)
367 return 0;
368 first = (first+(layout&255)) % raid_disks;
369 } while (first != 0);
370 return 1;
371
372 case LEVEL_MULTIPATH:
373 return avail_disks>= 1;
374 case LEVEL_LINEAR:
375 case 0:
376 return avail_disks == raid_disks;
377 case 1:
378 return avail_disks >= 1;
379 case 4:
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 */
387 case 5:
388 if (clean)
389 return avail_disks >= raid_disks-1;
390 else
391 return avail_disks >= raid_disks;
392 case 6:
393 if (clean)
394 return avail_disks >= raid_disks-2;
395 else
396 return avail_disks >= raid_disks;
397 default:
398 return 0;
399 }
400 }
401
402 int enough_fd(int fd)
403 {
404 struct mdu_array_info_s array;
405 struct mdu_disk_info_s disk;
406 int i, rv;
407 char *avail;
408
409 if (ioctl(fd, GET_ARRAY_INFO, &array) != 0 ||
410 array.raid_disks <= 0)
411 return 0;
412 avail = xcalloc(array.raid_disks, 1);
413 for (i = 0; i < MAX_DISKS && array.nr_disks > 0; i++) {
414 disk.number = i;
415 if (ioctl(fd, GET_DISK_INFO, &disk) != 0)
416 continue;
417 if (disk.major == 0 && disk.minor == 0)
418 continue;
419 array.nr_disks--;
420
421 if (! (disk.state & (1<<MD_DISK_SYNC)))
422 continue;
423 if (disk.raid_disk < 0 || disk.raid_disk >= array.raid_disks)
424 continue;
425 avail[disk.raid_disk] = 1;
426 }
427 /* This is used on an active array, so assume it is clean */
428 rv = enough(array.level, array.raid_disks, array.layout,
429 1, avail);
430 free(avail);
431 return rv;
432 }
433
434 const int uuid_zero[4] = { 0, 0, 0, 0 };
435
436 int same_uuid(int a[4], int b[4], int swapuuid)
437 {
438 if (swapuuid) {
439 /* parse uuids are hostendian.
440 * uuid's from some superblocks are big-ending
441 * if there is a difference, we need to swap..
442 */
443 unsigned char *ac = (unsigned char *)a;
444 unsigned char *bc = (unsigned char *)b;
445 int i;
446 for (i = 0; i < 16; i += 4) {
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 }
462 }
463
464 void 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;
474 for (i = 0; i < 16; i += 4) {
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 }
483
484 char *__fname_from_uuid(int id[4], int swap, char *buf, char sep)
485 {
486 int i, j;
487 char uuid[16];
488 char *c = buf;
489 strcpy(c, "UUID-");
490 c += strlen(c);
491 copy_uuid(uuid, id, swap);
492 for (i = 0; i < 4; i++) {
493 if (i)
494 *c++ = sep;
495 for (j = 3; j >= 0; j--) {
496 sprintf(c,"%02x", (unsigned char) uuid[j+4*i]);
497 c+= 2;
498 }
499 }
500 return buf;
501
502 }
503
504 char *fname_from_uuid(struct supertype *st, struct mdinfo *info, char *buf, char sep)
505 {
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);
512 }
513
514 #ifndef MDASSEMBLE
515 int 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;
528 unsigned long long size;
529 int bsize;
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;
540 size <<= bsize;
541 pr_err("%s appears to contain an ext2fs file system\n",
542 name);
543 cont_err("size=%lluK mtime=%s", size, ctime(&mtime));
544 return 1;
545 }
546
547 int 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];
556 unsigned long long size;
557 if (lseek(fd, 64*1024, 0) != 64*1024)
558 return 0;
559 if (read(fd, sb, 1024) != 1024)
560 return 0;
561 if (strncmp((char*)sb+52, "ReIsErFs",8) != 0 &&
562 strncmp((char*)sb+52, "ReIsEr2Fs",9) != 0)
563 return 0;
564 pr_err("%s appears to contain a reiserfs file system\n",name);
565 size = sb[0]|(sb[1]|(sb[2]|sb[3]<<8)<<8)<<8;
566 cont_err("size = %lluK\n", size*4);
567
568 return 1;
569 }
570
571 int check_raid(int fd, char *name)
572 {
573 struct mdinfo info;
574 time_t crtime;
575 char *level;
576 struct supertype *st = guess_super(fd);
577
578 if (!st)
579 return 0;
580 st->ss->load_super(st, fd, name);
581 /* Looks like a raid array .. */
582 pr_err("%s appears to be part of a raid array:\n",
583 name);
584 st->ss->getinfo_super(st, &info, NULL);
585 st->ss->free_super(st);
586 crtime = info.array.ctime;
587 level = map_num(pers, info.array.level);
588 if (!level) level = "-unknown-";
589 cont_err("level=%s devices=%d ctime=%s",
590 level, info.array.raid_disks, ctime(&crtime));
591 return 1;
592 }
593
594 int ask(char *mesg)
595 {
596 char *add = "";
597 int i;
598 for (i = 0; i < 5; i++) {
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 }
610 pr_err("assuming 'no'\n");
611 return 0;
612 }
613 #endif /* MDASSEMBLE */
614
615 int is_standard(char *dev, int *nump)
616 {
617 /* tests if dev is a "standard" md dev name.
618 * i.e if the last component is "/dNN" or "/mdNN",
619 * where NN is a string of digits
620 * Returns 1 if a partitionable standard,
621 * -1 if non-partitonable,
622 * 0 if not a standard name.
623 */
624 char *d = strrchr(dev, '/');
625 int type = 0;
626 int num;
627 if (!d)
628 return 0;
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 */
637 else
638 return 0;
639 if (!*d)
640 return 0;
641 num = atoi(d);
642 while (isdigit(*d))
643 d++;
644 if (*d)
645 return 0;
646 if (nump) *nump = num;
647
648 return type;
649 }
650
651 unsigned long calc_csum(void *super, int bytes)
652 {
653 unsigned long long newcsum = 0;
654 int i;
655 unsigned int csum;
656 unsigned int *superc = (unsigned int*) super;
657
658 for(i = 0; i < bytes/4; i++)
659 newcsum += superc[i];
660 csum = (newcsum& 0xffffffff) + (newcsum>>32);
661 #ifdef __alpha__
662 /* The in-kernel checksum calculation is always 16bit on
663 * the alpha, though it is 32 bit on i386...
664 * I wonder what it is elsewhere... (it uses an API in
665 * a way that it shouldn't).
666 */
667 csum = (csum & 0xffff) + (csum >> 16);
668 csum = (csum & 0xffff) + (csum >> 16);
669 #endif
670 return csum;
671 }
672
673 #ifndef MDASSEMBLE
674 char *human_size(long long bytes)
675 {
676 static char buf[30];
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.
684 * Terabytes are not yet handled.
685 */
686
687 if (bytes < 5000*1024)
688 buf[0] = 0;
689 else if (bytes < 2*1024LL*1024LL*1024LL) {
690 long cMiB = (bytes * 200LL / (1LL<<20) + 1) / 2;
691 long cMB = (bytes / ( 1000000LL / 200LL ) +1) /2;
692 snprintf(buf, sizeof(buf), " (%ld.%02ld MiB %ld.%02ld MB)",
693 cMiB/100 , cMiB % 100,
694 cMB/100, cMB % 100);
695 } else {
696 long cGiB = (bytes * 200LL / (1LL<<30) +1) / 2;
697 long cGB = (bytes / (1000000000LL/200LL ) +1) /2;
698 snprintf(buf, sizeof(buf), " (%ld.%02ld GiB %ld.%02ld GB)",
699 cGiB/100 , cGiB % 100,
700 cGB/100, cGB % 100);
701 }
702 return buf;
703 }
704
705 char *human_size_brief(long long bytes, int prefix)
706 {
707 static char buf[30];
708
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.
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.
719 */
720
721 if (bytes < 5000*1024)
722 buf[0] = 0;
723 else if (prefix == IEC) {
724 if (bytes < 2*1024LL*1024LL*1024LL) {
725 long cMiB = (bytes * 200LL / (1LL<<20) +1) /2;
726 snprintf(buf, sizeof(buf), "%ld.%02ldMiB",
727 cMiB/100 , cMiB % 100);
728 } else {
729 long cGiB = (bytes * 200LL / (1LL<<30) +1) /2;
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 }
744 }
745 else
746 buf[0] = 0;
747
748 return buf;
749 }
750
751 void 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 }
767 #endif
768
769 unsigned long long calc_array_size(int level, int raid_disks, int layout,
770 int chunksize, unsigned long long devsize)
771 {
772 if (level == 1)
773 return devsize;
774 devsize &= ~(unsigned long long)((chunksize>>9)-1);
775 return get_data_disks(level, layout, raid_disks) * devsize;
776 }
777
778 int get_data_disks(int level, int layout, int raid_disks)
779 {
780 int data_disks = 0;
781 switch (level) {
782 case 0: data_disks = raid_disks;
783 break;
784 case 1: data_disks = 1;
785 break;
786 case 4:
787 case 5: data_disks = raid_disks - 1;
788 break;
789 case 6: data_disks = raid_disks - 2;
790 break;
791 case 10: data_disks = raid_disks / (layout & 255) / ((layout>>8)&255);
792 break;
793 }
794
795 return data_disks;
796 }
797
798 int 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
834 #if !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO)
835 char *get_md_name(char *devnm)
836 {
837 /* find /dev/md%d or /dev/md/%d or make a device /dev/.tmp.md%d */
838 /* if dev < 0, want /dev/md/d%d or find mdp in /proc/devices ... */
839
840 static char devname[50];
841 struct stat stb;
842 dev_t rdev = devnm2devid(devnm);
843 char *dn;
844
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);
850 if (stat(devname, &stb) == 0
851 && (S_IFMT&stb.st_mode) == S_IFBLK
852 && (stb.st_rdev == rdev))
853 return devname;
854 }
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
867 dn = map_dev(major(rdev), minor(rdev), 0);
868 if (dn)
869 return dn;
870 snprintf(devname, sizeof(devname), "/dev/.tmp.%s", devnm);
871 if (mknod(devname, S_IFBLK | 0600, rdev) == -1)
872 if (errno != EEXIST)
873 return NULL;
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
883 void put_md_name(char *name)
884 {
885 if (strncmp(name, "/dev/.tmp.md", 12) == 0)
886 unlink(name);
887 }
888 #endif /* !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO) */
889
890 int 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
899 int 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 */
904 int fd = -1;
905 char devname[32];
906 int major;
907 int minor;
908
909 if (!dev) return -1;
910 flags |= O_DIRECT;
911
912 if (get_maj_min(dev, &major, &minor)) {
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);
918 }
919 if (fd < 0) {
920 /* Try /tmp as /dev appear to be read-only */
921 snprintf(devname, sizeof(devname), "/tmp/.tmp.md.%d:%d:%d",
922 (int)getpid(), major, minor);
923 if (mknod(devname, S_IFBLK|0600, makedev(major, minor)) == 0) {
924 fd = open(devname, flags);
925 unlink(devname);
926 }
927 }
928 } else
929 fd = open(dev, flags);
930 return fd;
931 }
932
933 int open_dev_flags(char *devnm, int flags)
934 {
935 int devid;
936 char buf[20];
937
938 devid = devnm2devid(devnm);
939 sprintf(buf, "%d:%d", major(devid), minor(devid));
940 return dev_open(buf, flags);
941 }
942
943 int open_dev(char *devnm)
944 {
945 return open_dev_flags(devnm, O_RDONLY);
946 }
947
948 int open_dev_excl(char *devnm)
949 {
950 char buf[20];
951 int i;
952 int flags = O_RDWR;
953 int devid = devnm2devid(devnm);
954 long delay = 1000;
955
956 sprintf(buf, "%d:%d", major(devid), minor(devid));
957 for (i = 0 ; i < 25 ; i++) {
958 int fd = dev_open(buf, flags|O_EXCL);
959 if (fd >= 0)
960 return fd;
961 if (errno == EACCES && flags == O_RDWR) {
962 flags = O_RDONLY;
963 continue;
964 }
965 if (errno != EBUSY)
966 return fd;
967 usleep(delay);
968 if (delay < 200000)
969 delay *= 2;
970 }
971 return -1;
972 }
973
974 int 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
988 void wait_for(char *dev, int fd)
989 {
990 int i;
991 struct stat stb_want;
992 long delay = 1000;
993
994 if (fstat(fd, &stb_want) != 0 ||
995 (stb_want.st_mode & S_IFMT) != S_IFBLK)
996 return;
997
998 for (i = 0 ; i < 25 ; i++) {
999 struct stat stb;
1000 if (stat(dev, &stb) == 0 &&
1001 (stb.st_mode & S_IFMT) == S_IFBLK &&
1002 (stb.st_rdev == stb_want.st_rdev))
1003 return;
1004 usleep(delay);
1005 if (delay < 200000)
1006 delay *= 2;
1007 }
1008 if (i == 25)
1009 dprintf("timeout waiting for %s\n", dev);
1010 }
1011
1012 struct superswitch *superlist[] =
1013 {
1014 &super0, &super1,
1015 &super_ddf, &super_imsm,
1016 &mbr, &gpt,
1017 NULL };
1018
1019 #if !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO)
1020
1021 struct supertype *super_by_fd(int fd, char **subarrayp)
1022 {
1023 mdu_array_info_t array;
1024 int vers;
1025 int minor;
1026 struct supertype *st = NULL;
1027 struct mdinfo *sra;
1028 char *verstr;
1029 char version[20];
1030 int i;
1031 char *subarray = NULL;
1032 char container[32] = "";
1033
1034 sra = sysfs_read(fd, NULL, GET_VERSION);
1035
1036 if (sra) {
1037 vers = sra->array.major_version;
1038 minor = sra->array.minor_version;
1039 verstr = sra->text_version;
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;
1045 verstr = "";
1046 }
1047
1048 if (vers != -1) {
1049 sprintf(version, "%d.%d", vers, minor);
1050 verstr = version;
1051 }
1052 if (minor == -2 && is_subarray(verstr)) {
1053 char *dev = verstr+1;
1054
1055 subarray = strchr(dev, '/');
1056 if (subarray) {
1057 *subarray++ = '\0';
1058 subarray = xstrdup(subarray);
1059 }
1060 strcpy(container, dev);
1061 if (sra)
1062 sysfs_free(sra);
1063 sra = sysfs_read(-1, container, GET_VERSION);
1064 if (sra && sra->text_version[0])
1065 verstr = sra->text_version;
1066 else
1067 verstr = "-no-metadata-";
1068 }
1069
1070 for (i = 0; st == NULL && superlist[i] ; i++)
1071 st = superlist[i]->match_metadata_desc(verstr);
1072
1073 if (sra)
1074 sysfs_free(sra);
1075 if (st) {
1076 st->sb = NULL;
1077 if (subarrayp)
1078 *subarrayp = subarray;
1079 strcpy(st->container_devnm, container);
1080 strcpy(st->devnm, fd2devnm(fd));
1081 } else
1082 free(subarray);
1083
1084 return st;
1085 }
1086 #endif /* !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO) */
1087
1088 int dev_size_from_id(dev_t id, unsigned long long *size)
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 }
1104
1105 struct supertype *dup_super(struct supertype *orig)
1106 {
1107 struct supertype *st;
1108
1109 if (!orig)
1110 return orig;
1111 st = xcalloc(1, sizeof(*st));
1112 st->ss = orig->ss;
1113 st->max_devs = orig->max_devs;
1114 st->minor_version = orig->minor_version;
1115 st->ignore_hw_compat = orig->ignore_hw_compat;
1116 st->data_offset = orig->data_offset;
1117 st->sb = NULL;
1118 st->info = NULL;
1119 return st;
1120 }
1121
1122 struct supertype *guess_super_type(int fd, enum guess_types guess_type)
1123 {
1124 /* try each load_super to find the best match,
1125 * and return the best superswitch
1126 */
1127 struct superswitch *ss;
1128 struct supertype *st;
1129 time_t besttime = 0;
1130 int bestsuper = -1;
1131 int i;
1132
1133 st = xcalloc(1, sizeof(*st));
1134 st->container_devnm[0] = 0;
1135
1136 for (i = 0 ; superlist[i]; i++) {
1137 int rv;
1138 ss = superlist[i];
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;
1143 memset(st, 0, sizeof(*st));
1144 st->ignore_hw_compat = 1;
1145 rv = ss->load_super(st, fd, NULL);
1146 if (rv == 0) {
1147 struct mdinfo info;
1148 st->ss->getinfo_super(st, &info, NULL);
1149 if (bestsuper == -1 ||
1150 besttime < info.array.ctime) {
1151 bestsuper = i;
1152 besttime = info.array.ctime;
1153 }
1154 ss->free_super(st);
1155 }
1156 }
1157 if (bestsuper != -1) {
1158 int rv;
1159 memset(st, 0, sizeof(*st));
1160 st->ignore_hw_compat = 1;
1161 rv = superlist[bestsuper]->load_super(st, fd, NULL);
1162 if (rv == 0) {
1163 superlist[bestsuper]->free_super(st);
1164 return st;
1165 }
1166 }
1167 free(st);
1168 return NULL;
1169 }
1170
1171 /* Return size of device in bytes */
1172 int get_dev_size(int fd, char *dname, unsigned long long *sizep)
1173 {
1174 unsigned long long ldsize;
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
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)
1190 pr_err("Cannot get size of %s: %s\b",
1191 dname, strerror(errno));
1192 return 0;
1193 }
1194 }
1195 *sizep = ldsize;
1196 return 1;
1197 }
1198
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 */
1202 int 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 }
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 */
1219 static int get_gpt_last_partition_end(int fd, unsigned long long *endofpart)
1220 {
1221 struct GPT gpt;
1222 unsigned char empty_gpt_entry[16]= {0};
1223 struct GPT_part_entry *part;
1224 char buf[512];
1225 unsigned long long curr_part_end;
1226 unsigned all_partitions, entry_size;
1227 unsigned part_nr;
1228
1229 *endofpart = 0;
1230
1231 BUILD_BUG_ON(sizeof(gpt) != 512);
1232 /* skip protective MBR */
1233 lseek(fd, 512, SEEK_SET);
1234 /* read GPT header */
1235 if (read(fd, &gpt, 512) != 512)
1236 return 0;
1237
1238 /* get the number of partition entries and the entry size */
1239 all_partitions = __le32_to_cpu(gpt.part_cnt);
1240 entry_size = __le32_to_cpu(gpt.part_size);
1241
1242 /* Check GPT signature*/
1243 if (gpt.magic != GPT_SIGNATURE_MAGIC)
1244 return -1;
1245
1246 /* sanity checks */
1247 if (all_partitions > 1024 ||
1248 entry_size > sizeof(buf))
1249 return -1;
1250
1251 part = (struct GPT_part_entry *)buf;
1252
1253 for (part_nr = 0; part_nr < all_partitions; part_nr++) {
1254 /* read partition entry */
1255 if (read(fd, buf, entry_size) != (ssize_t)entry_size)
1256 return 0;
1257
1258 /* is this valid partition? */
1259 if (memcmp(part->type_guid, empty_gpt_entry, 16) != 0) {
1260 /* check the last lba for the current partition */
1261 curr_part_end = __le64_to_cpu(part->ending_lba);
1262 if (curr_part_end > *endofpart)
1263 *endofpart = curr_part_end;
1264 }
1265
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 */
1275 static int get_last_partition_end(int fd, unsigned long long *endofpart)
1276 {
1277 struct MBR boot_sect;
1278 struct MBR_part_record *part;
1279 unsigned long long curr_part_end;
1280 unsigned part_nr;
1281 int retval = 0;
1282
1283 *endofpart = 0;
1284
1285 BUILD_BUG_ON(sizeof(boot_sect) != 512);
1286 /* read MBR */
1287 lseek(fd, 0, 0);
1288 if (read(fd, &boot_sect, 512) != 512)
1289 goto abort;
1290
1291 /* check MBP signature */
1292 if (boot_sect.magic == MBR_SIGNATURE_MAGIC) {
1293 retval = 1;
1294 /* found the correct signature */
1295 part = boot_sect.parts;
1296
1297 for (part_nr = 0; part_nr < MBR_PARTITIONS; part_nr++) {
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
1319 int check_partitions(int fd, char *dname, unsigned long long freesize,
1320 unsigned long long size)
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 */
1332 pr_err("partition table exists on %s but will be lost or\n"
1333 " meaningless after creating array\n",
1334 dname);
1335 return 1;
1336 } else if (endofpart > freesize) {
1337 /* last partition overlaps metadata */
1338 pr_err("metadata will over-write last partition on %s.\n",
1339 dname);
1340 return 1;
1341 } else if (size && endofpart > size) {
1342 /* partitions will be truncated in new device */
1343 pr_err("array size is too small to cover all partitions on %s.\n",
1344 dname);
1345 return 1;
1346 }
1347 }
1348 return 0;
1349 }
1350
1351 int 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;
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;
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);
1399 if (n <= 0 || (unsigned)n >= sizeof(buf))
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 }
1411 closedir(dir);
1412 return -1;
1413 }
1414
1415 struct 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
1429 int 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
1447 int 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
1465 int is_container_member(struct mdstat_ent *mdstat, char *container)
1466 {
1467 if (mdstat->metadata_version == NULL ||
1468 strncmp(mdstat->metadata_version, "external:", 9) != 0 ||
1469 !metadata_container_matches(mdstat->metadata_version+9, container))
1470 return 0;
1471
1472 return 1;
1473 }
1474
1475 int is_subarray_active(char *subarray, char *container)
1476 {
1477 struct mdstat_ent *mdstat = mdstat_read(0, 0);
1478 struct mdstat_ent *ent;
1479
1480 for (ent = mdstat; ent; ent = ent->next)
1481 if (is_container_member(ent, container))
1482 if (strcmp(to_subarray(ent, container), subarray) == 0)
1483 break;
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
1492 * @st: empty supertype
1493 * @quiet: block reporting errors flag
1494 *
1495 * On success returns an fd to a container and fills in *st
1496 */
1497 int open_subarray(char *dev, char *subarray, struct supertype *st, int quiet)
1498 {
1499 struct mdinfo *mdi;
1500 struct mdinfo *info;
1501 int fd, err = 1;
1502 char *_devnm;
1503
1504 fd = open(dev, O_RDWR|O_EXCL);
1505 if (fd < 0) {
1506 if (!quiet)
1507 pr_err("Couldn't open %s, aborting\n",
1508 dev);
1509 return -1;
1510 }
1511
1512 _devnm = fd2devnm(fd);
1513 if (_devnm == NULL) {
1514 if (!quiet)
1515 pr_err("Failed to determine device number for %s\n",
1516 dev);
1517 goto close_fd;
1518 }
1519 strcpy(st->devnm, _devnm);
1520
1521 mdi = sysfs_read(fd, st->devnm, GET_VERSION|GET_LEVEL);
1522 if (!mdi) {
1523 if (!quiet)
1524 pr_err("Failed to read sysfs for %s\n",
1525 dev);
1526 goto close_fd;
1527 }
1528
1529 if (mdi->array.level != UnSet) {
1530 if (!quiet)
1531 pr_err("%s is not a container\n", dev);
1532 goto free_sysfs;
1533 }
1534
1535 st->ss = version_to_superswitch(mdi->text_version);
1536 if (!st->ss) {
1537 if (!quiet)
1538 pr_err("Operation not supported for %s metadata\n",
1539 mdi->text_version);
1540 goto free_sysfs;
1541 }
1542
1543 if (st->devnm[0] == 0) {
1544 if (!quiet)
1545 pr_err("Failed to allocate device name\n");
1546 goto free_sysfs;
1547 }
1548
1549 if (!st->ss->load_container) {
1550 if (!quiet)
1551 pr_err("%s is not a container\n", dev);
1552 goto free_sysfs;
1553 }
1554
1555 if (st->ss->load_container(st, fd, NULL)) {
1556 if (!quiet)
1557 pr_err("Failed to load metadata for %s\n",
1558 dev);
1559 goto free_sysfs;
1560 }
1561
1562 info = st->ss->container_content(st, subarray);
1563 if (!info) {
1564 if (!quiet)
1565 pr_err("Failed to find subarray-%s in %s\n",
1566 subarray, dev);
1567 goto free_super;
1568 }
1569 free(info);
1570
1571 err = 0;
1572
1573 free_super:
1574 if (err)
1575 st->ss->free_super(st);
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
1588 int 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) {
1595 if (info->disk.state & (1<<MD_DISK_SYNC))
1596 info->recovery_start = MaxSector;
1597 else
1598 info->recovery_start = 0;
1599 rv = sysfs_add_disk(sra, info, 0);
1600 if (! rv) {
1601 struct mdinfo *sd2;
1602 for (sd2 = sra->devs; sd2; sd2=sd2->next)
1603 if (sd2 == info)
1604 break;
1605 if (sd2 == NULL) {
1606 sd2 = xmalloc(sizeof(*sd2));
1607 *sd2 = *info;
1608 sd2->next = sra->devs;
1609 sra->devs = sd2;
1610 }
1611 }
1612 } else
1613 #endif
1614 rv = ioctl(mdfd, ADD_NEW_DISK, &info->disk);
1615 return rv;
1616 }
1617
1618 int 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
1633 int 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
1658 unsigned 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
1673 int mdmon_pid(char *devnm)
1674 {
1675 char path[100];
1676 char pid[10];
1677 int fd;
1678 int n;
1679
1680 sprintf(path, "%s/%s.pid", MDMON_DIR, devnm);
1681
1682 fd = open(path, O_RDONLY | O_NOATIME, 0);
1683
1684 if (fd < 0)
1685 return -1;
1686 n = read(fd, pid, 9);
1687 close(fd);
1688 if (n <= 0)
1689 return -1;
1690 return atoi(pid);
1691 }
1692
1693 int mdmon_running(char *devnm)
1694 {
1695 int pid = mdmon_pid(devnm);
1696 if (pid <= 0)
1697 return 0;
1698 if (kill(pid, 0) == 0)
1699 return 1;
1700 return 0;
1701 }
1702
1703 int start_mdmon(char *devnm)
1704 {
1705 int i, skipped;
1706 int len;
1707 pid_t pid;
1708 int status;
1709 char pathbuf[1024];
1710 char *paths[4] = {
1711 pathbuf,
1712 BINDIR "/mdmon",
1713 "./mdmon",
1714 NULL
1715 };
1716
1717 if (check_env("MDADM_NO_MDMON"))
1718 return 0;
1719
1720 len = readlink("/proc/self/exe", pathbuf, sizeof(pathbuf)-1);
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
1733 /* First try to run systemctl */
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);
1759 case -1: pr_err("cannot run mdmon. Array remains readonly\n");
1760 return -1;
1761 default: /* parent - good */
1762 pid = wait(&status);
1763 if (pid >= 0 && status == 0)
1764 return 0;
1765 }
1766
1767 /* That failed, try running mdmon directly */
1768 switch(fork()) {
1769 case 0:
1770 /* FIXME yuk. CLOSE_EXEC?? */
1771 skipped = 0;
1772 for (i = 3; skipped < 20; i++)
1773 if (close(i) < 0)
1774 skipped++;
1775 else
1776 skipped = 0;
1777
1778 for (i = 0; paths[i]; i++)
1779 if (paths[i][0]) {
1780 execl(paths[i], paths[i],
1781 devnm, NULL);
1782 }
1783 exit(1);
1784 case -1: pr_err("cannot run mdmon. Array remains readonly\n");
1785 return -1;
1786 default: /* parent - good */
1787 pid = wait(&status);
1788 if (pid < 0 || status != 0) {
1789 pr_err("failed to launch mdmon. Array remains readonly\n");
1790 return -1;
1791 }
1792 }
1793 return 0;
1794 }
1795
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
1807 #ifndef MDASSEMBLE
1808 int flush_metadata_updates(struct supertype *st)
1809 {
1810 int sfd;
1811 if (!st->updates) {
1812 st->update_tail = NULL;
1813 return -1;
1814 }
1815
1816 sfd = connect_monitor(st->container_devnm);
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
1836 void append_metadata_update(struct supertype *st, void *buf, int len)
1837 {
1838
1839 struct metadata_update *mu = xmalloc(sizeof(*mu));
1840
1841 mu->buf = buf;
1842 mu->len = len;
1843 mu->space = NULL;
1844 mu->space_list = NULL;
1845 mu->next = NULL;
1846 *st->update_tail = mu;
1847 st->update_tail = &mu->next;
1848 }
1849 #endif /* MDASSEMBLE */
1850
1851 #ifdef __TINYC__
1852 /* tinyc doesn't optimize this check in ioctl.h out ... */
1853 unsigned int __invalid_size_argument_for_IOC = 0;
1854 #endif
1855
1856 int experimental(void)
1857 {
1858 if (check_env("MDADM_EXPERIMENTAL"))
1859 return 1;
1860 else {
1861 pr_err("To use this feature MDADM_EXPERIMENTAL environment variable has to be defined.\n");
1862 return 0;
1863 }
1864 }
1865
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 */
1871 struct 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) {
1902 struct dev_policy *pol = devid_policy(dev);
1903 if (spare_group)
1904 pol_add(&pol, pol_domain,
1905 spare_group, NULL);
1906 if (domain_test(domlist, pol, metadata) != 1)
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 }
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 */
1933 int 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 }
1947
1948 /* Make sure we can open as many devices as needed */
1949 void 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 }
1961
1962 int in_initrd(void)
1963 {
1964 /* This is based on similar function in systemd. */
1965 struct statfs s;
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 */
1969 return statfs("/", &s) >= 0 &&
1970 ((unsigned long)s.f_type == TMPFS_MAGIC ||
1971 ((unsigned long)s.f_type & 0xFFFFFFFFUL) ==
1972 ((unsigned long)RAMFS_MAGIC & 0xFFFFFFFFUL));
1973 }
1974
1975 void 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 }
1988
1989 int 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;
2030 name_err:
2031 finalize(handle);
2032 out:
2033 dlclose(lib_handle);
2034 return rv;
2035 }