]> git.ipfire.org Git - thirdparty/mdadm.git/blame - util.c
mdmon: fix wrong array state when disk fails during mdmon startup
[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
b7a462e5
JS
688 return __fname_from_uuid(info->uuid, (st->ss == &super1) ? 1 :
689 st->ss->swapuuid, buf, sep);
d7288ddc
N
690}
691
682c7051
NB
692int check_ext2(int fd, char *name)
693{
694 /*
695 * Check for an ext2fs file system.
696 * Superblock is always 1K at 1K offset
697 *
698 * s_magic is le16 at 56 == 0xEF53
699 * report mtime - le32 at 44
700 * blocks - le32 at 4
701 * logblksize - le32 at 24
702 */
703 unsigned char sb[1024];
704 time_t mtime;
2538ba2a
N
705 unsigned long long size;
706 int bsize;
682c7051
NB
707 if (lseek(fd, 1024,0)!= 1024)
708 return 0;
709 if (read(fd, sb, 1024)!= 1024)
710 return 0;
711 if (sb[56] != 0x53 || sb[57] != 0xef)
712 return 0;
713
714 mtime = sb[44]|(sb[45]|(sb[46]|sb[47]<<8)<<8)<<8;
715 bsize = sb[24]|(sb[25]|(sb[26]|sb[27]<<8)<<8)<<8;
716 size = sb[4]|(sb[5]|(sb[6]|sb[7]<<8)<<8)<<8;
2538ba2a 717 size <<= bsize;
e7b84f9d 718 pr_err("%s appears to contain an ext2fs file system\n",
682c7051 719 name);
2538ba2a 720 cont_err("size=%lluK mtime=%s", size, ctime(&mtime));
682c7051
NB
721 return 1;
722}
723
724int check_reiser(int fd, char *name)
725{
726 /*
727 * superblock is at 64K
728 * size is 1024;
729 * Magic string "ReIsErFs" or "ReIsEr2Fs" at 52
730 *
731 */
732 unsigned char sb[1024];
2538ba2a 733 unsigned long long size;
682c7051
NB
734 if (lseek(fd, 64*1024, 0) != 64*1024)
735 return 0;
736 if (read(fd, sb, 1024) != 1024)
737 return 0;
ca3b6696
N
738 if (strncmp((char*)sb+52, "ReIsErFs",8) != 0 &&
739 strncmp((char*)sb+52, "ReIsEr2Fs",9) != 0)
682c7051 740 return 0;
e7b84f9d 741 pr_err("%s appears to contain a reiserfs file system\n",name);
682c7051 742 size = sb[0]|(sb[1]|(sb[2]|sb[3]<<8)<<8)<<8;
2538ba2a 743 cont_err("size = %lluK\n", size*4);
aba69144 744
682c7051
NB
745 return 1;
746}
747
748int check_raid(int fd, char *name)
749{
4b1ac34b 750 struct mdinfo info;
682c7051 751 time_t crtime;
d078d77c 752 char *level;
82d9eba6 753 struct supertype *st = guess_super(fd);
f9ce90ba 754
cb8f6859
N
755 if (!st)
756 return 0;
fa219dd2
MD
757 if (st->ss->add_to_super != NULL) {
758 st->ss->load_super(st, fd, name);
759 /* Looks like a raid array .. */
760 pr_err("%s appears to be part of a raid array:\n", name);
761 st->ss->getinfo_super(st, &info, NULL);
762 st->ss->free_super(st);
763 crtime = info.array.ctime;
764 level = map_num(pers, info.array.level);
765 if (!level)
766 level = "-unknown-";
767 cont_err("level=%s devices=%d ctime=%s",
768 level, info.array.raid_disks, ctime(&crtime));
769 } else {
770 /* Looks like GPT or MBR */
771 pr_err("partition table exists on %s\n", name);
772 }
82d9eba6 773 return 1;
682c7051
NB
774}
775
0a6bff09
ZL
776int fstat_is_blkdev(int fd, char *devname, dev_t *rdev)
777{
778 struct stat stb;
779
780 if (fstat(fd, &stb) != 0) {
781 pr_err("fstat failed for %s: %s\n", devname, strerror(errno));
782 return 0;
783 }
784 if ((S_IFMT & stb.st_mode) != S_IFBLK) {
785 pr_err("%s is not a block device.\n", devname);
9e04ac1c
ZL
786 return 0;
787 }
788 if (rdev)
789 *rdev = stb.st_rdev;
790 return 1;
791}
792
793int stat_is_blkdev(char *devname, dev_t *rdev)
794{
795 struct stat stb;
796
797 if (stat(devname, &stb) != 0) {
798 pr_err("stat failed for %s: %s\n", devname, strerror(errno));
799 return 0;
800 }
801 if ((S_IFMT & stb.st_mode) != S_IFBLK) {
802 pr_err("%s is not a block device.\n", devname);
0a6bff09
ZL
803 return 0;
804 }
805 if (rdev)
806 *rdev = stb.st_rdev;
807 return 1;
808}
809
682c7051
NB
810int ask(char *mesg)
811{
812 char *add = "";
813 int i;
ca3b6696 814 for (i = 0; i < 5; i++) {
682c7051
NB
815 char buf[100];
816 fprintf(stderr, "%s%s", mesg, add);
817 fflush(stderr);
818 if (fgets(buf, 100, stdin)==NULL)
819 return 0;
820 if (buf[0]=='y' || buf[0]=='Y')
821 return 1;
822 if (buf[0]=='n' || buf[0]=='N')
823 return 0;
824 add = "(y/n) ";
825 }
e7b84f9d 826 pr_err("assuming 'no'\n");
682c7051
NB
827 return 0;
828}
829
8d80900b 830int is_standard(char *dev, int *nump)
e5329c37
NB
831{
832 /* tests if dev is a "standard" md dev name.
833 * i.e if the last component is "/dNN" or "/mdNN",
aba69144 834 * where NN is a string of digits
598f0d58
NB
835 * Returns 1 if a partitionable standard,
836 * -1 if non-partitonable,
837 * 0 if not a standard name.
e5329c37 838 */
8d80900b 839 char *d = strrchr(dev, '/');
ca3b6696 840 int type = 0;
8d80900b
NB
841 int num;
842 if (!d)
e5329c37 843 return 0;
ca3b6696
N
844 if (strncmp(d, "/d",2) == 0)
845 d += 2, type = 1; /* /dev/md/dN{pM} */
846 else if (strncmp(d, "/md_d", 5) == 0)
847 d += 5, type = 1; /* /dev/md_dN{pM} */
848 else if (strncmp(d, "/md", 3) == 0)
849 d += 3, type = -1; /* /dev/mdN */
850 else if (d-dev > 3 && strncmp(d-2, "md/", 3) == 0)
851 d += 1, type = -1; /* /dev/md/N */
e5329c37
NB
852 else
853 return 0;
8d80900b 854 if (!*d)
e5329c37 855 return 0;
8d80900b
NB
856 num = atoi(d);
857 while (isdigit(*d))
858 d++;
859 if (*d)
e5329c37 860 return 0;
8d80900b
NB
861 if (nump) *nump = num;
862
863 return type;
e5329c37
NB
864}
865
4b1ac34b 866unsigned long calc_csum(void *super, int bytes)
82b27616 867{
56eb10c0 868 unsigned long long newcsum = 0;
82b27616 869 int i;
4b1ac34b
NB
870 unsigned int csum;
871 unsigned int *superc = (unsigned int*) super;
82b27616 872
ca3b6696
N
873 for(i = 0; i < bytes/4; i++)
874 newcsum += superc[i];
82b27616 875 csum = (newcsum& 0xffffffff) + (newcsum>>32);
570c0542 876#ifdef __alpha__
aba69144 877/* The in-kernel checksum calculation is always 16bit on
570c0542 878 * the alpha, though it is 32 bit on i386...
ca3b6696 879 * I wonder what it is elsewhere... (it uses an API in
570c0542
NB
880 * a way that it shouldn't).
881 */
882 csum = (csum & 0xffff) + (csum >> 16);
883 csum = (csum & 0xffff) + (csum >> 16);
884#endif
82b27616
NB
885 return csum;
886}
cd29a5c8 887
56eb10c0 888char *human_size(long long bytes)
cd29a5c8 889{
ff9239ee 890 static char buf[47];
d5d3721e
NB
891
892 /* We convert bytes to either centi-M{ega,ibi}bytes or
893 * centi-G{igi,ibi}bytes, with appropriate rounding,
894 * and then print 1/100th of those as a decimal.
895 * We allow upto 2048Megabytes before converting to
896 * gigabytes, as that shows more precision and isn't
897 * too large a number.
01619b48 898 * Terabytes are not yet handled.
d5d3721e 899 */
cd29a5c8 900
56eb10c0 901 if (bytes < 5000*1024)
ca3b6696 902 buf[0] = 0;
d5d3721e 903 else if (bytes < 2*1024LL*1024LL*1024LL) {
93d3bd3b 904 long cMiB = (bytes * 200LL / (1LL<<20) + 1) / 2;
d5d3721e 905 long cMB = (bytes / ( 1000000LL / 200LL ) +1) /2;
8f23b0b3 906 snprintf(buf, sizeof(buf), " (%ld.%02ld MiB %ld.%02ld MB)",
efa29530 907 cMiB/100, cMiB % 100, cMB/100, cMB % 100);
d5d3721e 908 } else {
93d3bd3b 909 long cGiB = (bytes * 200LL / (1LL<<30) +1) / 2;
d5d3721e 910 long cGB = (bytes / (1000000000LL/200LL ) +1) /2;
8f23b0b3 911 snprintf(buf, sizeof(buf), " (%ld.%02ld GiB %ld.%02ld GB)",
efa29530 912 cGiB/100, cGiB % 100, cGB/100, cGB % 100);
d5d3721e 913 }
cd29a5c8
NB
914 return buf;
915}
e0d19036 916
f0ec6710 917char *human_size_brief(long long bytes, int prefix)
e0d19036
NB
918{
919 static char buf[30];
e0d19036 920
570abc6f
MN
921 /* We convert bytes to either centi-M{ega,ibi}bytes or
922 * centi-G{igi,ibi}bytes, with appropriate rounding,
923 * and then print 1/100th of those as a decimal.
924 * We allow upto 2048Megabytes before converting to
925 * gigabytes, as that shows more precision and isn't
926 * too large a number.
927 * Terabytes are not yet handled.
f0ec6710
MN
928 *
929 * If prefix == IEC, we mean prefixes like kibi,mebi,gibi etc.
930 * If prefix == JEDEC, we mean prefixes like kilo,mega,giga etc.
570abc6f
MN
931 */
932
e0d19036 933 if (bytes < 5000*1024)
570abc6f 934 buf[0] = 0;
f0ec6710
MN
935 else if (prefix == IEC) {
936 if (bytes < 2*1024LL*1024LL*1024LL) {
93d3bd3b 937 long cMiB = (bytes * 200LL / (1LL<<20) +1) /2;
f0ec6710 938 snprintf(buf, sizeof(buf), "%ld.%02ldMiB",
efa29530 939 cMiB/100, cMiB % 100);
f0ec6710 940 } else {
93d3bd3b 941 long cGiB = (bytes * 200LL / (1LL<<30) +1) /2;
f0ec6710 942 snprintf(buf, sizeof(buf), "%ld.%02ldGiB",
efa29530 943 cGiB/100, cGiB % 100);
f0ec6710
MN
944 }
945 }
946 else if (prefix == JEDEC) {
947 if (bytes < 2*1024LL*1024LL*1024LL) {
948 long cMB = (bytes / ( 1000000LL / 200LL ) +1) /2;
949 snprintf(buf, sizeof(buf), "%ld.%02ldMB",
efa29530 950 cMB/100, cMB % 100);
f0ec6710
MN
951 } else {
952 long cGB = (bytes / (1000000000LL/200LL ) +1) /2;
953 snprintf(buf, sizeof(buf), "%ld.%02ldGB",
efa29530 954 cGB/100, cGB % 100);
f0ec6710 955 }
570abc6f 956 }
f0ec6710
MN
957 else
958 buf[0] = 0;
570abc6f 959
e0d19036
NB
960 return buf;
961}
e4965ef8
N
962
963void print_r10_layout(int layout)
964{
965 int near = layout & 255;
966 int far = (layout >> 8) & 255;
967 int offset = (layout&0x10000);
968 char *sep = "";
969
970 if (near != 1) {
971 printf("%s near=%d", sep, near);
972 sep = ",";
973 }
974 if (far != 1)
975 printf("%s %s=%d", sep, offset?"offset":"far", far);
976 if (near*far == 1)
977 printf("NO REDUNDANCY");
978}
e0d19036 979
5f8097be
NB
980unsigned long long calc_array_size(int level, int raid_disks, int layout,
981 int chunksize, unsigned long long devsize)
577e8448 982{
e03640bd
CA
983 if (level == 1)
984 return devsize;
577e8448
AK
985 devsize &= ~(unsigned long long)((chunksize>>9)-1);
986 return get_data_disks(level, layout, raid_disks) * devsize;
987}
988
989int get_data_disks(int level, int layout, int raid_disks)
5f8097be
NB
990{
991 int data_disks = 0;
992 switch (level) {
ca3b6696
N
993 case 0: data_disks = raid_disks;
994 break;
995 case 1: data_disks = 1;
996 break;
5f8097be 997 case 4:
ca3b6696
N
998 case 5: data_disks = raid_disks - 1;
999 break;
1000 case 6: data_disks = raid_disks - 2;
1001 break;
5f8097be
NB
1002 case 10: data_disks = raid_disks / (layout & 255) / ((layout>>8)&255);
1003 break;
1004 }
577e8448
AK
1005
1006 return data_disks;
5f8097be
NB
1007}
1008
13db17bd 1009dev_t devnm2devid(char *devnm)
4dd2df09
N
1010{
1011 /* First look in /sys/block/$DEVNM/dev for %d:%d
1012 * If that fails, try parsing out a number
1013 */
1014 char path[100];
1015 char *ep;
1016 int fd;
1017 int mjr,mnr;
1018
1019 sprintf(path, "/sys/block/%s/dev", devnm);
1020 fd = open(path, O_RDONLY);
1021 if (fd >= 0) {
1022 char buf[20];
1023 int n = read(fd, buf, sizeof(buf));
1024 close(fd);
1025 if (n > 0)
1026 buf[n] = 0;
1027 if (n > 0 && sscanf(buf, "%d:%d\n", &mjr, &mnr) == 2)
1028 return makedev(mjr, mnr);
1029 }
1030 if (strncmp(devnm, "md_d", 4) == 0 &&
1031 isdigit(devnm[4]) &&
1032 (mnr = strtoul(devnm+4, &ep, 10)) >= 0 &&
1033 ep > devnm && *ep == 0)
1034 return makedev(get_mdp_major(), mnr << MdpMinorShift);
1035
1036 if (strncmp(devnm, "md", 2) == 0 &&
1037 isdigit(devnm[2]) &&
1038 (mnr = strtoul(devnm+2, &ep, 10)) >= 0 &&
1039 ep > devnm && *ep == 0)
1040 return makedev(MD_MAJOR, mnr);
1041
1042 return 0;
1043}
1044
1045char *get_md_name(char *devnm)
e0d19036
NB
1046{
1047 /* find /dev/md%d or /dev/md/%d or make a device /dev/.tmp.md%d */
98c6faba 1048 /* if dev < 0, want /dev/md/d%d or find mdp in /proc/devices ... */
4dd2df09 1049
e0d19036
NB
1050 static char devname[50];
1051 struct stat stb;
4dd2df09 1052 dev_t rdev = devnm2devid(devnm);
dd0781e5 1053 char *dn;
98c6faba 1054
4dd2df09
N
1055 if (rdev == 0)
1056 return 0;
1057 if (strncmp(devnm, "md_", 3) == 0) {
1058 snprintf(devname, sizeof(devname), "/dev/md/%s",
1059 devnm + 3);
fc54fe7a
JS
1060 if (stat(devname, &stb) == 0 &&
1061 (S_IFMT&stb.st_mode) == S_IFBLK && (stb.st_rdev == rdev))
98c6faba
NB
1062 return devname;
1063 }
4dd2df09 1064 snprintf(devname, sizeof(devname), "/dev/%s", devnm);
fc54fe7a
JS
1065 if (stat(devname, &stb) == 0 && (S_IFMT&stb.st_mode) == S_IFBLK &&
1066 (stb.st_rdev == rdev))
4dd2df09
N
1067 return devname;
1068
1069 snprintf(devname, sizeof(devname), "/dev/md/%s", devnm+2);
fc54fe7a
JS
1070 if (stat(devname, &stb) == 0 && (S_IFMT&stb.st_mode) == S_IFBLK &&
1071 (stb.st_rdev == rdev))
4dd2df09
N
1072 return devname;
1073
16c6fa80 1074 dn = map_dev(major(rdev), minor(rdev), 0);
dd0781e5
NB
1075 if (dn)
1076 return dn;
4dd2df09 1077 snprintf(devname, sizeof(devname), "/dev/.tmp.%s", devnm);
e0d19036 1078 if (mknod(devname, S_IFBLK | 0600, rdev) == -1)
dd0781e5
NB
1079 if (errno != EEXIST)
1080 return NULL;
e0d19036 1081
fc54fe7a
JS
1082 if (stat(devname, &stb) == 0 && (S_IFMT&stb.st_mode) == S_IFBLK &&
1083 (stb.st_rdev == rdev))
e0d19036
NB
1084 return devname;
1085 unlink(devname);
1086 return NULL;
1087}
1088
1089void put_md_name(char *name)
1090{
ca3b6696 1091 if (strncmp(name, "/dev/.tmp.md", 12) == 0)
e0d19036
NB
1092 unlink(name);
1093}
f9ce90ba 1094
cc742d38
N
1095int get_maj_min(char *dev, int *major, int *minor)
1096{
1097 char *e;
1098 *major = strtoul(dev, &e, 0);
1099 return (e > dev && *e == ':' && e[1] &&
1100 (*minor = strtoul(e+1, &e, 0)) >= 0 &&
1101 *e == 0);
1102}
1103
8b0dabea
NB
1104int dev_open(char *dev, int flags)
1105{
1106 /* like 'open', but if 'dev' matches %d:%d, create a temp
1107 * block device and open that
1108 */
8b0dabea
NB
1109 int fd = -1;
1110 char devname[32];
e81cdd9f 1111 int major;
8b0dabea 1112 int minor;
e81cdd9f 1113
9f0ad56b
JS
1114 if (!dev)
1115 return -1;
6df6a774 1116 flags |= O_DIRECT;
e81cdd9f 1117
cc742d38 1118 if (get_maj_min(dev, &major, &minor)) {
9dc7d357
N
1119 snprintf(devname, sizeof(devname), "/dev/.tmp.md.%d:%d:%d",
1120 (int)getpid(), major, minor);
1121 if (mknod(devname, S_IFBLK|0600, makedev(major, minor)) == 0) {
1122 fd = open(devname, flags);
1123 unlink(devname);
6df6a774
N
1124 }
1125 if (fd < 0) {
9dc7d357 1126 /* Try /tmp as /dev appear to be read-only */
b7a462e5
JS
1127 snprintf(devname, sizeof(devname),
1128 "/tmp/.tmp.md.%d:%d:%d",
6df6a774 1129 (int)getpid(), major, minor);
b7a462e5
JS
1130 if (mknod(devname, S_IFBLK|0600,
1131 makedev(major, minor)) == 0) {
6df6a774
N
1132 fd = open(devname, flags);
1133 unlink(devname);
1134 }
8b0dabea
NB
1135 }
1136 } else
6df6a774 1137 fd = open(dev, flags);
8b0dabea
NB
1138 return fd;
1139}
f9ce90ba 1140
4dd2df09 1141int open_dev_flags(char *devnm, int flags)
e8a70c89 1142{
13db17bd 1143 dev_t devid;
e8a70c89
N
1144 char buf[20];
1145
4dd2df09
N
1146 devid = devnm2devid(devnm);
1147 sprintf(buf, "%d:%d", major(devid), minor(devid));
d998b738
N
1148 return dev_open(buf, flags);
1149}
1150
4dd2df09 1151int open_dev(char *devnm)
d998b738 1152{
4dd2df09 1153 return open_dev_flags(devnm, O_RDONLY);
e8a70c89
N
1154}
1155
4dd2df09 1156int open_dev_excl(char *devnm)
a931db9e
NB
1157{
1158 char buf[20];
1159 int i;
7187750e 1160 int flags = O_RDWR;
13db17bd 1161 dev_t devid = devnm2devid(devnm);
399e0b97 1162 long delay = 1000;
a931db9e 1163
4dd2df09 1164 sprintf(buf, "%d:%d", major(devid), minor(devid));
efa29530 1165 for (i = 0; i < 25; i++) {
7187750e 1166 int fd = dev_open(buf, flags|O_EXCL);
a931db9e
NB
1167 if (fd >= 0)
1168 return fd;
7187750e
N
1169 if (errno == EACCES && flags == O_RDWR) {
1170 flags = O_RDONLY;
1171 continue;
1172 }
a931db9e
NB
1173 if (errno != EBUSY)
1174 return fd;
399e0b97
N
1175 usleep(delay);
1176 if (delay < 200000)
1177 delay *= 2;
a931db9e
NB
1178 }
1179 return -1;
1180}
1181
9008ed1c
N
1182int same_dev(char *one, char *two)
1183{
1184 struct stat st1, st2;
1185 if (stat(one, &st1) != 0)
1186 return 0;
1187 if (stat(two, &st2) != 0)
1188 return 0;
1189 if ((st1.st_mode & S_IFMT) != S_IFBLK)
1190 return 0;
1191 if ((st2.st_mode & S_IFMT) != S_IFBLK)
1192 return 0;
1193 return st1.st_rdev == st2.st_rdev;
1194}
1195
a7c6e3fb 1196void wait_for(char *dev, int fd)
a714580e
N
1197{
1198 int i;
a7c6e3fb 1199 struct stat stb_want;
399e0b97 1200 long delay = 1000;
a7c6e3fb
N
1201
1202 if (fstat(fd, &stb_want) != 0 ||
1203 (stb_want.st_mode & S_IFMT) != S_IFBLK)
1204 return;
a714580e 1205
efa29530 1206 for (i = 0; i < 25; i++) {
a714580e 1207 struct stat stb;
a7c6e3fb
N
1208 if (stat(dev, &stb) == 0 &&
1209 (stb.st_mode & S_IFMT) == S_IFBLK &&
1210 (stb.st_rdev == stb_want.st_rdev))
a714580e 1211 return;
399e0b97
N
1212 usleep(delay);
1213 if (delay < 200000)
1214 delay *= 2;
a714580e 1215 }
436305c6 1216 if (i == 25)
9b8fea91 1217 pr_err("timeout waiting for %s\n", dev);
a714580e
N
1218}
1219
0f22b998
N
1220struct superswitch *superlist[] =
1221{
1222 &super0, &super1,
1223 &super_ddf, &super_imsm,
0592faeb 1224 &mbr, &gpt,
32141c17
JS
1225 NULL
1226};
f7dd881f 1227
4725bc31 1228struct supertype *super_by_fd(int fd, char **subarrayp)
f9ce90ba 1229{
1686dc25
NB
1230 mdu_array_info_t array;
1231 int vers;
1232 int minor;
1233 struct supertype *st = NULL;
7e0f6979 1234 struct mdinfo *sra;
142cb9e1 1235 char *verstr;
1686dc25
NB
1236 char version[20];
1237 int i;
f7e7067b 1238 char *subarray = NULL;
4dd2df09 1239 char container[32] = "";
1686dc25 1240
4dd2df09 1241 sra = sysfs_read(fd, NULL, GET_VERSION);
1686dc25
NB
1242
1243 if (sra) {
7e0f6979
NB
1244 vers = sra->array.major_version;
1245 minor = sra->array.minor_version;
142cb9e1 1246 verstr = sra->text_version;
1686dc25 1247 } else {
9cd39f01 1248 if (md_get_array_info(fd, &array))
1686dc25
NB
1249 array.major_version = array.minor_version = 0;
1250 vers = array.major_version;
1251 minor = array.minor_version;
142cb9e1 1252 verstr = "";
6fbba4c9 1253 }
82d9eba6 1254
1686dc25
NB
1255 if (vers != -1) {
1256 sprintf(version, "%d.%d", vers, minor);
1257 verstr = version;
6fbba4c9 1258 }
3c558363 1259 if (minor == -2 && is_subarray(verstr)) {
f7e7067b 1260 char *dev = verstr+1;
5f7e44b2 1261
f7e7067b 1262 subarray = strchr(dev, '/');
92d49ecf 1263 if (subarray) {
f7e7067b 1264 *subarray++ = '\0';
503975b9 1265 subarray = xstrdup(subarray);
92d49ecf 1266 }
4dd2df09 1267 strcpy(container, dev);
15d230f7 1268 sysfs_free(sra);
5f7e44b2 1269 sra = sysfs_read(-1, container, GET_VERSION);
603f24a0
N
1270 if (sra && sra->text_version[0])
1271 verstr = sra->text_version;
1272 else
1273 verstr = "-no-metadata-";
f7e7067b
NB
1274 }
1275
efa29530 1276 for (i = 0; st == NULL && superlist[i]; i++)
f7e7067b 1277 st = superlist[i]->match_metadata_desc(verstr);
1686dc25 1278
15d230f7 1279 sysfs_free(sra);
f7e7067b 1280 if (st) {
3b0896f8 1281 st->sb = NULL;
1f49fb3a
N
1282 if (subarrayp)
1283 *subarrayp = subarray;
4dd2df09
N
1284 strcpy(st->container_devnm, container);
1285 strcpy(st->devnm, fd2devnm(fd));
4725bc31
N
1286 } else
1287 free(subarray);
5f7e44b2 1288
82d9eba6 1289 return st;
f9ce90ba 1290}
ea24acd0 1291
0f0749ad 1292int dev_size_from_id(dev_t id, unsigned long long *size)
52d5d101
AC
1293{
1294 char buf[20];
1295 int fd;
1296
1297 sprintf(buf, "%d:%d", major(id), minor(id));
1298 fd = dev_open(buf, O_RDONLY);
1299 if (fd < 0)
1300 return 0;
1301 if (get_dev_size(fd, NULL, size)) {
1302 close(fd);
1303 return 1;
1304 }
1305 close(fd);
1306 return 0;
1307}
f9ce90ba 1308
4b57ecf6
AO
1309int dev_sector_size_from_id(dev_t id, unsigned int *size)
1310{
1311 char buf[20];
1312 int fd;
1313
1314 sprintf(buf, "%d:%d", major(id), minor(id));
1315 fd = dev_open(buf, O_RDONLY);
1316 if (fd < 0)
1317 return 0;
1318 if (get_dev_sector_size(fd, NULL, size)) {
1319 close(fd);
1320 return 1;
1321 }
1322 close(fd);
1323 return 0;
1324}
1325
159c3a1a 1326struct supertype *dup_super(struct supertype *orig)
3da92f27 1327{
159c3a1a 1328 struct supertype *st;
1686dc25 1329
d2ca6449
NB
1330 if (!orig)
1331 return orig;
503975b9 1332 st = xcalloc(1, sizeof(*st));
159c3a1a
NB
1333 st->ss = orig->ss;
1334 st->max_devs = orig->max_devs;
1335 st->minor_version = orig->minor_version;
cb8f6859 1336 st->ignore_hw_compat = orig->ignore_hw_compat;
23bf42cc 1337 st->data_offset = orig->data_offset;
159c3a1a
NB
1338 st->sb = NULL;
1339 st->info = NULL;
1340 return st;
3da92f27
NB
1341}
1342
54887ad8 1343struct supertype *guess_super_type(int fd, enum guess_types guess_type)
f9ce90ba
NB
1344{
1345 /* try each load_super to find the best match,
1346 * and return the best superswitch
1347 */
82d9eba6
NB
1348 struct superswitch *ss;
1349 struct supertype *st;
1d13b599 1350 unsigned int besttime = 0;
570c0542 1351 int bestsuper = -1;
f9ce90ba
NB
1352 int i;
1353
503975b9 1354 st = xcalloc(1, sizeof(*st));
4dd2df09 1355 st->container_devnm[0] = 0;
d1d599ea 1356
efa29530 1357 for (i = 0; superlist[i]; i++) {
f9ce90ba
NB
1358 int rv;
1359 ss = superlist[i];
54887ad8
N
1360 if (guess_type == guess_array && ss->add_to_super == NULL)
1361 continue;
1362 if (guess_type == guess_partitions && ss->add_to_super != NULL)
1363 continue;
ef609477 1364 memset(st, 0, sizeof(*st));
df3346e6 1365 st->ignore_hw_compat = 1;
3da92f27 1366 rv = ss->load_super(st, fd, NULL);
570c0542
NB
1367 if (rv == 0) {
1368 struct mdinfo info;
a5d85af7 1369 st->ss->getinfo_super(st, &info, NULL);
570c0542
NB
1370 if (bestsuper == -1 ||
1371 besttime < info.array.ctime) {
1372 bestsuper = i;
1373 besttime = info.array.ctime;
570c0542 1374 }
3da92f27 1375 ss->free_super(st);
570c0542
NB
1376 }
1377 }
1378 if (bestsuper != -1) {
1379 int rv;
ef609477 1380 memset(st, 0, sizeof(*st));
df3346e6 1381 st->ignore_hw_compat = 1;
3da92f27 1382 rv = superlist[bestsuper]->load_super(st, fd, NULL);
f9ce90ba 1383 if (rv == 0) {
5e747af2 1384 superlist[bestsuper]->free_super(st);
82d9eba6 1385 return st;
f9ce90ba
NB
1386 }
1387 }
570c0542 1388 free(st);
f9ce90ba
NB
1389 return NULL;
1390}
fe6729fa 1391
beae1dfe
NB
1392/* Return size of device in bytes */
1393int get_dev_size(int fd, char *dname, unsigned long long *sizep)
1394{
1395 unsigned long long ldsize;
c2c9bb6f
NB
1396 struct stat st;
1397
1398 if (fstat(fd, &st) != -1 && S_ISREG(st.st_mode))
1399 ldsize = (unsigned long long)st.st_size;
1400 else
beae1dfe
NB
1401#ifdef BLKGETSIZE64
1402 if (ioctl(fd, BLKGETSIZE64, &ldsize) != 0)
1403#endif
1404 {
1405 unsigned long dsize;
1406 if (ioctl(fd, BLKGETSIZE, &dsize) == 0) {
1407 ldsize = dsize;
1408 ldsize <<= 9;
1409 } else {
1410 if (dname)
32971509 1411 pr_err("Cannot get size of %s: %s\n",
beae1dfe
NB
1412 dname, strerror(errno));
1413 return 0;
1414 }
1415 }
1416 *sizep = ldsize;
1417 return 1;
1418}
8fac0577 1419
32971509
PB
1420/* Return sector size of device in bytes */
1421int get_dev_sector_size(int fd, char *dname, unsigned int *sectsizep)
1422{
1423 unsigned int sectsize;
1424
1425 if (ioctl(fd, BLKSSZGET, &sectsize) != 0) {
1426 if (dname)
1427 pr_err("Cannot get sector size of %s: %s\n",
1428 dname, strerror(errno));
1429 return 0;
1430 }
1431
1432 *sectsizep = sectsize;
1433 return 1;
1434}
1435
3a371610
N
1436/* Return true if this can only be a container, not a member device.
1437 * i.e. is and md device and size is zero
1438 */
1439int must_be_container(int fd)
1440{
f5c924f4 1441 struct mdinfo *mdi;
3a371610 1442 unsigned long long size;
f5c924f4
JS
1443
1444 mdi = sysfs_read(fd, NULL, GET_VERSION);
1445 if (!mdi)
3a371610 1446 return 0;
f5c924f4
JS
1447 sysfs_free(mdi);
1448
3a371610
N
1449 if (get_dev_size(fd, NULL, &size) == 0)
1450 return 1;
1451 if (size == 0)
1452 return 1;
1453 return 0;
1454}
034b203a
TM
1455
1456/* Sets endofpart parameter to the last block used by the last GPT partition on the device.
1457 * Returns: 1 if successful
1458 * -1 for unknown partition type
1459 * 0 for other errors
1460 */
1461static int get_gpt_last_partition_end(int fd, unsigned long long *endofpart)
1462{
056b331e 1463 struct GPT gpt;
034b203a 1464 unsigned char empty_gpt_entry[16]= {0};
db7fdfe4
JS
1465 struct GPT_part_entry *part;
1466 char buf[512];
034b203a
TM
1467 unsigned long long curr_part_end;
1468 unsigned all_partitions, entry_size;
f21e18ca 1469 unsigned part_nr;
41b06495 1470 unsigned int sector_size = 0;
034b203a
TM
1471
1472 *endofpart = 0;
1473
056b331e 1474 BUILD_BUG_ON(sizeof(gpt) != 512);
73e658d8 1475 /* skip protective MBR */
41b06495
MD
1476 if (!get_dev_sector_size(fd, NULL, &sector_size))
1477 return 0;
1478 lseek(fd, sector_size, SEEK_SET);
73e658d8 1479 /* read GPT header */
056b331e 1480 if (read(fd, &gpt, 512) != 512)
034b203a
TM
1481 return 0;
1482
1483 /* get the number of partition entries and the entry size */
056b331e
N
1484 all_partitions = __le32_to_cpu(gpt.part_cnt);
1485 entry_size = __le32_to_cpu(gpt.part_size);
034b203a
TM
1486
1487 /* Check GPT signature*/
056b331e 1488 if (gpt.magic != GPT_SIGNATURE_MAGIC)
034b203a
TM
1489 return -1;
1490
1491 /* sanity checks */
1492 if (all_partitions > 1024 ||
db7fdfe4 1493 entry_size > sizeof(buf))
034b203a
TM
1494 return -1;
1495
db7fdfe4
JS
1496 part = (struct GPT_part_entry *)buf;
1497
41b06495
MD
1498 /* set offset to third block (GPT entries) */
1499 lseek(fd, sector_size*2, SEEK_SET);
ca3b6696 1500 for (part_nr = 0; part_nr < all_partitions; part_nr++) {
73e658d8 1501 /* read partition entry */
db7fdfe4 1502 if (read(fd, buf, entry_size) != (ssize_t)entry_size)
73e658d8
LB
1503 return 0;
1504
034b203a 1505 /* is this valid partition? */
db7fdfe4 1506 if (memcmp(part->type_guid, empty_gpt_entry, 16) != 0) {
034b203a 1507 /* check the last lba for the current partition */
db7fdfe4 1508 curr_part_end = __le64_to_cpu(part->ending_lba);
034b203a
TM
1509 if (curr_part_end > *endofpart)
1510 *endofpart = curr_part_end;
1511 }
1512
034b203a
TM
1513 }
1514 return 1;
1515}
1516
1517/* Sets endofpart parameter to the last block used by the last partition on the device.
1518 * Returns: 1 if successful
1519 * -1 for unknown partition type
1520 * 0 for other errors
1521 */
1522static int get_last_partition_end(int fd, unsigned long long *endofpart)
1523{
056b331e 1524 struct MBR boot_sect;
034b203a 1525 unsigned long long curr_part_end;
f21e18ca 1526 unsigned part_nr;
31208db9 1527 unsigned int sector_size;
034b203a
TM
1528 int retval = 0;
1529
1530 *endofpart = 0;
1531
056b331e 1532 BUILD_BUG_ON(sizeof(boot_sect) != 512);
034b203a
TM
1533 /* read MBR */
1534 lseek(fd, 0, 0);
056b331e 1535 if (read(fd, &boot_sect, 512) != 512)
034b203a
TM
1536 goto abort;
1537
1538 /* check MBP signature */
056b331e 1539 if (boot_sect.magic == MBR_SIGNATURE_MAGIC) {
034b203a
TM
1540 retval = 1;
1541 /* found the correct signature */
034b203a 1542
ca3b6696 1543 for (part_nr = 0; part_nr < MBR_PARTITIONS; part_nr++) {
8e2bca51
JC
1544 /*
1545 * Have to make every access through boot_sect rather
1546 * than using a pointer to the partition table (or an
1547 * entry), since the entries are not properly aligned.
1548 */
1549
034b203a 1550 /* check for GPT type */
8e2bca51
JC
1551 if (boot_sect.parts[part_nr].part_type ==
1552 MBR_GPT_PARTITION_TYPE) {
034b203a
TM
1553 retval = get_gpt_last_partition_end(fd, endofpart);
1554 break;
1555 }
1556 /* check the last used lba for the current partition */
8e2bca51
JC
1557 curr_part_end =
1558 __le32_to_cpu(boot_sect.parts[part_nr].first_sect_lba) +
1559 __le32_to_cpu(boot_sect.parts[part_nr].blocks_num);
034b203a
TM
1560 if (curr_part_end > *endofpart)
1561 *endofpart = curr_part_end;
034b203a
TM
1562 }
1563 } else {
1564 /* Unknown partition table */
1565 retval = -1;
1566 }
31208db9
MD
1567 /* calculate number of 512-byte blocks */
1568 if (get_dev_sector_size(fd, NULL, &sector_size))
1569 *endofpart *= (sector_size / 512);
034b203a
TM
1570 abort:
1571 return retval;
1572}
1573
53ed6ac3
KW
1574int check_partitions(int fd, char *dname, unsigned long long freesize,
1575 unsigned long long size)
034b203a
TM
1576{
1577 /*
1578 * Check where the last partition ends
1579 */
1580 unsigned long long endofpart;
034b203a 1581
31208db9 1582 if (get_last_partition_end(fd, &endofpart) > 0) {
034b203a
TM
1583 /* There appears to be a partition table here */
1584 if (freesize == 0) {
1585 /* partitions will not be visible in new device */
e7b84f9d
N
1586 pr_err("partition table exists on %s but will be lost or\n"
1587 " meaningless after creating array\n",
1588 dname);
034b203a
TM
1589 return 1;
1590 } else if (endofpart > freesize) {
1591 /* last partition overlaps metadata */
e7b84f9d
N
1592 pr_err("metadata will over-write last partition on %s.\n",
1593 dname);
034b203a 1594 return 1;
53ed6ac3
KW
1595 } else if (size && endofpart > size) {
1596 /* partitions will be truncated in new device */
e7b84f9d
N
1597 pr_err("array size is too small to cover all partitions on %s.\n",
1598 dname);
53ed6ac3 1599 return 1;
034b203a
TM
1600 }
1601 }
1602 return 0;
1603}
1604
a322f70c
DW
1605int open_container(int fd)
1606{
1607 /* 'fd' is a block device. Find out if it is in use
1608 * by a container, and return an open fd on that container.
1609 */
1610 char path[256];
1611 char *e;
1612 DIR *dir;
1613 struct dirent *de;
1614 int dfd, n;
1615 char buf[200];
1616 int major, minor;
1617 struct stat st;
1618
1619 if (fstat(fd, &st) != 0)
1620 return -1;
1621 sprintf(path, "/sys/dev/block/%d:%d/holders",
1622 (int)major(st.st_rdev), (int)minor(st.st_rdev));
1623 e = path + strlen(path);
1624
1625 dir = opendir(path);
1626 if (!dir)
1627 return -1;
1628 while ((de = readdir(dir))) {
1629 if (de->d_ino == 0)
1630 continue;
1631 if (de->d_name[0] == '.')
1632 continue;
a994592d
N
1633 /* Need to make sure it is a container and not a volume */
1634 sprintf(e, "/%s/md/metadata_version", de->d_name);
1635 dfd = open(path, O_RDONLY);
1636 if (dfd < 0)
1637 continue;
1638 n = read(dfd, buf, sizeof(buf));
1639 close(dfd);
1640 if (n <= 0 || (unsigned)n >= sizeof(buf))
1641 continue;
1642 buf[n] = 0;
1643 if (strncmp(buf, "external", 8) != 0 ||
1644 n < 10 ||
1645 buf[9] == '/')
1646 continue;
a322f70c
DW
1647 sprintf(e, "/%s/dev", de->d_name);
1648 dfd = open(path, O_RDONLY);
1649 if (dfd < 0)
1650 continue;
1651 n = read(dfd, buf, sizeof(buf));
1652 close(dfd);
f21e18ca 1653 if (n <= 0 || (unsigned)n >= sizeof(buf))
a322f70c
DW
1654 continue;
1655 buf[n] = 0;
1656 if (sscanf(buf, "%d:%d", &major, &minor) != 2)
1657 continue;
1658 sprintf(buf, "%d:%d", major, minor);
1659 dfd = dev_open(buf, O_RDONLY);
1660 if (dfd >= 0) {
1661 closedir(dir);
1662 return dfd;
1663 }
1664 }
355726fa 1665 closedir(dir);
a322f70c
DW
1666 return -1;
1667}
1668
33414a01
DW
1669struct superswitch *version_to_superswitch(char *vers)
1670{
1671 int i;
1672
1673 for (i = 0; superlist[i]; i++) {
1674 struct superswitch *ss = superlist[i];
1675
1676 if (strcmp(vers, ss->name) == 0)
1677 return ss;
1678 }
1679
1680 return NULL;
1681}
1682
4dd2df09
N
1683int metadata_container_matches(char *metadata, char *devnm)
1684{
1685 /* Check if 'devnm' is the container named in 'metadata'
1686 * which is
1687 * /containername/componentname or
1688 * -containername/componentname
1689 */
1690 int l;
1691 if (*metadata != '/' && *metadata != '-')
1692 return 0;
1693 l = strlen(devnm);
1694 if (strncmp(metadata+1, devnm, l) != 0)
1695 return 0;
1696 if (metadata[l+1] != '/')
1697 return 0;
1698 return 1;
1699}
1700
1701int metadata_subdev_matches(char *metadata, char *devnm)
1702{
1703 /* Check if 'devnm' is the subdev named in 'metadata'
1704 * which is
1705 * /containername/subdev or
1706 * -containername/subdev
1707 */
1708 char *sl;
1709 if (*metadata != '/' && *metadata != '-')
1710 return 0;
1711 sl = strchr(metadata+1, '/');
1712 if (!sl)
1713 return 0;
1714 if (strcmp(sl+1, devnm) == 0)
1715 return 1;
1716 return 0;
1717}
1718
33414a01
DW
1719int is_container_member(struct mdstat_ent *mdstat, char *container)
1720{
1721 if (mdstat->metadata_version == NULL ||
1722 strncmp(mdstat->metadata_version, "external:", 9) != 0 ||
4dd2df09 1723 !metadata_container_matches(mdstat->metadata_version+9, container))
33414a01
DW
1724 return 0;
1725
1726 return 1;
1727}
1728
1729int is_subarray_active(char *subarray, char *container)
1730{
1731 struct mdstat_ent *mdstat = mdstat_read(0, 0);
1732 struct mdstat_ent *ent;
1733
e5408a32
DW
1734 for (ent = mdstat; ent; ent = ent->next)
1735 if (is_container_member(ent, container))
e5e5d7ce 1736 if (strcmp(to_subarray(ent, container), subarray) == 0)
33414a01 1737 break;
33414a01
DW
1738
1739 free_mdstat(mdstat);
1740
1741 return ent != NULL;
1742}
1743
1744/* open_subarray - opens a subarray in a container
1745 * @dev: container device name
feab51f8 1746 * @st: empty supertype
33414a01
DW
1747 * @quiet: block reporting errors flag
1748 *
1749 * On success returns an fd to a container and fills in *st
1750 */
feab51f8 1751int open_subarray(char *dev, char *subarray, struct supertype *st, int quiet)
33414a01
DW
1752{
1753 struct mdinfo *mdi;
a951a4f7 1754 struct mdinfo *info;
33414a01 1755 int fd, err = 1;
4dd2df09 1756 char *_devnm;
33414a01
DW
1757
1758 fd = open(dev, O_RDWR|O_EXCL);
1759 if (fd < 0) {
1760 if (!quiet)
e7b84f9d 1761 pr_err("Couldn't open %s, aborting\n",
33414a01 1762 dev);
b990032d 1763 return -1;
33414a01
DW
1764 }
1765
4dd2df09
N
1766 _devnm = fd2devnm(fd);
1767 if (_devnm == NULL) {
33414a01 1768 if (!quiet)
e7b84f9d
N
1769 pr_err("Failed to determine device number for %s\n",
1770 dev);
33414a01
DW
1771 goto close_fd;
1772 }
4dd2df09 1773 strcpy(st->devnm, _devnm);
33414a01 1774
4dd2df09 1775 mdi = sysfs_read(fd, st->devnm, GET_VERSION|GET_LEVEL);
33414a01
DW
1776 if (!mdi) {
1777 if (!quiet)
e7b84f9d 1778 pr_err("Failed to read sysfs for %s\n",
33414a01
DW
1779 dev);
1780 goto close_fd;
1781 }
1782
1783 if (mdi->array.level != UnSet) {
1784 if (!quiet)
e7b84f9d 1785 pr_err("%s is not a container\n", dev);
33414a01
DW
1786 goto free_sysfs;
1787 }
1788
1789 st->ss = version_to_superswitch(mdi->text_version);
1790 if (!st->ss) {
1791 if (!quiet)
e7b84f9d
N
1792 pr_err("Operation not supported for %s metadata\n",
1793 mdi->text_version);
33414a01
DW
1794 goto free_sysfs;
1795 }
1796
4dd2df09 1797 if (st->devnm[0] == 0) {
33414a01 1798 if (!quiet)
e7b84f9d 1799 pr_err("Failed to allocate device name\n");
33414a01
DW
1800 goto free_sysfs;
1801 }
1802
db20d413 1803 if (!st->ss->load_container) {
33414a01 1804 if (!quiet)
e7b84f9d 1805 pr_err("%s is not a container\n", dev);
4dd2df09 1806 goto free_sysfs;
33414a01
DW
1807 }
1808
db20d413 1809 if (st->ss->load_container(st, fd, NULL)) {
33414a01 1810 if (!quiet)
e7b84f9d 1811 pr_err("Failed to load metadata for %s\n",
db20d413 1812 dev);
4dd2df09 1813 goto free_sysfs;
33414a01
DW
1814 }
1815
a951a4f7
N
1816 info = st->ss->container_content(st, subarray);
1817 if (!info) {
1818 if (!quiet)
e7b84f9d 1819 pr_err("Failed to find subarray-%s in %s\n",
a951a4f7
N
1820 subarray, dev);
1821 goto free_super;
1822 }
1823 free(info);
1824
33414a01
DW
1825 err = 0;
1826
1827 free_super:
1828 if (err)
1829 st->ss->free_super(st);
33414a01
DW
1830 free_sysfs:
1831 sysfs_free(mdi);
1832 close_fd:
1833 if (err)
1834 close(fd);
1835
1836 if (err)
1837 return -1;
1838 else
1839 return fd;
1840}
1841
7801ac20
N
1842int add_disk(int mdfd, struct supertype *st,
1843 struct mdinfo *sra, struct mdinfo *info)
1844{
1845 /* Add a device to an array, in one of 2 ways. */
1846 int rv;
32141c17 1847
7801ac20 1848 if (st->ss->external) {
d23534e4
DW
1849 if (info->disk.state & (1<<MD_DISK_SYNC))
1850 info->recovery_start = MaxSector;
1851 else
1852 info->recovery_start = 0;
2904b26f 1853 rv = sysfs_add_disk(sra, info, 0);
7801ac20
N
1854 if (! rv) {
1855 struct mdinfo *sd2;
f35f2525
N
1856 for (sd2 = sra->devs; sd2; sd2=sd2->next)
1857 if (sd2 == info)
1858 break;
1859 if (sd2 == NULL) {
503975b9 1860 sd2 = xmalloc(sizeof(*sd2));
f35f2525
N
1861 *sd2 = *info;
1862 sd2->next = sra->devs;
1863 sra->devs = sd2;
1864 }
7801ac20
N
1865 }
1866 } else
7801ac20
N
1867 rv = ioctl(mdfd, ADD_NEW_DISK, &info->disk);
1868 return rv;
1869}
1870
de6ae750
N
1871int remove_disk(int mdfd, struct supertype *st,
1872 struct mdinfo *sra, struct mdinfo *info)
1873{
1874 int rv;
32141c17 1875
de6ae750 1876 /* Remove the disk given by 'info' from the array */
de6ae750
N
1877 if (st->ss->external)
1878 rv = sysfs_set_str(sra, info, "slot", "none");
1879 else
de6ae750
N
1880 rv = ioctl(mdfd, HOT_REMOVE_DISK, makedev(info->disk.major,
1881 info->disk.minor));
1882 return rv;
1883}
1884
1ab9ed2a 1885int hot_remove_disk(int mdfd, unsigned long dev, int force)
2dd271fe 1886{
1ab9ed2a 1887 int cnt = force ? 500 : 5;
2dd271fe
N
1888 int ret;
1889
1890 /* HOT_REMOVE_DISK can fail with EBUSY if there are
1891 * outstanding IO requests to the device.
1892 * In this case, it can be helpful to wait a little while,
1ab9ed2a 1893 * up to 5 seconds if 'force' is set, or 50 msec if not.
2dd271fe
N
1894 */
1895 while ((ret = ioctl(mdfd, HOT_REMOVE_DISK, dev)) == -1 &&
1896 errno == EBUSY &&
1897 cnt-- > 0)
1898 usleep(10000);
1899
1900 return ret;
1901}
1902
1ab9ed2a 1903int sys_hot_remove_disk(int statefd, int force)
fdd01569 1904{
1ab9ed2a 1905 int cnt = force ? 500 : 5;
fdd01569
N
1906 int ret;
1907
1908 while ((ret = write(statefd, "remove", 6)) == -1 &&
1909 errno == EBUSY &&
1910 cnt-- > 0)
1911 usleep(10000);
1912 return ret == 6 ? 0 : -1;
1913}
1914
f35f2525
N
1915int set_array_info(int mdfd, struct supertype *st, struct mdinfo *info)
1916{
1917 /* Initialise kernel's knowledge of array.
1918 * This varies between externally managed arrays
1919 * and older kernels
1920 */
700483a2 1921 mdu_array_info_t inf;
f35f2525
N
1922 int rv;
1923
f35f2525 1924 if (st->ss->external)
700483a2 1925 return sysfs_set_array(info, 9003);
700483a2
JS
1926
1927 memset(&inf, 0, sizeof(inf));
1928 inf.major_version = info->array.major_version;
1929 inf.minor_version = info->array.minor_version;
1930 rv = md_set_array_info(mdfd, &inf);
1931
f35f2525
N
1932 return rv;
1933}
1934
1e5c6983
DW
1935unsigned long long min_recovery_start(struct mdinfo *array)
1936{
1937 /* find the minimum recovery_start in an array for metadata
1938 * formats that only record per-array recovery progress instead
1939 * of per-device
1940 */
1941 unsigned long long recovery_start = MaxSector;
1942 struct mdinfo *d;
1943
1944 for (d = array->devs; d; d = d->next)
1945 recovery_start = min(recovery_start, d->recovery_start);
1946
1947 return recovery_start;
1948}
1949
4dd2df09 1950int mdmon_pid(char *devnm)
a931db9e
NB
1951{
1952 char path[100];
1953 char pid[10];
1954 int fd;
1955 int n;
10013317 1956
4dd2df09 1957 sprintf(path, "%s/%s.pid", MDMON_DIR, devnm);
10013317 1958
24f6f99b 1959 fd = open(path, O_RDONLY | O_NOATIME, 0);
a931db9e
NB
1960
1961 if (fd < 0)
cf556303 1962 return -1;
a931db9e
NB
1963 n = read(fd, pid, 9);
1964 close(fd);
1965 if (n <= 0)
cf556303 1966 return -1;
24f6f99b 1967 return atoi(pid);
a931db9e
NB
1968}
1969
4dd2df09 1970int mdmon_running(char *devnm)
a931db9e 1971{
4dd2df09 1972 int pid = mdmon_pid(devnm);
24f6f99b 1973 if (pid <= 0)
a931db9e 1974 return 0;
24f6f99b 1975 if (kill(pid, 0) == 0)
a931db9e
NB
1976 return 1;
1977 return 0;
1978}
1979
4dd2df09 1980int start_mdmon(char *devnm)
8850ee3e 1981{
1913c325 1982 int i, skipped;
44d2e365 1983 int len;
ca3b6696 1984 pid_t pid;
9fe32043 1985 int status;
44d2e365
N
1986 char pathbuf[1024];
1987 char *paths[4] = {
1988 pathbuf,
85945e19 1989 BINDIR "/mdmon",
2f1bcf43 1990 "./mdmon",
44d2e365
N
1991 NULL
1992 };
8850ee3e 1993
40ebbb9c 1994 if (check_env("MDADM_NO_MDMON"))
8850ee3e
N
1995 return 0;
1996
9cf014ec 1997 len = readlink("/proc/self/exe", pathbuf, sizeof(pathbuf)-1);
44d2e365
N
1998 if (len > 0) {
1999 char *sl;
2000 pathbuf[len] = 0;
2001 sl = strrchr(pathbuf, '/');
2002 if (sl)
2003 sl++;
2004 else
2005 sl = pathbuf;
2006 strcpy(sl, "mdmon");
2007 } else
2008 pathbuf[0] = '\0';
2009
0f7bdf89 2010 /* First try to run systemctl */
9540cc24
N
2011 if (!check_env("MDADM_NO_SYSTEMCTL"))
2012 switch(fork()) {
2013 case 0:
2014 /* FIXME yuk. CLOSE_EXEC?? */
2015 skipped = 0;
2016 for (i = 3; skipped < 20; i++)
2017 if (close(i) < 0)
2018 skipped++;
2019 else
2020 skipped = 0;
2021
2022 /* Don't want to see error messages from
2023 * systemctl. If the service doesn't exist,
2024 * we start mdmon ourselves.
2025 */
2026 close(2);
2027 open("/dev/null", O_WRONLY);
2028 snprintf(pathbuf, sizeof(pathbuf), "mdmon@%s.service",
2029 devnm);
2030 status = execl("/usr/bin/systemctl", "systemctl",
2031 "start",
2032 pathbuf, NULL);
2033 status = execl("/bin/systemctl", "systemctl", "start",
2034 pathbuf, NULL);
2035 exit(1);
7a862a02 2036 case -1: pr_err("cannot run mdmon. Array remains readonly\n");
9540cc24
N
2037 return -1;
2038 default: /* parent - good */
2039 pid = wait(&status);
2040 if (pid >= 0 && status == 0)
2041 return 0;
2042 }
0f7bdf89
JS
2043
2044 /* That failed, try running mdmon directly */
8850ee3e
N
2045 switch(fork()) {
2046 case 0:
2047 /* FIXME yuk. CLOSE_EXEC?? */
1913c325 2048 skipped = 0;
ca3b6696 2049 for (i = 3; skipped < 20; i++)
1913c325
N
2050 if (close(i) < 0)
2051 skipped++;
2052 else
2053 skipped = 0;
2054
ca3b6696 2055 for (i = 0; paths[i]; i++)
a0963a86 2056 if (paths[i][0]) {
2f1bcf43 2057 execl(paths[i], paths[i],
4dd2df09 2058 devnm, NULL);
a0963a86 2059 }
8850ee3e 2060 exit(1);
7a862a02 2061 case -1: pr_err("cannot run mdmon. Array remains readonly\n");
8850ee3e 2062 return -1;
9fe32043
N
2063 default: /* parent - good */
2064 pid = wait(&status);
15c10423 2065 if (pid < 0 || status != 0) {
7a862a02 2066 pr_err("failed to launch mdmon. Array remains readonly\n");
9fe32043 2067 return -1;
15c10423 2068 }
8850ee3e
N
2069 }
2070 return 0;
2071}
2072
148acb7b
DW
2073__u32 random32(void)
2074{
2075 __u32 rv;
2076 int rfd = open("/dev/urandom", O_RDONLY);
2077 if (rfd < 0 || read(rfd, &rv, 4) != 4)
2078 rv = random();
2079 if (rfd >= 0)
2080 close(rfd);
2081 return rv;
2082}
2083
c5f71c24
JS
2084void random_uuid(__u8 *buf)
2085{
2086 int fd, i, len;
2087 __u32 r[4];
2088
2089 fd = open("/dev/urandom", O_RDONLY);
2090 if (fd < 0)
2091 goto use_random;
2092 len = read(fd, buf, 16);
2093 close(fd);
2094 if (len != 16)
2095 goto use_random;
2096
2097 return;
2098
2099use_random:
2100 for (i = 0; i < 4; i++)
2101 r[i] = random();
2102 memcpy(buf, r, 16);
2103}
2104
edd8d13c
NB
2105int flush_metadata_updates(struct supertype *st)
2106{
2107 int sfd;
2108 if (!st->updates) {
2109 st->update_tail = NULL;
2110 return -1;
2111 }
2112
4dd2df09 2113 sfd = connect_monitor(st->container_devnm);
edd8d13c
NB
2114 if (sfd < 0)
2115 return -1;
2116
2117 while (st->updates) {
2118 struct metadata_update *mu = st->updates;
2119 st->updates = mu->next;
2120
2121 send_message(sfd, mu, 0);
2122 wait_reply(sfd, 0);
2123 free(mu->buf);
2124 free(mu);
2125 }
2126 ack(sfd, 0);
2127 wait_reply(sfd, 0);
2128 close(sfd);
2129 st->update_tail = NULL;
2130 return 0;
2131}
2132
2133void append_metadata_update(struct supertype *st, void *buf, int len)
2134{
2135
503975b9 2136 struct metadata_update *mu = xmalloc(sizeof(*mu));
edd8d13c
NB
2137
2138 mu->buf = buf;
2139 mu->len = len;
2140 mu->space = NULL;
cb23f1f4 2141 mu->space_list = NULL;
edd8d13c
NB
2142 mu->next = NULL;
2143 *st->update_tail = mu;
2144 st->update_tail = &mu->next;
2145}
a931db9e 2146
fe6729fa
NB
2147#ifdef __TINYC__
2148/* tinyc doesn't optimize this check in ioctl.h out ... */
2149unsigned int __invalid_size_argument_for_IOC = 0;
2150#endif
2151
326727d9
AC
2152/* Pick all spares matching given criteria from a container
2153 * if min_size == 0 do not check size
2154 * if domlist == NULL do not check domains
2155 * if spare_group given add it to domains of each spare
2156 * metadata allows to test domains using metadata of destination array */
2157struct mdinfo *container_choose_spares(struct supertype *st,
fbfdcb06 2158 struct spare_criteria *criteria,
326727d9
AC
2159 struct domainlist *domlist,
2160 char *spare_group,
2161 const char *metadata, int get_one)
2162{
2163 struct mdinfo *d, **dp, *disks = NULL;
2164
2165 /* get list of all disks in container */
2166 if (st->ss->getinfo_super_disks)
2167 disks = st->ss->getinfo_super_disks(st);
2168
2169 if (!disks)
2170 return disks;
2171 /* find spare devices on the list */
2172 dp = &disks->devs;
2173 disks->array.spare_disks = 0;
2174 while (*dp) {
2175 int found = 0;
2176 d = *dp;
2177 if (d->disk.state == 0) {
2178 /* check if size is acceptable */
2179 unsigned long long dev_size;
4b57ecf6
AO
2180 unsigned int dev_sector_size;
2181 int size_valid = 0;
2182 int sector_size_valid = 0;
2183
326727d9
AC
2184 dev_t dev = makedev(d->disk.major,d->disk.minor);
2185
fbfdcb06 2186 if (!criteria->min_size ||
326727d9 2187 (dev_size_from_id(dev, &dev_size) &&
fbfdcb06 2188 dev_size >= criteria->min_size))
4b57ecf6
AO
2189 size_valid = 1;
2190
2191 if (!criteria->sector_size ||
2192 (dev_sector_size_from_id(dev, &dev_sector_size) &&
2193 criteria->sector_size == dev_sector_size))
2194 sector_size_valid = 1;
2195
2196 found = size_valid && sector_size_valid;
2197
326727d9
AC
2198 /* check if domain matches */
2199 if (found && domlist) {
4dd2df09 2200 struct dev_policy *pol = devid_policy(dev);
326727d9
AC
2201 if (spare_group)
2202 pol_add(&pol, pol_domain,
2203 spare_group, NULL);
e5508b36 2204 if (domain_test(domlist, pol, metadata) != 1)
326727d9
AC
2205 found = 0;
2206 dev_policy_free(pol);
2207 }
2208 }
2209 if (found) {
2210 dp = &d->next;
2211 disks->array.spare_disks++;
2212 if (get_one) {
2213 sysfs_free(*dp);
2214 d->next = NULL;
2215 }
2216 } else {
2217 *dp = d->next;
2218 d->next = NULL;
2219 sysfs_free(d);
2220 }
2221 }
2222 return disks;
2223}
9eafa1de
MN
2224
2225/* Checks if paths point to the same device
2226 * Returns 0 if they do.
2227 * Returns 1 if they don't.
2228 * Returns -1 if something went wrong,
2229 * e.g. paths are empty or the files
2230 * they point to don't exist */
2231int compare_paths (char* path1, char* path2)
2232{
2233 struct stat st1,st2;
2234
2235 if (path1 == NULL || path2 == NULL)
2236 return -1;
2237 if (stat(path1,&st1) != 0)
2238 return -1;
2239 if (stat(path2,&st2) != 0)
2240 return -1;
2241 if ((st1.st_ino == st2.st_ino) && (st1.st_dev == st2.st_dev))
2242 return 0;
2243 return 1;
2244}
a7dec3fd
N
2245
2246/* Make sure we can open as many devices as needed */
2247void enable_fds(int devices)
2248{
2249 unsigned int fds = 20 + devices;
2250 struct rlimit lim;
d7be7d87 2251 if (getrlimit(RLIMIT_NOFILE, &lim) != 0 || lim.rlim_cur >= fds)
a7dec3fd
N
2252 return;
2253 if (lim.rlim_max < fds)
2254 lim.rlim_max = fds;
2255 lim.rlim_cur = fds;
2256 setrlimit(RLIMIT_NOFILE, &lim);
2257}
a9c15847
N
2258
2259int in_initrd(void)
2260{
2261 /* This is based on similar function in systemd. */
2262 struct statfs s;
76d0f188
JS
2263 /* statfs.f_type is signed long on s390x and MIPS, causing all
2264 sorts of sign extension problems with RAMFS_MAGIC being
2265 defined as 0x858458f6 */
a9c15847 2266 return statfs("/", &s) >= 0 &&
7ac5d47e 2267 ((unsigned long)s.f_type == TMPFS_MAGIC ||
76d0f188
JS
2268 ((unsigned long)s.f_type & 0xFFFFFFFFUL) ==
2269 ((unsigned long)RAMFS_MAGIC & 0xFFFFFFFFUL));
a9c15847 2270}
8832342d
N
2271
2272void reopen_mddev(int mdfd)
2273{
2274 /* Re-open without any O_EXCL, but keep
2275 * the same fd
2276 */
2277 char *devnm;
2278 int fd;
2279 devnm = fd2devnm(mdfd);
2280 close(mdfd);
2281 fd = open_dev(devnm);
2282 if (fd >= 0 && fd != mdfd)
2283 dup2(fd, mdfd);
2284}
7716570e 2285
e80357f8
GJ
2286static struct cmap_hooks *cmap_hooks = NULL;
2287static int is_cmap_hooks_ready = 0;
7716570e 2288
e80357f8
GJ
2289void set_cmap_hooks(void)
2290{
2291 cmap_hooks = xmalloc(sizeof(struct cmap_hooks));
2292 cmap_hooks->cmap_handle = dlopen("libcmap.so.4", RTLD_NOW | RTLD_LOCAL);
2293 if (!cmap_hooks->cmap_handle)
2294 return;
7716570e 2295
b7a462e5
JS
2296 cmap_hooks->initialize =
2297 dlsym(cmap_hooks->cmap_handle, "cmap_initialize");
2298 cmap_hooks->get_string =
2299 dlsym(cmap_hooks->cmap_handle, "cmap_get_string");
e80357f8 2300 cmap_hooks->finalize = dlsym(cmap_hooks->cmap_handle, "cmap_finalize");
7716570e 2301
e80357f8
GJ
2302 if (!cmap_hooks->initialize || !cmap_hooks->get_string ||
2303 !cmap_hooks->finalize)
2304 dlclose(cmap_hooks->cmap_handle);
2305 else
2306 is_cmap_hooks_ready = 1;
2307}
7716570e 2308
e80357f8
GJ
2309int get_cluster_name(char **cluster_name)
2310{
2311 int rv = -1;
2312 cmap_handle_t handle;
7716570e 2313
e80357f8
GJ
2314 if (!is_cmap_hooks_ready)
2315 return rv;
7716570e 2316
e80357f8 2317 rv = cmap_hooks->initialize(&handle);
7716570e
GJ
2318 if (rv != CS_OK)
2319 goto out;
2320
e80357f8 2321 rv = cmap_hooks->get_string(handle, "totem.cluster_name", cluster_name);
7716570e
GJ
2322 if (rv != CS_OK) {
2323 free(*cluster_name);
2324 rv = -1;
2325 goto name_err;
2326 }
2327
2328 rv = 0;
2329name_err:
e80357f8 2330 cmap_hooks->finalize(handle);
7716570e 2331out:
7716570e
GJ
2332 return rv;
2333}
d15a1f72
GJ
2334
2335void set_dlm_hooks(void)
2336{
2337 dlm_hooks = xmalloc(sizeof(struct dlm_hooks));
2338 dlm_hooks->dlm_handle = dlopen("libdlm_lt.so.3", RTLD_NOW | RTLD_LOCAL);
2339 if (!dlm_hooks->dlm_handle)
2340 return;
2341
1b7eb962
GJ
2342 dlm_hooks->open_lockspace =
2343 dlsym(dlm_hooks->dlm_handle, "dlm_open_lockspace");
b7a462e5
JS
2344 dlm_hooks->create_lockspace =
2345 dlsym(dlm_hooks->dlm_handle, "dlm_create_lockspace");
2346 dlm_hooks->release_lockspace =
2347 dlsym(dlm_hooks->dlm_handle, "dlm_release_lockspace");
d15a1f72 2348 dlm_hooks->ls_lock = dlsym(dlm_hooks->dlm_handle, "dlm_ls_lock");
1b7eb962
GJ
2349 dlm_hooks->ls_unlock_wait =
2350 dlsym(dlm_hooks->dlm_handle, "dlm_ls_unlock_wait");
d15a1f72
GJ
2351 dlm_hooks->ls_get_fd = dlsym(dlm_hooks->dlm_handle, "dlm_ls_get_fd");
2352 dlm_hooks->dispatch = dlsym(dlm_hooks->dlm_handle, "dlm_dispatch");
2353
1b7eb962
GJ
2354 if (!dlm_hooks->open_lockspace || !dlm_hooks->create_lockspace ||
2355 !dlm_hooks->ls_lock || !dlm_hooks->ls_unlock_wait ||
2356 !dlm_hooks->release_lockspace || !dlm_hooks->ls_get_fd ||
2357 !dlm_hooks->dispatch)
d15a1f72
GJ
2358 dlclose(dlm_hooks->dlm_handle);
2359 else
2360 is_dlm_hooks_ready = 1;
2361}
e80357f8
GJ
2362
2363void set_hooks(void)
2364{
2365 set_dlm_hooks();
2366 set_cmap_hooks();
2367}
b2514242
PB
2368
2369int zero_disk_range(int fd, unsigned long long sector, size_t count)
2370{
2371 int ret = 0;
2372 int fd_zero;
2373 void *addr = NULL;
2374 size_t written = 0;
2375 size_t len = count * 512;
2376 ssize_t n;
2377
2378 fd_zero = open("/dev/zero", O_RDONLY);
2379 if (fd_zero < 0) {
2380 pr_err("Cannot open /dev/zero\n");
2381 return -1;
2382 }
2383
2384 if (lseek64(fd, sector * 512, SEEK_SET) < 0) {
2385 ret = -errno;
2386 pr_err("Failed to seek offset for zeroing\n");
2387 goto out;
2388 }
2389
2390 addr = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd_zero, 0);
2391
2392 if (addr == MAP_FAILED) {
2393 ret = -errno;
2394 pr_err("Mapping /dev/zero failed\n");
2395 goto out;
2396 }
2397
2398 do {
2399 n = write(fd, addr + written, len - written);
2400 if (n < 0) {
2401 if (errno == EINTR)
2402 continue;
2403 ret = -errno;
2404 pr_err("Zeroing disk range failed\n");
2405 break;
2406 }
2407 written += n;
2408 } while (written != len);
2409
2410 munmap(addr, len);
2411
2412out:
2413 close(fd_zero);
2414 return ret;
2415}