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