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