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