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