Safeguard against writing to an active device of another node
[thirdparty/mdadm.git] / util.c
CommitLineData
64c4757e 1/*
9a9dab36 2 * mdadm - manage Linux "md" devices aka RAID arrays.
64c4757e 3 *
6f02172d 4 * Copyright (C) 2001-2013 Neil Brown <neilb@suse.de>
64c4757e
NB
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
e736b623 22 * Email: <neilb@suse.de>
64c4757e
NB
23 */
24
9a9dab36 25#include "mdadm.h"
64c4757e 26#include "md_p.h"
d15a1f72 27#include <sys/poll.h>
edd8d13c 28#include <sys/socket.h>
64c4757e 29#include <sys/utsname.h>
9fe32043 30#include <sys/wait.h>
edd8d13c 31#include <sys/un.h>
a7dec3fd 32#include <sys/resource.h>
a9c15847
N
33#include <sys/vfs.h>
34#include <linux/magic.h>
98c6faba 35#include <ctype.h>
a322f70c 36#include <dirent.h>
a931db9e 37#include <signal.h>
7716570e
GJ
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
0a816ef9
NB
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 */
56struct blkpg_ioctl_arg {
5d500228
N
57 int op;
58 int flags;
59 int datalen;
60 void *data;
0a816ef9
NB
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 */
72struct 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};
64c4757e 80
0f22b998 81#include "part.h"
056b331e
N
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
d15a1f72
GJ
92static struct dlm_hooks *dlm_hooks = NULL;
93static int is_dlm_hooks_ready = 0;
94struct dlm_lock_resource *dlm_lock_res = NULL;
95static int ast_called = 0;
96
97struct dlm_lock_resource {
98 dlm_lshandle_t *ls;
99 struct dlm_lksb lksb;
100};
101
102int 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 */
112static 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
133static void dlm_ast(void *arg)
134{
135 ast_called = 1;
136}
137
138/* Create the lockspace, take bitmapXXX locks on all the bitmaps. */
139int 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
177out:
178 return ret;
179}
180
181int 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
213out:
214 return ret;
215}
216
64c4757e
NB
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 */
223int parse_uuid(char *str, int uuid[4])
224{
aba69144
NB
225 int hit = 0; /* number of Hex digIT */
226 int i;
227 char c;
ca3b6696
N
228 for (i = 0; i < 4; i++)
229 uuid[i] = 0;
aba69144 230
ca3b6696 231 while ((c = *str++) != 0) {
aba69144 232 int n;
ca3b6696 233 if (c >= '0' && c <= '9')
aba69144 234 n = c-'0';
ca3b6696 235 else if (c >= 'a' && c <= 'f')
aba69144 236 n = 10 + c - 'a';
ca3b6696 237 else if (c >= 'A' && c <= 'F')
aba69144
NB
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++;
82b27616 248 }
aba69144
NB
249 if (hit == 32)
250 return 1;
251 return 0;
64c4757e
NB
252}
253
64c4757e
NB
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
264int md_get_version(int fd)
265{
5d500228
N
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);
64c4757e 280 return -1;
64c4757e
NB
281}
282
64c4757e
NB
283int get_linux_version()
284{
285 struct utsname name;
98c6faba 286 char *cp;
f161d047 287 int a = 0, b = 0,c = 0;
64c4757e
NB
288 if (uname(&name) <0)
289 return -1;
290
98c6faba
NB
291 cp = name.release;
292 a = strtoul(cp, &cp, 10);
f161d047
N
293 if (*cp == '.')
294 b = strtoul(cp+1, &cp, 10);
295 if (*cp == '.')
296 c = strtoul(cp+1, &cp, 10);
98c6faba 297
682c7051 298 return (a*1000000)+(b*1000)+c;
64c4757e
NB
299}
300
71204a50 301#ifndef MDASSEMBLE
bc77ed53
DW
302int 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
51d4261c 327unsigned long long parse_size(char *size)
84e11361
N
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)
822e393a 333 * INVALID_SECTORS returned on error.
84e11361
N
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;
72ca9bcf
N
352 case 's': /* sectors */
353 c++;
354 break;
84e11361 355 }
51d4261c 356 } else
822e393a 357 s = INVALID_SECTORS;
84e11361 358 if (*c)
822e393a 359 s = INVALID_SECTORS;
84e11361
N
360 return s;
361}
362
4a06e2c2
N
363int 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
383int parse_layout_faulty(char *layout)
384{
385 /* Parse the layout string for 'faulty' */
386 int ln = strcspn(layout, "0123456789");
503975b9 387 char *m = xstrdup(layout);
4a06e2c2
N
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}
79868890
N
396
397long 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}
eb3929a4 407#endif
4a06e2c2 408
4de90913
GJ
409int 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
0430ed48
NB
419void 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);
ca3b6696 433 for (p.pno = 0; p.pno < 16; p.pno++)
0430ed48
NB
434 ioctl(fd, BLKPG, &a);
435#endif
436}
437
691c6ee1
N
438int 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;
357ac106 455 if (errno == ENXIO || errno == ENOTTY)
691c6ee1
N
456 /* not a partition */
457 return 0;
458
459 return 1;
460}
461
bfd76b93
CA
462int 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}
691c6ee1 475
de5a472e 476int enough(int level, int raid_disks, int layout, int clean, char *avail)
64c4757e 477{
265e0f17 478 int copies, first;
de5a472e
N
479 int i;
480 int avail_disks = 0;
481
482 for (i = 0; i < raid_disks; i++)
483 avail_disks += !!avail[i];
484
64c4757e 485 switch (level) {
265e0f17
NB
486 case 10:
487 /* This is the tricky one - we need to check
488 * which actual disks are present.
489 */
702b557b 490 copies = (layout&255)* ((layout>>8) & 255);
ca3b6696 491 first = 0;
265e0f17
NB
492 do {
493 /* there must be one of the 'copies' form 'first' */
494 int n = copies;
ca3b6696 495 int cnt = 0;
b3ec716d 496 int this = first;
265e0f17 497 while (n--) {
b3ec716d 498 if (avail[this])
265e0f17 499 cnt++;
b3ec716d 500 this = (this+1) % raid_disks;
265e0f17
NB
501 }
502 if (cnt == 0)
503 return 0;
b3ec716d 504 first = (first+(layout&255)) % raid_disks;
265e0f17
NB
505 } while (first != 0);
506 return 1;
e5329c37 507
df0d4ea0 508 case LEVEL_MULTIPATH:
e0d19036 509 return avail_disks>= 1;
df0d4ea0 510 case LEVEL_LINEAR:
64c4757e
NB
511 case 0:
512 return avail_disks == raid_disks;
513 case 1:
514 return avail_disks >= 1;
515 case 4:
330d6900
N
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 */
64c4757e 523 case 5:
583315d9
NB
524 if (clean)
525 return avail_disks >= raid_disks-1;
526 else
527 return avail_disks >= raid_disks;
98c6faba 528 case 6:
583315d9
NB
529 if (clean)
530 return avail_disks >= raid_disks-2;
531 else
532 return avail_disks >= raid_disks;
64c4757e
NB
533 default:
534 return 0;
535 }
536}
537
8453e704
N
538int enough_fd(int fd)
539{
540 struct mdu_array_info_s array;
541 struct mdu_disk_info_s disk;
aabe020d 542 int i, rv;
8453e704
N
543 char *avail;
544
545 if (ioctl(fd, GET_ARRAY_INFO, &array) != 0 ||
546 array.raid_disks <= 0)
547 return 0;
503975b9 548 avail = xcalloc(array.raid_disks, 1);
ca3b6696 549 for (i = 0; i < MAX_DISKS && array.nr_disks > 0; i++) {
8453e704
N
550 disk.number = i;
551 if (ioctl(fd, GET_DISK_INFO, &disk) != 0)
552 continue;
9e6d9291
N
553 if (disk.major == 0 && disk.minor == 0)
554 continue;
555 array.nr_disks--;
556
8453e704
N
557 if (! (disk.state & (1<<MD_DISK_SYNC)))
558 continue;
559 if (disk.raid_disk < 0 || disk.raid_disk >= array.raid_disks)
560 continue;
8453e704
N
561 avail[disk.raid_disk] = 1;
562 }
563 /* This is used on an active array, so assume it is clean */
aabe020d 564 rv = enough(array.level, array.raid_disks, array.layout,
de5a472e 565 1, avail);
aabe020d
JS
566 free(avail);
567 return rv;
8453e704
N
568}
569
22e263f6
AC
570const int uuid_zero[4] = { 0, 0, 0, 0 };
571
f277ce36 572int same_uuid(int a[4], int b[4], int swapuuid)
64c4757e 573{
f277ce36
NB
574 if (swapuuid) {
575 /* parse uuids are hostendian.
576 * uuid's from some superblocks are big-ending
aba69144 577 * if there is a difference, we need to swap..
f277ce36
NB
578 */
579 unsigned char *ac = (unsigned char *)a;
580 unsigned char *bc = (unsigned char *)b;
581 int i;
ca3b6696 582 for (i = 0; i < 16; i += 4) {
f277ce36
NB
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 }
64c4757e 598}
ca3b6696 599
350f29f9
NB
600void 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;
ca3b6696 610 for (i = 0; i < 16; i += 4) {
350f29f9
NB
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}
64c4757e 619
aae5a112 620char *__fname_from_uuid(int id[4], int swap, char *buf, char sep)
d7288ddc 621{
9968e376 622 int i, j;
d7288ddc
N
623 char uuid[16];
624 char *c = buf;
625 strcpy(c, "UUID-");
626 c += strlen(c);
aae5a112 627 copy_uuid(uuid, id, swap);
9968e376 628 for (i = 0; i < 4; i++) {
9968e376 629 if (i)
ff54de6e 630 *c++ = sep;
9968e376
DW
631 for (j = 3; j >= 0; j--) {
632 sprintf(c,"%02x", (unsigned char) uuid[j+4*i]);
633 c+= 2;
634 }
d7288ddc
N
635 }
636 return buf;
aae5a112
DW
637
638}
639
640char *fname_from_uuid(struct supertype *st, struct mdinfo *info, char *buf, char sep)
641{
86983cce
N
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);
d7288ddc
N
648}
649
435d4ebb 650#ifndef MDASSEMBLE
682c7051
NB
651int 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;
2538ba2a
N
664 unsigned long long size;
665 int bsize;
682c7051
NB
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;
2538ba2a 676 size <<= bsize;
e7b84f9d 677 pr_err("%s appears to contain an ext2fs file system\n",
682c7051 678 name);
2538ba2a 679 cont_err("size=%lluK mtime=%s", size, ctime(&mtime));
682c7051
NB
680 return 1;
681}
682
683int 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];
2538ba2a 692 unsigned long long size;
682c7051
NB
693 if (lseek(fd, 64*1024, 0) != 64*1024)
694 return 0;
695 if (read(fd, sb, 1024) != 1024)
696 return 0;
ca3b6696
N
697 if (strncmp((char*)sb+52, "ReIsErFs",8) != 0 &&
698 strncmp((char*)sb+52, "ReIsEr2Fs",9) != 0)
682c7051 699 return 0;
e7b84f9d 700 pr_err("%s appears to contain a reiserfs file system\n",name);
682c7051 701 size = sb[0]|(sb[1]|(sb[2]|sb[3]<<8)<<8)<<8;
2538ba2a 702 cont_err("size = %lluK\n", size*4);
aba69144 703
682c7051
NB
704 return 1;
705}
706
707int check_raid(int fd, char *name)
708{
4b1ac34b 709 struct mdinfo info;
682c7051 710 time_t crtime;
d078d77c 711 char *level;
82d9eba6 712 struct supertype *st = guess_super(fd);
f9ce90ba 713
cb8f6859
N
714 if (!st)
715 return 0;
3da92f27 716 st->ss->load_super(st, fd, name);
82d9eba6 717 /* Looks like a raid array .. */
e7b84f9d 718 pr_err("%s appears to be part of a raid array:\n",
82d9eba6 719 name);
a5d85af7 720 st->ss->getinfo_super(st, &info, NULL);
3da92f27 721 st->ss->free_super(st);
82d9eba6 722 crtime = info.array.ctime;
d078d77c
NB
723 level = map_num(pers, info.array.level);
724 if (!level) level = "-unknown-";
d33f1518
N
725 cont_err("level=%s devices=%d ctime=%s",
726 level, info.array.raid_disks, ctime(&crtime));
82d9eba6 727 return 1;
682c7051
NB
728}
729
682c7051
NB
730int ask(char *mesg)
731{
732 char *add = "";
733 int i;
ca3b6696 734 for (i = 0; i < 5; i++) {
682c7051
NB
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 }
e7b84f9d 746 pr_err("assuming 'no'\n");
682c7051
NB
747 return 0;
748}
435d4ebb 749#endif /* MDASSEMBLE */
682c7051 750
8d80900b 751int is_standard(char *dev, int *nump)
e5329c37
NB
752{
753 /* tests if dev is a "standard" md dev name.
754 * i.e if the last component is "/dNN" or "/mdNN",
aba69144 755 * where NN is a string of digits
598f0d58
NB
756 * Returns 1 if a partitionable standard,
757 * -1 if non-partitonable,
758 * 0 if not a standard name.
e5329c37 759 */
8d80900b 760 char *d = strrchr(dev, '/');
ca3b6696 761 int type = 0;
8d80900b
NB
762 int num;
763 if (!d)
e5329c37 764 return 0;
ca3b6696
N
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 */
e5329c37
NB
773 else
774 return 0;
8d80900b 775 if (!*d)
e5329c37 776 return 0;
8d80900b
NB
777 num = atoi(d);
778 while (isdigit(*d))
779 d++;
780 if (*d)
e5329c37 781 return 0;
8d80900b
NB
782 if (nump) *nump = num;
783
784 return type;
e5329c37
NB
785}
786
4b1ac34b 787unsigned long calc_csum(void *super, int bytes)
82b27616 788{
56eb10c0 789 unsigned long long newcsum = 0;
82b27616 790 int i;
4b1ac34b
NB
791 unsigned int csum;
792 unsigned int *superc = (unsigned int*) super;
82b27616 793
ca3b6696
N
794 for(i = 0; i < bytes/4; i++)
795 newcsum += superc[i];
82b27616 796 csum = (newcsum& 0xffffffff) + (newcsum>>32);
570c0542 797#ifdef __alpha__
aba69144 798/* The in-kernel checksum calculation is always 16bit on
570c0542 799 * the alpha, though it is 32 bit on i386...
ca3b6696 800 * I wonder what it is elsewhere... (it uses an API in
570c0542
NB
801 * a way that it shouldn't).
802 */
803 csum = (csum & 0xffff) + (csum >> 16);
804 csum = (csum & 0xffff) + (csum >> 16);
805#endif
82b27616
NB
806 return csum;
807}
cd29a5c8 808
435d4ebb 809#ifndef MDASSEMBLE
56eb10c0 810char *human_size(long long bytes)
cd29a5c8
NB
811{
812 static char buf[30];
d5d3721e
NB
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.
01619b48 820 * Terabytes are not yet handled.
d5d3721e 821 */
cd29a5c8 822
56eb10c0 823 if (bytes < 5000*1024)
ca3b6696 824 buf[0] = 0;
d5d3721e 825 else if (bytes < 2*1024LL*1024LL*1024LL) {
93d3bd3b 826 long cMiB = (bytes * 200LL / (1LL<<20) + 1) / 2;
d5d3721e 827 long cMB = (bytes / ( 1000000LL / 200LL ) +1) /2;
8f23b0b3 828 snprintf(buf, sizeof(buf), " (%ld.%02ld MiB %ld.%02ld MB)",
d5d3721e
NB
829 cMiB/100 , cMiB % 100,
830 cMB/100, cMB % 100);
831 } else {
93d3bd3b 832 long cGiB = (bytes * 200LL / (1LL<<30) +1) / 2;
d5d3721e 833 long cGB = (bytes / (1000000000LL/200LL ) +1) /2;
8f23b0b3 834 snprintf(buf, sizeof(buf), " (%ld.%02ld GiB %ld.%02ld GB)",
d5d3721e
NB
835 cGiB/100 , cGiB % 100,
836 cGB/100, cGB % 100);
837 }
cd29a5c8
NB
838 return buf;
839}
e0d19036 840
f0ec6710 841char *human_size_brief(long long bytes, int prefix)
e0d19036
NB
842{
843 static char buf[30];
e0d19036 844
570abc6f
MN
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.
f0ec6710
MN
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.
570abc6f
MN
855 */
856
e0d19036 857 if (bytes < 5000*1024)
570abc6f 858 buf[0] = 0;
f0ec6710
MN
859 else if (prefix == IEC) {
860 if (bytes < 2*1024LL*1024LL*1024LL) {
93d3bd3b 861 long cMiB = (bytes * 200LL / (1LL<<20) +1) /2;
f0ec6710
MN
862 snprintf(buf, sizeof(buf), "%ld.%02ldMiB",
863 cMiB/100 , cMiB % 100);
864 } else {
93d3bd3b 865 long cGiB = (bytes * 200LL / (1LL<<30) +1) /2;
f0ec6710
MN
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 }
570abc6f 880 }
f0ec6710
MN
881 else
882 buf[0] = 0;
570abc6f 883
e0d19036
NB
884 return buf;
885}
e4965ef8
N
886
887void 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}
435d4ebb 903#endif
e0d19036 904
5f8097be
NB
905unsigned long long calc_array_size(int level, int raid_disks, int layout,
906 int chunksize, unsigned long long devsize)
577e8448 907{
e03640bd
CA
908 if (level == 1)
909 return devsize;
577e8448
AK
910 devsize &= ~(unsigned long long)((chunksize>>9)-1);
911 return get_data_disks(level, layout, raid_disks) * devsize;
912}
913
914int get_data_disks(int level, int layout, int raid_disks)
5f8097be
NB
915{
916 int data_disks = 0;
917 switch (level) {
ca3b6696
N
918 case 0: data_disks = raid_disks;
919 break;
920 case 1: data_disks = 1;
921 break;
5f8097be 922 case 4:
ca3b6696
N
923 case 5: data_disks = raid_disks - 1;
924 break;
925 case 6: data_disks = raid_disks - 2;
926 break;
5f8097be
NB
927 case 10: data_disks = raid_disks / (layout & 255) / ((layout>>8)&255);
928 break;
929 }
577e8448
AK
930
931 return data_disks;
5f8097be
NB
932}
933
4dd2df09
N
934int 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
5a23a06e 970#if !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO)
4dd2df09 971char *get_md_name(char *devnm)
e0d19036
NB
972{
973 /* find /dev/md%d or /dev/md/%d or make a device /dev/.tmp.md%d */
98c6faba 974 /* if dev < 0, want /dev/md/d%d or find mdp in /proc/devices ... */
4dd2df09 975
e0d19036
NB
976 static char devname[50];
977 struct stat stb;
4dd2df09 978 dev_t rdev = devnm2devid(devnm);
dd0781e5 979 char *dn;
98c6faba 980
4dd2df09
N
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);
98c6faba
NB
986 if (stat(devname, &stb) == 0
987 && (S_IFMT&stb.st_mode) == S_IFBLK
988 && (stb.st_rdev == rdev))
989 return devname;
990 }
4dd2df09
N
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
16c6fa80 1003 dn = map_dev(major(rdev), minor(rdev), 0);
dd0781e5
NB
1004 if (dn)
1005 return dn;
4dd2df09 1006 snprintf(devname, sizeof(devname), "/dev/.tmp.%s", devnm);
e0d19036 1007 if (mknod(devname, S_IFBLK | 0600, rdev) == -1)
dd0781e5
NB
1008 if (errno != EEXIST)
1009 return NULL;
e0d19036
NB
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
1019void put_md_name(char *name)
1020{
ca3b6696 1021 if (strncmp(name, "/dev/.tmp.md", 12) == 0)
e0d19036
NB
1022 unlink(name);
1023}
435d4ebb 1024#endif /* !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO) */
f9ce90ba 1025
cc742d38
N
1026int 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
8b0dabea
NB
1035int 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 */
8b0dabea
NB
1040 int fd = -1;
1041 char devname[32];
e81cdd9f 1042 int major;
8b0dabea 1043 int minor;
e81cdd9f
NB
1044
1045 if (!dev) return -1;
6df6a774 1046 flags |= O_DIRECT;
e81cdd9f 1047
cc742d38 1048 if (get_maj_min(dev, &major, &minor)) {
9dc7d357
N
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);
6df6a774
N
1054 }
1055 if (fd < 0) {
9dc7d357 1056 /* Try /tmp as /dev appear to be read-only */
6df6a774
N
1057 snprintf(devname, sizeof(devname), "/tmp/.tmp.md.%d:%d:%d",
1058 (int)getpid(), major, minor);
ca3b6696 1059 if (mknod(devname, S_IFBLK|0600, makedev(major, minor)) == 0) {
6df6a774
N
1060 fd = open(devname, flags);
1061 unlink(devname);
1062 }
8b0dabea
NB
1063 }
1064 } else
6df6a774 1065 fd = open(dev, flags);
8b0dabea
NB
1066 return fd;
1067}
f9ce90ba 1068
4dd2df09 1069int open_dev_flags(char *devnm, int flags)
e8a70c89 1070{
4dd2df09 1071 int devid;
e8a70c89
N
1072 char buf[20];
1073
4dd2df09
N
1074 devid = devnm2devid(devnm);
1075 sprintf(buf, "%d:%d", major(devid), minor(devid));
d998b738
N
1076 return dev_open(buf, flags);
1077}
1078
4dd2df09 1079int open_dev(char *devnm)
d998b738 1080{
4dd2df09 1081 return open_dev_flags(devnm, O_RDONLY);
e8a70c89
N
1082}
1083
4dd2df09 1084int open_dev_excl(char *devnm)
a931db9e
NB
1085{
1086 char buf[20];
1087 int i;
7187750e 1088 int flags = O_RDWR;
4dd2df09 1089 int devid = devnm2devid(devnm);
399e0b97 1090 long delay = 1000;
a931db9e 1091
4dd2df09 1092 sprintf(buf, "%d:%d", major(devid), minor(devid));
ca3b6696 1093 for (i = 0 ; i < 25 ; i++) {
7187750e 1094 int fd = dev_open(buf, flags|O_EXCL);
a931db9e
NB
1095 if (fd >= 0)
1096 return fd;
7187750e
N
1097 if (errno == EACCES && flags == O_RDWR) {
1098 flags = O_RDONLY;
1099 continue;
1100 }
a931db9e
NB
1101 if (errno != EBUSY)
1102 return fd;
399e0b97
N
1103 usleep(delay);
1104 if (delay < 200000)
1105 delay *= 2;
a931db9e
NB
1106 }
1107 return -1;
1108}
1109
9008ed1c
N
1110int 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
a7c6e3fb 1124void wait_for(char *dev, int fd)
a714580e
N
1125{
1126 int i;
a7c6e3fb 1127 struct stat stb_want;
399e0b97 1128 long delay = 1000;
a7c6e3fb
N
1129
1130 if (fstat(fd, &stb_want) != 0 ||
1131 (stb_want.st_mode & S_IFMT) != S_IFBLK)
1132 return;
a714580e 1133
ca3b6696 1134 for (i = 0 ; i < 25 ; i++) {
a714580e 1135 struct stat stb;
a7c6e3fb
N
1136 if (stat(dev, &stb) == 0 &&
1137 (stb.st_mode & S_IFMT) == S_IFBLK &&
1138 (stb.st_rdev == stb_want.st_rdev))
a714580e 1139 return;
399e0b97
N
1140 usleep(delay);
1141 if (delay < 200000)
1142 delay *= 2;
a714580e 1143 }
436305c6 1144 if (i == 25)
1ade5cc1 1145 dprintf("timeout waiting for %s\n", dev);
a714580e
N
1146}
1147
0f22b998
N
1148struct superswitch *superlist[] =
1149{
1150 &super0, &super1,
1151 &super_ddf, &super_imsm,
0592faeb 1152 &mbr, &gpt,
0f22b998 1153 NULL };
f9ce90ba 1154
ea24acd0 1155#if !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO)
f7dd881f 1156
4725bc31 1157struct supertype *super_by_fd(int fd, char **subarrayp)
f9ce90ba 1158{
1686dc25
NB
1159 mdu_array_info_t array;
1160 int vers;
1161 int minor;
1162 struct supertype *st = NULL;
7e0f6979 1163 struct mdinfo *sra;
142cb9e1 1164 char *verstr;
1686dc25
NB
1165 char version[20];
1166 int i;
f7e7067b 1167 char *subarray = NULL;
4dd2df09 1168 char container[32] = "";
1686dc25 1169
4dd2df09 1170 sra = sysfs_read(fd, NULL, GET_VERSION);
1686dc25
NB
1171
1172 if (sra) {
7e0f6979
NB
1173 vers = sra->array.major_version;
1174 minor = sra->array.minor_version;
142cb9e1 1175 verstr = sra->text_version;
1686dc25
NB
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;
142cb9e1 1181 verstr = "";
6fbba4c9 1182 }
82d9eba6 1183
1686dc25
NB
1184 if (vers != -1) {
1185 sprintf(version, "%d.%d", vers, minor);
1186 verstr = version;
6fbba4c9 1187 }
3c558363 1188 if (minor == -2 && is_subarray(verstr)) {
f7e7067b 1189 char *dev = verstr+1;
5f7e44b2 1190
f7e7067b 1191 subarray = strchr(dev, '/');
92d49ecf 1192 if (subarray) {
f7e7067b 1193 *subarray++ = '\0';
503975b9 1194 subarray = xstrdup(subarray);
92d49ecf 1195 }
4dd2df09 1196 strcpy(container, dev);
f7e7067b
NB
1197 if (sra)
1198 sysfs_free(sra);
5f7e44b2 1199 sra = sysfs_read(-1, container, GET_VERSION);
603f24a0
N
1200 if (sra && sra->text_version[0])
1201 verstr = sra->text_version;
1202 else
1203 verstr = "-no-metadata-";
f7e7067b
NB
1204 }
1205
1206 for (i = 0; st == NULL && superlist[i] ; i++)
1207 st = superlist[i]->match_metadata_desc(verstr);
1686dc25
NB
1208
1209 if (sra)
1210 sysfs_free(sra);
f7e7067b 1211 if (st) {
3b0896f8 1212 st->sb = NULL;
1f49fb3a
N
1213 if (subarrayp)
1214 *subarrayp = subarray;
4dd2df09
N
1215 strcpy(st->container_devnm, container);
1216 strcpy(st->devnm, fd2devnm(fd));
4725bc31
N
1217 } else
1218 free(subarray);
5f7e44b2 1219
82d9eba6 1220 return st;
f9ce90ba 1221}
ea24acd0
NB
1222#endif /* !defined(MDASSEMBLE) || defined(MDASSEMBLE) && defined(MDASSEMBLE_AUTO) */
1223
0f0749ad 1224int dev_size_from_id(dev_t id, unsigned long long *size)
52d5d101
AC
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}
f9ce90ba 1240
159c3a1a 1241struct supertype *dup_super(struct supertype *orig)
3da92f27 1242{
159c3a1a 1243 struct supertype *st;
1686dc25 1244
d2ca6449
NB
1245 if (!orig)
1246 return orig;
503975b9 1247 st = xcalloc(1, sizeof(*st));
159c3a1a
NB
1248 st->ss = orig->ss;
1249 st->max_devs = orig->max_devs;
1250 st->minor_version = orig->minor_version;
cb8f6859 1251 st->ignore_hw_compat = orig->ignore_hw_compat;
23bf42cc 1252 st->data_offset = orig->data_offset;
159c3a1a
NB
1253 st->sb = NULL;
1254 st->info = NULL;
1255 return st;
3da92f27
NB
1256}
1257
54887ad8 1258struct supertype *guess_super_type(int fd, enum guess_types guess_type)
f9ce90ba
NB
1259{
1260 /* try each load_super to find the best match,
1261 * and return the best superswitch
1262 */
82d9eba6
NB
1263 struct superswitch *ss;
1264 struct supertype *st;
f21e18ca 1265 time_t besttime = 0;
570c0542 1266 int bestsuper = -1;
f9ce90ba
NB
1267 int i;
1268
503975b9 1269 st = xcalloc(1, sizeof(*st));
4dd2df09 1270 st->container_devnm[0] = 0;
d1d599ea 1271
ca3b6696 1272 for (i = 0 ; superlist[i]; i++) {
f9ce90ba
NB
1273 int rv;
1274 ss = superlist[i];
54887ad8
N
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;
ef609477 1279 memset(st, 0, sizeof(*st));
df3346e6 1280 st->ignore_hw_compat = 1;
3da92f27 1281 rv = ss->load_super(st, fd, NULL);
570c0542
NB
1282 if (rv == 0) {
1283 struct mdinfo info;
a5d85af7 1284 st->ss->getinfo_super(st, &info, NULL);
570c0542
NB
1285 if (bestsuper == -1 ||
1286 besttime < info.array.ctime) {
1287 bestsuper = i;
1288 besttime = info.array.ctime;
570c0542 1289 }
3da92f27 1290 ss->free_super(st);
570c0542
NB
1291 }
1292 }
1293 if (bestsuper != -1) {
1294 int rv;
ef609477 1295 memset(st, 0, sizeof(*st));
df3346e6 1296 st->ignore_hw_compat = 1;
3da92f27 1297 rv = superlist[bestsuper]->load_super(st, fd, NULL);
f9ce90ba 1298 if (rv == 0) {
5e747af2 1299 superlist[bestsuper]->free_super(st);
82d9eba6 1300 return st;
f9ce90ba
NB
1301 }
1302 }
570c0542 1303 free(st);
f9ce90ba
NB
1304 return NULL;
1305}
fe6729fa 1306
beae1dfe
NB
1307/* Return size of device in bytes */
1308int get_dev_size(int fd, char *dname, unsigned long long *sizep)
1309{
1310 unsigned long long ldsize;
c2c9bb6f
NB
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
beae1dfe
NB
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)
e7b84f9d 1326 pr_err("Cannot get size of %s: %s\b",
beae1dfe
NB
1327 dname, strerror(errno));
1328 return 0;
1329 }
1330 }
1331 *sizep = ldsize;
1332 return 1;
1333}
8fac0577 1334
3a371610
N
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 */
1338int 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}
034b203a
TM
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 */
1355static int get_gpt_last_partition_end(int fd, unsigned long long *endofpart)
1356{
056b331e 1357 struct GPT gpt;
034b203a 1358 unsigned char empty_gpt_entry[16]= {0};
db7fdfe4
JS
1359 struct GPT_part_entry *part;
1360 char buf[512];
034b203a
TM
1361 unsigned long long curr_part_end;
1362 unsigned all_partitions, entry_size;
f21e18ca 1363 unsigned part_nr;
034b203a
TM
1364
1365 *endofpart = 0;
1366
056b331e 1367 BUILD_BUG_ON(sizeof(gpt) != 512);
73e658d8 1368 /* skip protective MBR */
034b203a 1369 lseek(fd, 512, SEEK_SET);
73e658d8 1370 /* read GPT header */
056b331e 1371 if (read(fd, &gpt, 512) != 512)
034b203a
TM
1372 return 0;
1373
1374 /* get the number of partition entries and the entry size */
056b331e
N
1375 all_partitions = __le32_to_cpu(gpt.part_cnt);
1376 entry_size = __le32_to_cpu(gpt.part_size);
034b203a
TM
1377
1378 /* Check GPT signature*/
056b331e 1379 if (gpt.magic != GPT_SIGNATURE_MAGIC)
034b203a
TM
1380 return -1;
1381
1382 /* sanity checks */
1383 if (all_partitions > 1024 ||
db7fdfe4 1384 entry_size > sizeof(buf))
034b203a
TM
1385 return -1;
1386
db7fdfe4
JS
1387 part = (struct GPT_part_entry *)buf;
1388
ca3b6696 1389 for (part_nr = 0; part_nr < all_partitions; part_nr++) {
73e658d8 1390 /* read partition entry */
db7fdfe4 1391 if (read(fd, buf, entry_size) != (ssize_t)entry_size)
73e658d8
LB
1392 return 0;
1393
034b203a 1394 /* is this valid partition? */
db7fdfe4 1395 if (memcmp(part->type_guid, empty_gpt_entry, 16) != 0) {
034b203a 1396 /* check the last lba for the current partition */
db7fdfe4 1397 curr_part_end = __le64_to_cpu(part->ending_lba);
034b203a
TM
1398 if (curr_part_end > *endofpart)
1399 *endofpart = curr_part_end;
1400 }
1401
034b203a
TM
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 */
1411static int get_last_partition_end(int fd, unsigned long long *endofpart)
1412{
056b331e 1413 struct MBR boot_sect;
034b203a
TM
1414 struct MBR_part_record *part;
1415 unsigned long long curr_part_end;
f21e18ca 1416 unsigned part_nr;
034b203a
TM
1417 int retval = 0;
1418
1419 *endofpart = 0;
1420
056b331e 1421 BUILD_BUG_ON(sizeof(boot_sect) != 512);
034b203a
TM
1422 /* read MBR */
1423 lseek(fd, 0, 0);
056b331e 1424 if (read(fd, &boot_sect, 512) != 512)
034b203a
TM
1425 goto abort;
1426
1427 /* check MBP signature */
056b331e 1428 if (boot_sect.magic == MBR_SIGNATURE_MAGIC) {
034b203a
TM
1429 retval = 1;
1430 /* found the correct signature */
056b331e 1431 part = boot_sect.parts;
034b203a 1432
ca3b6696 1433 for (part_nr = 0; part_nr < MBR_PARTITIONS; part_nr++) {
034b203a
TM
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
53ed6ac3
KW
1455int check_partitions(int fd, char *dname, unsigned long long freesize,
1456 unsigned long long size)
034b203a
TM
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 */
e7b84f9d
N
1468 pr_err("partition table exists on %s but will be lost or\n"
1469 " meaningless after creating array\n",
1470 dname);
034b203a
TM
1471 return 1;
1472 } else if (endofpart > freesize) {
1473 /* last partition overlaps metadata */
e7b84f9d
N
1474 pr_err("metadata will over-write last partition on %s.\n",
1475 dname);
034b203a 1476 return 1;
53ed6ac3
KW
1477 } else if (size && endofpart > size) {
1478 /* partitions will be truncated in new device */
e7b84f9d
N
1479 pr_err("array size is too small to cover all partitions on %s.\n",
1480 dname);
53ed6ac3 1481 return 1;
034b203a
TM
1482 }
1483 }
1484 return 0;
1485}
1486
a322f70c
DW
1487int 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;
a994592d
N
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;
a322f70c
DW
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);
f21e18ca 1535 if (n <= 0 || (unsigned)n >= sizeof(buf))
a322f70c
DW
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 }
355726fa 1547 closedir(dir);
a322f70c
DW
1548 return -1;
1549}
1550
33414a01
DW
1551struct 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
4dd2df09
N
1565int 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
1583int 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
33414a01
DW
1601int is_container_member(struct mdstat_ent *mdstat, char *container)
1602{
1603 if (mdstat->metadata_version == NULL ||
1604 strncmp(mdstat->metadata_version, "external:", 9) != 0 ||
4dd2df09 1605 !metadata_container_matches(mdstat->metadata_version+9, container))
33414a01
DW
1606 return 0;
1607
1608 return 1;
1609}
1610
1611int is_subarray_active(char *subarray, char *container)
1612{
1613 struct mdstat_ent *mdstat = mdstat_read(0, 0);
1614 struct mdstat_ent *ent;
1615
e5408a32
DW
1616 for (ent = mdstat; ent; ent = ent->next)
1617 if (is_container_member(ent, container))
e5e5d7ce 1618 if (strcmp(to_subarray(ent, container), subarray) == 0)
33414a01 1619 break;
33414a01
DW
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
feab51f8 1628 * @st: empty supertype
33414a01
DW
1629 * @quiet: block reporting errors flag
1630 *
1631 * On success returns an fd to a container and fills in *st
1632 */
feab51f8 1633int open_subarray(char *dev, char *subarray, struct supertype *st, int quiet)
33414a01
DW
1634{
1635 struct mdinfo *mdi;
a951a4f7 1636 struct mdinfo *info;
33414a01 1637 int fd, err = 1;
4dd2df09 1638 char *_devnm;
33414a01
DW
1639
1640 fd = open(dev, O_RDWR|O_EXCL);
1641 if (fd < 0) {
1642 if (!quiet)
e7b84f9d 1643 pr_err("Couldn't open %s, aborting\n",
33414a01 1644 dev);
b990032d 1645 return -1;
33414a01
DW
1646 }
1647
4dd2df09
N
1648 _devnm = fd2devnm(fd);
1649 if (_devnm == NULL) {
33414a01 1650 if (!quiet)
e7b84f9d
N
1651 pr_err("Failed to determine device number for %s\n",
1652 dev);
33414a01
DW
1653 goto close_fd;
1654 }
4dd2df09 1655 strcpy(st->devnm, _devnm);
33414a01 1656
4dd2df09 1657 mdi = sysfs_read(fd, st->devnm, GET_VERSION|GET_LEVEL);
33414a01
DW
1658 if (!mdi) {
1659 if (!quiet)
e7b84f9d 1660 pr_err("Failed to read sysfs for %s\n",
33414a01
DW
1661 dev);
1662 goto close_fd;
1663 }
1664
1665 if (mdi->array.level != UnSet) {
1666 if (!quiet)
e7b84f9d 1667 pr_err("%s is not a container\n", dev);
33414a01
DW
1668 goto free_sysfs;
1669 }
1670
1671 st->ss = version_to_superswitch(mdi->text_version);
1672 if (!st->ss) {
1673 if (!quiet)
e7b84f9d
N
1674 pr_err("Operation not supported for %s metadata\n",
1675 mdi->text_version);
33414a01
DW
1676 goto free_sysfs;
1677 }
1678
4dd2df09 1679 if (st->devnm[0] == 0) {
33414a01 1680 if (!quiet)
e7b84f9d 1681 pr_err("Failed to allocate device name\n");
33414a01
DW
1682 goto free_sysfs;
1683 }
1684
db20d413 1685 if (!st->ss->load_container) {
33414a01 1686 if (!quiet)
e7b84f9d 1687 pr_err("%s is not a container\n", dev);
4dd2df09 1688 goto free_sysfs;
33414a01
DW
1689 }
1690
db20d413 1691 if (st->ss->load_container(st, fd, NULL)) {
33414a01 1692 if (!quiet)
e7b84f9d 1693 pr_err("Failed to load metadata for %s\n",
db20d413 1694 dev);
4dd2df09 1695 goto free_sysfs;
33414a01
DW
1696 }
1697
a951a4f7
N
1698 info = st->ss->container_content(st, subarray);
1699 if (!info) {
1700 if (!quiet)
e7b84f9d 1701 pr_err("Failed to find subarray-%s in %s\n",
a951a4f7
N
1702 subarray, dev);
1703 goto free_super;
1704 }
1705 free(info);
1706
33414a01
DW
1707 err = 0;
1708
1709 free_super:
1710 if (err)
1711 st->ss->free_super(st);
33414a01
DW
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
7801ac20
N
1724int 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) {
d23534e4
DW
1731 if (info->disk.state & (1<<MD_DISK_SYNC))
1732 info->recovery_start = MaxSector;
1733 else
1734 info->recovery_start = 0;
2904b26f 1735 rv = sysfs_add_disk(sra, info, 0);
7801ac20
N
1736 if (! rv) {
1737 struct mdinfo *sd2;
f35f2525
N
1738 for (sd2 = sra->devs; sd2; sd2=sd2->next)
1739 if (sd2 == info)
1740 break;
1741 if (sd2 == NULL) {
503975b9 1742 sd2 = xmalloc(sizeof(*sd2));
f35f2525
N
1743 *sd2 = *info;
1744 sd2->next = sra->devs;
1745 sra->devs = sd2;
1746 }
7801ac20
N
1747 }
1748 } else
1749#endif
1750 rv = ioctl(mdfd, ADD_NEW_DISK, &info->disk);
1751 return rv;
1752}
1753
de6ae750
N
1754int 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
f35f2525
N
1769int 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
1e5c6983
DW
1794unsigned 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
4dd2df09 1809int mdmon_pid(char *devnm)
a931db9e
NB
1810{
1811 char path[100];
1812 char pid[10];
1813 int fd;
1814 int n;
10013317 1815
4dd2df09 1816 sprintf(path, "%s/%s.pid", MDMON_DIR, devnm);
10013317 1817
24f6f99b 1818 fd = open(path, O_RDONLY | O_NOATIME, 0);
a931db9e
NB
1819
1820 if (fd < 0)
cf556303 1821 return -1;
a931db9e
NB
1822 n = read(fd, pid, 9);
1823 close(fd);
1824 if (n <= 0)
cf556303 1825 return -1;
24f6f99b 1826 return atoi(pid);
a931db9e
NB
1827}
1828
4dd2df09 1829int mdmon_running(char *devnm)
a931db9e 1830{
4dd2df09 1831 int pid = mdmon_pid(devnm);
24f6f99b 1832 if (pid <= 0)
a931db9e 1833 return 0;
24f6f99b 1834 if (kill(pid, 0) == 0)
a931db9e
NB
1835 return 1;
1836 return 0;
1837}
1838
4dd2df09 1839int start_mdmon(char *devnm)
8850ee3e 1840{
1913c325 1841 int i, skipped;
44d2e365 1842 int len;
ca3b6696 1843 pid_t pid;
9fe32043 1844 int status;
44d2e365
N
1845 char pathbuf[1024];
1846 char *paths[4] = {
1847 pathbuf,
85945e19 1848 BINDIR "/mdmon",
2f1bcf43 1849 "./mdmon",
44d2e365
N
1850 NULL
1851 };
8850ee3e 1852
40ebbb9c 1853 if (check_env("MDADM_NO_MDMON"))
8850ee3e
N
1854 return 0;
1855
9cf014ec 1856 len = readlink("/proc/self/exe", pathbuf, sizeof(pathbuf)-1);
44d2e365
N
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
0f7bdf89 1869 /* First try to run systemctl */
9540cc24
N
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);
7a862a02 1895 case -1: pr_err("cannot run mdmon. Array remains readonly\n");
9540cc24
N
1896 return -1;
1897 default: /* parent - good */
1898 pid = wait(&status);
1899 if (pid >= 0 && status == 0)
1900 return 0;
1901 }
0f7bdf89
JS
1902
1903 /* That failed, try running mdmon directly */
8850ee3e
N
1904 switch(fork()) {
1905 case 0:
1906 /* FIXME yuk. CLOSE_EXEC?? */
1913c325 1907 skipped = 0;
ca3b6696 1908 for (i = 3; skipped < 20; i++)
1913c325
N
1909 if (close(i) < 0)
1910 skipped++;
1911 else
1912 skipped = 0;
1913
ca3b6696 1914 for (i = 0; paths[i]; i++)
a0963a86 1915 if (paths[i][0]) {
2f1bcf43 1916 execl(paths[i], paths[i],
4dd2df09 1917 devnm, NULL);
a0963a86 1918 }
8850ee3e 1919 exit(1);
7a862a02 1920 case -1: pr_err("cannot run mdmon. Array remains readonly\n");
8850ee3e 1921 return -1;
9fe32043
N
1922 default: /* parent - good */
1923 pid = wait(&status);
15c10423 1924 if (pid < 0 || status != 0) {
7a862a02 1925 pr_err("failed to launch mdmon. Array remains readonly\n");
9fe32043 1926 return -1;
15c10423 1927 }
8850ee3e
N
1928 }
1929 return 0;
1930}
1931
148acb7b
DW
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
0e600426 1943#ifndef MDASSEMBLE
edd8d13c
NB
1944int flush_metadata_updates(struct supertype *st)
1945{
1946 int sfd;
1947 if (!st->updates) {
1948 st->update_tail = NULL;
1949 return -1;
1950 }
1951
4dd2df09 1952 sfd = connect_monitor(st->container_devnm);
edd8d13c
NB
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
1972void append_metadata_update(struct supertype *st, void *buf, int len)
1973{
1974
503975b9 1975 struct metadata_update *mu = xmalloc(sizeof(*mu));
edd8d13c
NB
1976
1977 mu->buf = buf;
1978 mu->len = len;
1979 mu->space = NULL;
cb23f1f4 1980 mu->space_list = NULL;
edd8d13c
NB
1981 mu->next = NULL;
1982 *st->update_tail = mu;
1983 st->update_tail = &mu->next;
1984}
0e600426 1985#endif /* MDASSEMBLE */
a931db9e 1986
fe6729fa
NB
1987#ifdef __TINYC__
1988/* tinyc doesn't optimize this check in ioctl.h out ... */
1989unsigned int __invalid_size_argument_for_IOC = 0;
1990#endif
1991
6d11ec6f
AK
1992int experimental(void)
1993{
1994 if (check_env("MDADM_EXPERIMENTAL"))
1995 return 1;
1996 else {
7a862a02 1997 pr_err("To use this feature MDADM_EXPERIMENTAL environment variable has to be defined.\n");
6d11ec6f
AK
1998 return 0;
1999 }
2000}
2001
326727d9
AC
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 */
2007struct 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) {
4dd2df09 2038 struct dev_policy *pol = devid_policy(dev);
326727d9
AC
2039 if (spare_group)
2040 pol_add(&pol, pol_domain,
2041 spare_group, NULL);
e5508b36 2042 if (domain_test(domlist, pol, metadata) != 1)
326727d9
AC
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}
9eafa1de
MN
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 */
2069int 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}
a7dec3fd
N
2083
2084/* Make sure we can open as many devices as needed */
2085void 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}
a9c15847
N
2097
2098int in_initrd(void)
2099{
2100 /* This is based on similar function in systemd. */
2101 struct statfs s;
76d0f188
JS
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 */
a9c15847 2105 return statfs("/", &s) >= 0 &&
7ac5d47e 2106 ((unsigned long)s.f_type == TMPFS_MAGIC ||
76d0f188
JS
2107 ((unsigned long)s.f_type & 0xFFFFFFFFUL) ==
2108 ((unsigned long)RAMFS_MAGIC & 0xFFFFFFFFUL));
a9c15847 2109}
8832342d
N
2110
2111void 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}
7d55dca2 2124#ifndef MDASSEMBLE
7716570e
GJ
2125int 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;
2166name_err:
2167 finalize(handle);
2168out:
2169 dlclose(lib_handle);
2170 return rv;
2171}
d15a1f72
GJ
2172
2173void 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}
7d55dca2 2194#endif