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