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