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