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