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