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