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