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