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