2 * mdadm - manage Linux "md" devices aka RAID arrays.
4 * Copyright (C) 2001-2013 Neil Brown <neilb@suse.de>
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.
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.
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
22 * Email: <neilb@suse.de>
29 #include <sys/socket.h>
30 #include <sys/utsname.h>
33 #include <sys/resource.h>
36 #include <linux/magic.h>
44 * following taken from linux/blkpg.h because they aren't
45 * anywhere else and it isn't safe to #include linux/ * stuff.
48 #define BLKPG _IO(0x12,105)
50 /* The argument structure */
51 struct blkpg_ioctl_arg
{
58 /* The subfunctions (for the op field) */
59 #define BLKPG_ADD_PARTITION 1
60 #define BLKPG_DEL_PARTITION 2
62 /* Sizes of name fields. Unused at present. */
63 #define BLKPG_DEVNAMELTH 64
64 #define BLKPG_VOLNAMELTH 64
66 /* The data structure for ADD_PARTITION and DEL_PARTITION */
67 struct blkpg_partition
{
68 long long start
; /* starting offset in bytes */
69 long long length
; /* length in bytes */
70 int pno
; /* partition number */
71 char devname
[BLKPG_DEVNAMELTH
]; /* partition name, like sda5 or c0d1p2,
72 to be used in kernel messages */
73 char volname
[BLKPG_VOLNAMELTH
]; /* volume label */
78 /* Force a compilation error if condition is true */
79 #define BUILD_BUG_ON(condition) ((void)BUILD_BUG_ON_ZERO(condition))
81 /* Force a compilation error if condition is true, but also produce a
82 result (of value 0 and type size_t), so the expression can be used
83 e.g. in a structure initializer (or where-ever else comma expressions
85 #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
87 static int is_dlm_hooks_ready
= 0;
89 int dlm_funs_ready(void)
91 return is_dlm_hooks_ready
? 1 : 0;
94 static struct dlm_hooks
*dlm_hooks
= NULL
;
95 struct dlm_lock_resource
*dlm_lock_res
= NULL
;
96 static int ast_called
= 0;
98 struct dlm_lock_resource
{
100 struct dlm_lksb lksb
;
103 /* Using poll(2) to wait for and dispatch ASTs */
104 static int poll_for_ast(dlm_lshandle_t ls
)
108 pfd
.fd
= dlm_hooks
->ls_get_fd(ls
);
113 if (poll(&pfd
, 1, 0) < 0)
118 dlm_hooks
->dispatch(dlm_hooks
->ls_get_fd(ls
));
125 static void dlm_ast(void *arg
)
130 static char *cluster_name
= NULL
;
131 /* Create the lockspace, take bitmapXXX locks on all the bitmaps. */
132 int cluster_get_dlmlock(void)
136 int flags
= LKF_NOQUEUE
;
139 if (!dlm_funs_ready()) {
140 pr_err("Something wrong with dlm library\n");
144 ret
= get_cluster_name(&cluster_name
);
146 pr_err("The md can't get cluster name\n");
150 dlm_lock_res
= xmalloc(sizeof(struct dlm_lock_resource
));
151 dlm_lock_res
->ls
= dlm_hooks
->open_lockspace(cluster_name
);
152 if (!dlm_lock_res
->ls
) {
153 dlm_lock_res
->ls
= dlm_hooks
->create_lockspace(cluster_name
, O_RDWR
);
154 if (!dlm_lock_res
->ls
) {
155 pr_err("%s failed to create lockspace\n", cluster_name
);
159 pr_err("open existed %s lockspace\n", cluster_name
);
162 snprintf(str
, 64, "bitmap%s", cluster_name
);
164 ret
= dlm_hooks
->ls_lock(dlm_lock_res
->ls
, LKM_PWMODE
,
165 &dlm_lock_res
->lksb
, flags
, str
, strlen(str
),
166 0, dlm_ast
, dlm_lock_res
, NULL
, NULL
);
168 pr_err("error %d when get PW mode on lock %s\n", errno
, str
);
169 /* let's try several times if EAGAIN happened */
170 if (dlm_lock_res
->lksb
.sb_status
== EAGAIN
&& retry_count
< 10) {
171 sleep_for(10, 0, true);
175 dlm_hooks
->release_lockspace(cluster_name
, dlm_lock_res
->ls
, 1);
179 /* Wait for it to complete */
180 poll_for_ast(dlm_lock_res
->ls
);
182 if (dlm_lock_res
->lksb
.sb_status
) {
183 pr_err("failed to lock cluster\n");
189 int cluster_release_dlmlock(void)
196 if (!dlm_lock_res
->lksb
.sb_lkid
)
199 ret
= dlm_hooks
->ls_unlock_wait(dlm_lock_res
->ls
,
200 dlm_lock_res
->lksb
.sb_lkid
, 0,
201 &dlm_lock_res
->lksb
);
203 pr_err("error %d happened when unlock\n", errno
);
204 /* XXX make sure the lock is unlocked eventually */
208 /* Wait for it to complete */
209 poll_for_ast(dlm_lock_res
->ls
);
211 errno
= dlm_lock_res
->lksb
.sb_status
;
212 if (errno
!= EUNLOCK
) {
213 pr_err("error %d happened in ast when unlock lockspace\n",
215 /* XXX make sure the lockspace is unlocked eventually */
219 ret
= dlm_hooks
->release_lockspace(cluster_name
, dlm_lock_res
->ls
, 1);
221 pr_err("error %d happened when release lockspace\n", errno
);
222 /* XXX make sure the lockspace is released eventually */
231 int md_array_valid(int fd
)
236 sra
= sysfs_read(fd
, NULL
, GET_ARRAY_STATE
);
238 if (sra
->array_state
!= ARRAY_UNKNOWN_STATE
)
246 * GET_ARRAY_INFO doesn't provide access to the proper state
247 * information, so fallback to a basic check for raid_disks != 0
249 ret
= ioctl(fd
, RAID_VERSION
);
255 int md_array_active(int fd
)
258 struct mdu_array_info_s array
;
261 sra
= sysfs_read(fd
, NULL
, GET_ARRAY_STATE
);
263 if (!md_array_is_active(sra
))
269 * GET_ARRAY_INFO doesn't provide access to the proper state
270 * information, so fallback to a basic check for raid_disks != 0
272 ret
= md_get_array_info(fd
, &array
);
278 int md_array_is_active(struct mdinfo
*info
)
280 return (info
->array_state
!= ARRAY_CLEAR
&&
281 info
->array_state
!= ARRAY_INACTIVE
&&
282 info
->array_state
!= ARRAY_UNKNOWN_STATE
);
286 * Get array info from the kernel. Longer term we want to deprecate the
287 * ioctl and get it from sysfs.
289 int md_get_array_info(int fd
, struct mdu_array_info_s
*array
)
291 return ioctl(fd
, GET_ARRAY_INFO
, array
);
297 int md_set_array_info(int fd
, struct mdu_array_info_s
*array
)
299 return ioctl(fd
, SET_ARRAY_INFO
, array
);
303 * Get disk info from the kernel.
305 int md_get_disk_info(int fd
, struct mdu_disk_info_s
*disk
)
307 return ioctl(fd
, GET_DISK_INFO
, disk
);
310 int get_linux_version()
314 int a
= 0, b
= 0,c
= 0;
319 a
= strtoul(cp
, &cp
, 10);
321 b
= strtoul(cp
+1, &cp
, 10);
323 c
= strtoul(cp
+1, &cp
, 10);
325 return (a
*1000000)+(b
*1000)+c
;
328 int mdadm_version(char *version
)
336 cp
= strchr(version
, '-');
337 if (!cp
|| *(cp
+1) != ' ' || *(cp
+2) != 'v')
340 a
= strtoul(cp
, &cp
, 10);
343 b
= strtoul(cp
+1, &cp
, 10);
345 c
= strtoul(cp
+1, &cp
, 10);
348 if (*cp
!= ' ' && *cp
!= '-')
350 return (a
*1000000)+(b
*1000)+c
;
353 unsigned long long parse_size(char *size
)
355 /* parse 'size' which should be a number optionally
356 * followed by 'K', 'M'. 'G' or 'T'.
357 * Without a suffix, K is assumed.
358 * Number returned is in sectors (half-K)
359 * INVALID_SECTORS returned on error.
362 long long s
= strtoll(size
, &c
, 10);
376 s
*= 1024 * 1024 * 2;
380 s
*= 1024 * 1024 * 1024 * 2LL;
382 case 's': /* sectors */
393 int is_near_layout_10(int layout
)
397 fc
= (layout
>> 8) & 255;
398 fo
= layout
& (1 << 16);
399 if (fc
> 1 || fo
> 0)
404 int parse_layout_10(char *layout
)
408 /* Parse the layout string for raid10 */
409 /* 'f', 'o' or 'n' followed by a number <= raid_disks */
410 if ((layout
[0] != 'n' && layout
[0] != 'f' && layout
[0] != 'o') ||
411 (copies
= strtoul(layout
+1, &cp
, 10)) < 1 ||
415 if (layout
[0] == 'n')
417 else if (layout
[0] == 'o')
418 rv
= 0x10000 + (copies
<<8) + 1;
420 rv
= 1 + (copies
<<8);
424 int parse_layout_faulty(char *layout
)
432 /* Parse the layout string for 'faulty' */
433 ln
= strcspn(layout
, "0123456789");
436 mode
= map_name(faultylayout
, m
);
442 return mode
| (atoi(layout
+ln
)<< ModeShift
);
445 int parse_cluster_confirm_arg(char *input
, char **devname
, int *slot
)
448 *slot
= strtoul(input
, &dev
, 10);
449 if (dev
== input
|| dev
[0] != ':')
455 void remove_partitions(int fd
)
457 /* remove partitions from this block devices.
458 * This is used for components added to an array
460 #ifdef BLKPG_DEL_PARTITION
461 struct blkpg_ioctl_arg a
;
462 struct blkpg_partition p
;
464 a
.op
= BLKPG_DEL_PARTITION
;
466 a
.datalen
= sizeof(p
);
468 memset(a
.data
, 0, a
.datalen
);
469 for (p
.pno
= 0; p
.pno
< 16; p
.pno
++)
470 ioctl(fd
, BLKPG
, &a
);
474 int test_partition(int fd
)
476 /* Check if fd is a whole-disk or a partition.
477 * BLKPG will return EINVAL on a partition, and BLKPG_DEL_PARTITION
478 * will return ENXIO on an invalid partition number.
480 struct blkpg_ioctl_arg a
;
481 struct blkpg_partition p
;
482 a
.op
= BLKPG_DEL_PARTITION
;
484 a
.datalen
= sizeof(p
);
486 memset(a
.data
, 0, a
.datalen
);
488 if (ioctl(fd
, BLKPG
, &a
) == 0)
489 /* Very unlikely, but not a partition */
491 if (errno
== ENXIO
|| errno
== ENOTTY
)
492 /* not a partition */
498 int test_partition_from_id(dev_t id
)
503 sprintf(buf
, "%d:%d", major(id
), minor(id
));
504 fd
= dev_open(buf
, O_RDONLY
);
507 rv
= test_partition(fd
);
512 int enough(int level
, int raid_disks
, int layout
, int clean
, char *avail
)
521 for (i
= 0; i
< raid_disks
; i
++)
522 avail_disks
+= !!avail
[i
];
526 /* This is the tricky one - we need to check
527 * which actual disks are present.
529 copies
= (layout
& 255) * ((layout
>> 8) & 255);
532 /* there must be one of the 'copies' form 'first' */
539 this = (this + 1) % raid_disks
;
543 first
= (first
+ (layout
& 255)) % raid_disks
;
544 } while (first
!= 0);
547 case LEVEL_MULTIPATH
:
548 return avail_disks
>= 1;
551 return avail_disks
== raid_disks
;
553 return avail_disks
>= 1;
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
564 return avail_disks
>= raid_disks
- 1;
566 return avail_disks
>= raid_disks
;
569 return avail_disks
>= raid_disks
- 2;
571 return avail_disks
>= raid_disks
;
577 char *__fname_from_uuid(int id
[4], int swap
, char *buf
, char sep
)
584 copy_uuid(uuid
, id
, swap
);
585 for (i
= 0; i
< 4; i
++) {
588 for (j
= 3; j
>= 0; j
--) {
589 sprintf(c
,"%02x", (unsigned char) uuid
[j
+4*i
]);
598 * fname_from_uuid() - generate uuid string. Should not be used with super1.
599 * @info: info with uuid
602 * This routine should not be used with super1. See detail_fname_from_uuid() for details. It does
603 * not use superswitch swapuuid as it should be 0 but it has to do UUID conversion if host is big
604 * endian- left for backward compatibility.
606 char *fname_from_uuid(struct mdinfo
*info
, char *buf
)
608 #if __BYTE_ORDER == BIG_ENDIAN
609 return __fname_from_uuid(info
->uuid
, true, buf
, ':');
611 return __fname_from_uuid(info
->uuid
, false, buf
, ':');
615 int check_ext2(int fd
, char *name
)
618 * Check for an ext2fs file system.
619 * Superblock is always 1K at 1K offset
621 * s_magic is le16 at 56 == 0xEF53
622 * report mtime - le32 at 44
624 * logblksize - le32 at 24
626 unsigned char sb
[1024];
628 unsigned long long size
;
630 if (lseek(fd
, 1024,0)!= 1024)
632 if (read(fd
, sb
, 1024)!= 1024)
634 if (sb
[56] != 0x53 || sb
[57] != 0xef)
637 mtime
= sb
[44]|(sb
[45]|(sb
[46]|sb
[47]<<8)<<8)<<8;
638 bsize
= sb
[24]|(sb
[25]|(sb
[26]|sb
[27]<<8)<<8)<<8;
639 size
= sb
[4]|(sb
[5]|(sb
[6]|sb
[7]<<8)<<8)<<8;
641 pr_info("%s appears to contain an ext2fs file system\n",
643 pr_info("size=%lluK mtime=%s", size
, ctime(&mtime
));
647 int check_reiser(int fd
, char *name
)
650 * superblock is at 64K
652 * Magic string "ReIsErFs" or "ReIsEr2Fs" at 52
655 unsigned char sb
[1024];
656 unsigned long long size
;
657 if (lseek(fd
, 64*1024, 0) != 64*1024)
659 if (read(fd
, sb
, 1024) != 1024)
661 if (strncmp((char*)sb
+52, "ReIsErFs",8) != 0 &&
662 strncmp((char*)sb
+52, "ReIsEr2Fs",9) != 0)
664 pr_err("%s appears to contain a reiserfs file system\n",name
);
665 size
= sb
[0]|(sb
[1]|(sb
[2]|sb
[3]<<8)<<8)<<8;
666 cont_err("size = %lluK\n", size
*4);
671 int check_raid(int fd
, char *name
)
676 struct supertype
*st
= guess_super(fd
);
680 if (st
->ss
->add_to_super
!= NULL
) {
681 st
->ss
->load_super(st
, fd
, name
);
682 /* Looks like a raid array .. */
683 pr_err("%s appears to be part of a raid array:\n", name
);
684 st
->ss
->getinfo_super(st
, &info
, NULL
);
685 st
->ss
->free_super(st
);
686 crtime
= info
.array
.ctime
;
687 level
= map_num(pers
, info
.array
.level
);
690 cont_err("level=%s devices=%d ctime=%s",
691 level
, info
.array
.raid_disks
, ctime(&crtime
));
693 /* Looks like GPT or MBR */
694 pr_err("partition table exists on %s\n", name
);
699 int fstat_is_blkdev(int fd
, char *devname
, dev_t
*rdev
)
703 if (fstat(fd
, &stb
) != 0) {
704 pr_err("fstat failed for %s: %s\n", devname
, strerror(errno
));
707 if ((S_IFMT
& stb
.st_mode
) != S_IFBLK
) {
708 pr_err("%s is not a block device.\n", devname
);
716 int stat_is_blkdev(char *devname
, dev_t
*rdev
)
720 if (stat(devname
, &stb
) != 0) {
721 pr_err("stat failed for %s: %s\n", devname
, strerror(errno
));
724 if ((S_IFMT
& stb
.st_mode
) != S_IFBLK
) {
725 pr_err("%s is not a block device.\n", devname
);
734 * ask() - prompt user for "yes/no" dialog.
735 * @mesg: message to be printed, without '?' sign.
736 * Returns: 1 if 'Y/y', 0 otherwise.
738 * The default value is 'N/n', thus the caps on "N" on prompt.
744 fprintf(stderr
, "%s [y/N]? ", mesg
);
746 if (fgets(buf
, 3, stdin
) == NULL
)
748 if (strlen(buf
) == 1) {
749 pr_err("assuming no.\n");
754 if (toupper(buf
[0]) == 'Y')
756 if (toupper(buf
[0]) == 'N')
759 pr_err("bad option.\n");
763 unsigned long calc_csum(void *super
, int bytes
)
765 unsigned long long newcsum
= 0;
768 unsigned int *superc
= (unsigned int*) super
;
770 for(i
= 0; i
< bytes
/4; i
++)
771 newcsum
+= superc
[i
];
772 csum
= (newcsum
& 0xffffffff) + (newcsum
>>32);
774 /* The in-kernel checksum calculation is always 16bit on
775 * the alpha, though it is 32 bit on i386...
776 * I wonder what it is elsewhere... (it uses an API in
777 * a way that it shouldn't).
779 csum
= (csum
& 0xffff) + (csum
>> 16);
780 csum
= (csum
& 0xffff) + (csum
>> 16);
785 char *human_size(long long bytes
)
789 /* We convert bytes to either centi-M{ega,ibi}bytes,
790 * centi-G{igi,ibi}bytes or centi-T{era,ebi}bytes
791 * with appropriate rounding, and then print
792 * 1/100th of those as a decimal.
793 * We allow upto 2048Megabytes before converting to
794 * gigabytes and 2048Gigabytes before converting to
795 * terabytes, as that shows more precision and isn't
796 * too large a number.
799 if (bytes
< 5000*1024)
801 else if (bytes
< 2*1024LL*1024LL*1024LL) {
802 long cMiB
= (bytes
* 200LL / (1LL<<20) + 1) / 2;
803 long cMB
= (bytes
/ ( 1000000LL / 200LL ) +1) /2;
804 snprintf(buf
, sizeof(buf
), " (%ld.%02ld MiB %ld.%02ld MB)",
805 cMiB
/100, cMiB
% 100, cMB
/100, cMB
% 100);
806 } else if (bytes
< 2*1024LL*1024LL*1024LL*1024LL) {
807 long cGiB
= (bytes
* 200LL / (1LL<<30) +1) / 2;
808 long cGB
= (bytes
/ (1000000000LL/200LL ) +1) /2;
809 snprintf(buf
, sizeof(buf
), " (%ld.%02ld GiB %ld.%02ld GB)",
810 cGiB
/100, cGiB
% 100, cGB
/100, cGB
% 100);
812 long cTiB
= (bytes
* 200LL / (1LL<<40) + 1) / 2;
813 long cTB
= (bytes
/ (1000000000000LL / 200LL) + 1) / 2;
814 snprintf(buf
, sizeof(buf
), " (%ld.%02ld TiB %ld.%02ld TB)",
815 cTiB
/100, cTiB
% 100, cTB
/100, cTB
% 100);
820 char *human_size_brief(long long bytes
, int prefix
)
824 /* We convert bytes to either centi-M{ega,ibi}bytes,
825 * centi-G{igi,ibi}bytes or centi-T{era,ebi}bytes
826 * with appropriate rounding, and then print
827 * 1/100th of those as a decimal.
828 * We allow upto 2048Megabytes before converting to
829 * gigabytes and 2048Gigabytes before converting to
830 * terabytes, as that shows more precision and isn't
831 * too large a number.
833 * If prefix == IEC, we mean prefixes like kibi,mebi,gibi etc.
834 * If prefix == JEDEC, we mean prefixes like kilo,mega,giga etc.
837 if (bytes
< 5000*1024)
839 else if (prefix
== IEC
) {
840 if (bytes
< 2*1024LL*1024LL*1024LL) {
841 long cMiB
= (bytes
* 200LL / (1LL<<20) +1) /2;
842 snprintf(buf
, sizeof(buf
), "%ld.%02ldMiB",
843 cMiB
/100, cMiB
% 100);
844 } else if (bytes
< 2*1024LL*1024LL*1024LL*1024LL) {
845 long cGiB
= (bytes
* 200LL / (1LL<<30) +1) /2;
846 snprintf(buf
, sizeof(buf
), "%ld.%02ldGiB",
847 cGiB
/100, cGiB
% 100);
849 long cTiB
= (bytes
* 200LL / (1LL<<40) + 1) / 2;
850 snprintf(buf
, sizeof(buf
), "%ld.%02ldTiB",
851 cTiB
/100, cTiB
% 100);
854 else if (prefix
== JEDEC
) {
855 if (bytes
< 2*1024LL*1024LL*1024LL) {
856 long cMB
= (bytes
/ ( 1000000LL / 200LL ) +1) /2;
857 snprintf(buf
, sizeof(buf
), "%ld.%02ldMB",
859 } else if (bytes
< 2*1024LL*1024LL*1024LL*1024LL) {
860 long cGB
= (bytes
/ (1000000000LL/200LL ) +1) /2;
861 snprintf(buf
, sizeof(buf
), "%ld.%02ldGB",
864 long cTB
= (bytes
/ (1000000000000LL / 200LL) + 1) / 2;
865 snprintf(buf
, sizeof(buf
), "%ld.%02ldTB",
875 void print_r10_layout(int layout
)
877 int near
= layout
& 255;
878 int far
= (layout
>> 8) & 255;
879 int offset
= (layout
&0x10000);
883 printf("%s near=%d", sep
, near
);
887 printf("%s %s=%d", sep
, offset
?"offset":"far", far
);
889 printf("NO REDUNDANCY");
892 unsigned long long calc_array_size(int level
, int raid_disks
, int layout
,
893 int chunksize
, unsigned long long devsize
)
897 devsize
&= ~(unsigned long long)((chunksize
>>9)-1);
898 return get_data_disks(level
, layout
, raid_disks
) * devsize
;
901 int get_data_disks(int level
, int layout
, int raid_disks
)
905 case 0: data_disks
= raid_disks
;
907 case 1: data_disks
= 1;
910 case 5: data_disks
= raid_disks
- 1;
912 case 6: data_disks
= raid_disks
- 2;
914 case 10: data_disks
= raid_disks
/ (layout
& 255) / ((layout
>>8)&255);
921 dev_t
devnm2devid(char *devnm
)
923 /* First look in /sys/block/$DEVNM/dev for %d:%d
924 * If that fails, try parsing out a number
931 snprintf(path
, sizeof(path
), "/sys/block/%s/dev", devnm
);
932 fd
= open(path
, O_RDONLY
);
935 int n
= read(fd
, buf
, sizeof(buf
));
939 if (n
> 0 && sscanf(buf
, "%d:%d\n", &mjr
, &mnr
) == 2)
940 return makedev(mjr
, mnr
);
942 if (strncmp(devnm
, "md_d", 4) == 0 &&
944 (mnr
= strtoul(devnm
+4, &ep
, 10)) >= 0 &&
945 ep
> devnm
&& *ep
== 0)
946 return makedev(get_mdp_major(), mnr
<< MdpMinorShift
);
948 if (strncmp(devnm
, "md", 2) == 0 &&
950 (mnr
= strtoul(devnm
+2, &ep
, 10)) >= 0 &&
951 ep
> devnm
&& *ep
== 0)
952 return makedev(MD_MAJOR
, mnr
);
958 * is_devname_numbered() - helper for numbered devname verification.
959 * @devname: path or name to check.
960 * @pref: expected devname prefix.
961 * @pref_len: prefix len.
963 static bool is_devname_numbered(const char *devname
, const char *pref
, const int pref_len
)
967 assert(devname
&& pref
);
969 if (strncmp(devname
, pref
, pref_len
) != 0)
972 if (parse_num(&val
, devname
+ pref_len
) != 0)
975 /* Allow any number that represents a valid minor number */
976 if (val
>= (1 << 20))
983 * is_devname_md_numbered() - check if &devname is numbered MD device (md).
984 * @devname: path or name to check.
986 bool is_devname_md_numbered(const char *devname
)
988 return is_devname_numbered(devname
, DEV_NUM_PREF
, DEV_NUM_PREF_LEN
);
992 * is_devname_md_d_numbered() - check if &devname is secondary numbered MD device (md_d).
993 * @devname: path or name to check.
995 bool is_devname_md_d_numbered(const char *devname
)
997 static const char d_dev
[] = DEV_NUM_PREF
"_d";
999 return is_devname_numbered(devname
, d_dev
, sizeof(d_dev
) - 1);
1003 * get_md_name() - Get main dev node of the md device.
1004 * @devnm: Md device name or path.
1006 * Function checks if the full name was passed and returns md name
1007 * if it is the MD device.
1009 * Return: Main dev node of the md device or NULL if not found.
1011 char *get_md_name(char *devnm
)
1013 static char devname
[NAME_MAX
];
1016 if (strncmp(devnm
, "/dev/", 5) == 0)
1017 snprintf(devname
, sizeof(devname
), "%s", devnm
);
1019 snprintf(devname
, sizeof(devname
), "/dev/%s", devnm
);
1021 if (!is_mddev(devname
))
1023 if (stat(devname
, &stb
) == 0 && (S_IFMT
&stb
.st_mode
) == S_IFBLK
)
1029 void put_md_name(char *name
)
1031 if (strncmp(name
, "/dev/.tmp.md", 12) == 0)
1035 int get_maj_min(char *dev
, int *major
, int *minor
)
1038 *major
= strtoul(dev
, &e
, 0);
1039 return (e
> dev
&& *e
== ':' && e
[1] &&
1040 (*minor
= strtoul(e
+1, &e
, 0)) >= 0 &&
1045 * is_bit_set() - get bit value by index.
1047 * @index: index of the bit (LSB numbering).
1049 * Return: bit value.
1051 bool is_bit_set(int *val
, unsigned char index
)
1053 if ((*val
) & (1 << index
))
1058 int dev_open(char *dev
, int flags
)
1060 /* like 'open', but if 'dev' matches %d:%d, create a temp
1061 * block device and open that
1072 if (get_maj_min(dev
, &major
, &minor
)) {
1073 snprintf(devname
, sizeof(devname
), "/dev/.tmp.md.%d:%d:%d",
1074 (int)getpid(), major
, minor
);
1075 if (mknod(devname
, S_IFBLK
|0600, makedev(major
, minor
)) == 0) {
1076 fd
= open(devname
, flags
);
1080 fd
= open(dev
, flags
);
1084 int open_dev_flags(char *devnm
, int flags
)
1089 devid
= devnm2devid(devnm
);
1090 sprintf(buf
, "%d:%d", major(devid
), minor(devid
));
1091 return dev_open(buf
, flags
);
1094 int open_dev(char *devnm
)
1096 return open_dev_flags(devnm
, O_RDONLY
);
1099 int open_dev_excl(char *devnm
)
1104 dev_t devid
= devnm2devid(devnm
);
1105 unsigned int delay
= 1; // miliseconds
1107 sprintf(buf
, "%d:%d", major(devid
), minor(devid
));
1108 for (i
= 0; i
< 25; i
++) {
1109 int fd
= dev_open(buf
, flags
|O_EXCL
);
1112 if (errno
== EACCES
&& flags
== O_RDWR
) {
1118 sleep_for(0, MSEC_TO_NSEC(delay
), true);
1125 int same_dev(char *one
, char *two
)
1127 struct stat st1
, st2
;
1128 if (stat(one
, &st1
) != 0)
1130 if (stat(two
, &st2
) != 0)
1132 if ((st1
.st_mode
& S_IFMT
) != S_IFBLK
)
1134 if ((st2
.st_mode
& S_IFMT
) != S_IFBLK
)
1136 return st1
.st_rdev
== st2
.st_rdev
;
1139 void wait_for(char *dev
, int fd
)
1142 struct stat stb_want
;
1143 unsigned int delay
= 1; // miliseconds
1145 if (fstat(fd
, &stb_want
) != 0 ||
1146 (stb_want
.st_mode
& S_IFMT
) != S_IFBLK
)
1149 for (i
= 0; i
< 25; i
++) {
1151 if (stat(dev
, &stb
) == 0 &&
1152 (stb
.st_mode
& S_IFMT
) == S_IFBLK
&&
1153 (stb
.st_rdev
== stb_want
.st_rdev
))
1155 sleep_for(0, MSEC_TO_NSEC(delay
), true);
1160 pr_err("timeout waiting for %s\n", dev
);
1163 struct superswitch
*superlist
[] =
1166 &super_ddf
, &super_imsm
,
1171 struct supertype
*super_by_fd(int fd
, char **subarrayp
)
1173 mdu_array_info_t array
;
1176 struct supertype
*st
= NULL
;
1181 char *subarray
= NULL
;
1182 char container
[32] = "";
1185 devnm
= fd2devnm(fd
);
1189 sra
= sysfs_read(fd
, NULL
, GET_VERSION
);
1192 vers
= sra
->array
.major_version
;
1193 minor
= sra
->array
.minor_version
;
1194 verstr
= sra
->text_version
;
1196 if (md_get_array_info(fd
, &array
))
1197 array
.major_version
= array
.minor_version
= 0;
1198 vers
= array
.major_version
;
1199 minor
= array
.minor_version
;
1204 sprintf(version
, "%d.%d", vers
, minor
);
1207 if (minor
== -2 && is_subarray(verstr
)) {
1208 char *dev
= verstr
+1;
1210 subarray
= strchr(dev
, '/');
1213 subarray
= xstrdup(subarray
);
1215 snprintf(container
, sizeof(container
), "%s", dev
);
1217 sra
= sysfs_read(-1, container
, GET_VERSION
);
1218 if (sra
&& sra
->text_version
[0])
1219 verstr
= sra
->text_version
;
1221 verstr
= "-no-metadata-";
1224 for (i
= 0; st
== NULL
&& superlist
[i
]; i
++)
1225 st
= superlist
[i
]->match_metadata_desc(verstr
);
1231 *subarrayp
= subarray
;
1232 strcpy(st
->container_devnm
, container
);
1233 strncpy(st
->devnm
, devnm
, MD_NAME_MAX
- 1);
1240 struct supertype
*dup_super(struct supertype
*orig
)
1242 struct supertype
*st
;
1246 st
= xcalloc(1, sizeof(*st
));
1248 st
->max_devs
= orig
->max_devs
;
1249 st
->minor_version
= orig
->minor_version
;
1250 st
->ignore_hw_compat
= orig
->ignore_hw_compat
;
1251 st
->data_offset
= orig
->data_offset
;
1257 struct supertype
*guess_super_type(int fd
, enum guess_types guess_type
)
1259 /* try each load_super to find the best match,
1260 * and return the best superswitch
1262 struct superswitch
*ss
;
1263 struct supertype
*st
;
1264 unsigned int besttime
= 0;
1268 st
= xcalloc(1, sizeof(*st
));
1269 st
->container_devnm
[0] = 0;
1271 for (i
= 0; superlist
[i
]; i
++) {
1274 if (guess_type
== guess_array
&& ss
->add_to_super
== NULL
)
1276 if (guess_type
== guess_partitions
&& ss
->add_to_super
!= NULL
)
1278 memset(st
, 0, sizeof(*st
));
1279 st
->ignore_hw_compat
= 1;
1280 rv
= ss
->load_super(st
, fd
, NULL
);
1283 st
->ss
->getinfo_super(st
, &info
, NULL
);
1284 if (bestsuper
== -1 ||
1285 besttime
< info
.array
.ctime
) {
1287 besttime
= info
.array
.ctime
;
1292 if (bestsuper
!= -1) {
1294 memset(st
, 0, sizeof(*st
));
1295 st
->ignore_hw_compat
= 1;
1296 rv
= superlist
[bestsuper
]->load_super(st
, fd
, NULL
);
1298 superlist
[bestsuper
]->free_super(st
);
1306 /* Return size of device in bytes */
1307 int get_dev_size(int fd
, char *dname
, unsigned long long *sizep
)
1309 unsigned long long ldsize
;
1312 if (fstat(fd
, &st
) != -1 && S_ISREG(st
.st_mode
))
1313 ldsize
= (unsigned long long)st
.st_size
;
1316 if (ioctl(fd
, BLKGETSIZE64
, &ldsize
) != 0)
1319 unsigned long dsize
;
1320 if (ioctl(fd
, BLKGETSIZE
, &dsize
) == 0) {
1325 pr_err("Cannot get size of %s: %s\n",
1326 dname
, strerror(errno
));
1334 /* Return sector size of device in bytes */
1335 int get_dev_sector_size(int fd
, char *dname
, unsigned int *sectsizep
)
1337 unsigned int sectsize
;
1339 if (ioctl(fd
, BLKSSZGET
, §size
) != 0) {
1341 pr_err("Cannot get sector size of %s: %s\n",
1342 dname
, strerror(errno
));
1346 *sectsizep
= sectsize
;
1350 /* Return true if this can only be a container, not a member device.
1351 * i.e. is and md device and size is zero
1353 int must_be_container(int fd
)
1356 unsigned long long size
;
1358 mdi
= sysfs_read(fd
, NULL
, GET_VERSION
);
1363 if (get_dev_size(fd
, NULL
, &size
) == 0)
1370 /* Sets endofpart parameter to the last block used by the last GPT partition on the device.
1371 * Returns: 1 if successful
1372 * -1 for unknown partition type
1373 * 0 for other errors
1375 static int get_gpt_last_partition_end(int fd
, unsigned long long *endofpart
)
1378 unsigned char empty_gpt_entry
[16]= {0};
1379 struct GPT_part_entry
*part
;
1381 unsigned long long curr_part_end
;
1382 unsigned all_partitions
, entry_size
;
1384 unsigned int sector_size
= 0;
1388 BUILD_BUG_ON(sizeof(gpt
) != 512);
1389 /* skip protective MBR */
1390 if (!get_dev_sector_size(fd
, NULL
, §or_size
))
1392 if (lseek(fd
, sector_size
, SEEK_SET
) == -1L)
1394 /* read GPT header */
1395 if (read(fd
, &gpt
, 512) != 512)
1398 /* get the number of partition entries and the entry size */
1399 all_partitions
= __le32_to_cpu(gpt
.part_cnt
);
1400 entry_size
= __le32_to_cpu(gpt
.part_size
);
1402 /* Check GPT signature*/
1403 if (gpt
.magic
!= GPT_SIGNATURE_MAGIC
)
1407 if (all_partitions
> 1024 ||
1408 entry_size
> sizeof(buf
))
1411 part
= (struct GPT_part_entry
*)buf
;
1413 /* set offset to third block (GPT entries) */
1414 if (lseek(fd
, sector_size
*2, SEEK_SET
) == -1L)
1416 for (part_nr
= 0; part_nr
< all_partitions
; part_nr
++) {
1417 /* read partition entry */
1418 if (read(fd
, buf
, entry_size
) != (ssize_t
)entry_size
)
1421 /* is this valid partition? */
1422 if (memcmp(part
->type_guid
, empty_gpt_entry
, 16) != 0) {
1423 /* check the last lba for the current partition */
1424 curr_part_end
= __le64_to_cpu(part
->ending_lba
);
1425 if (curr_part_end
> *endofpart
)
1426 *endofpart
= curr_part_end
;
1433 /* Sets endofpart parameter to the last block used by the last partition on the device.
1434 * Returns: 1 if successful
1435 * -1 for unknown partition type
1436 * 0 for other errors
1438 static int get_last_partition_end(int fd
, unsigned long long *endofpart
)
1440 struct MBR boot_sect
;
1441 unsigned long long curr_part_end
;
1443 unsigned int sector_size
;
1448 BUILD_BUG_ON(sizeof(boot_sect
) != 512);
1450 if (lseek(fd
, 0, 0) == -1L)
1452 if (read(fd
, &boot_sect
, 512) != 512)
1455 /* check MBP signature */
1456 if (boot_sect
.magic
== MBR_SIGNATURE_MAGIC
) {
1458 /* found the correct signature */
1460 for (part_nr
= 0; part_nr
< MBR_PARTITIONS
; part_nr
++) {
1462 * Have to make every access through boot_sect rather
1463 * than using a pointer to the partition table (or an
1464 * entry), since the entries are not properly aligned.
1467 /* check for GPT type */
1468 if (boot_sect
.parts
[part_nr
].part_type
==
1469 MBR_GPT_PARTITION_TYPE
) {
1470 retval
= get_gpt_last_partition_end(fd
, endofpart
);
1473 /* check the last used lba for the current partition */
1475 __le32_to_cpu(boot_sect
.parts
[part_nr
].first_sect_lba
) +
1476 __le32_to_cpu(boot_sect
.parts
[part_nr
].blocks_num
);
1477 if (curr_part_end
> *endofpart
)
1478 *endofpart
= curr_part_end
;
1481 /* Unknown partition table */
1484 /* calculate number of 512-byte blocks */
1485 if (get_dev_sector_size(fd
, NULL
, §or_size
))
1486 *endofpart
*= (sector_size
/ 512);
1491 int check_partitions(int fd
, char *dname
, unsigned long long freesize
,
1492 unsigned long long size
)
1495 * Check where the last partition ends
1497 unsigned long long endofpart
;
1499 if (get_last_partition_end(fd
, &endofpart
) > 0) {
1500 /* There appears to be a partition table here */
1501 if (freesize
== 0) {
1502 /* partitions will not be visible in new device */
1503 pr_err("partition table exists on %s but will be lost or\n"
1504 " meaningless after creating array\n",
1507 } else if (endofpart
> freesize
) {
1508 /* last partition overlaps metadata */
1509 pr_err("metadata will over-write last partition on %s.\n",
1512 } else if (size
&& endofpart
> size
) {
1513 /* partitions will be truncated in new device */
1514 pr_err("array size is too small to cover all partitions on %s.\n",
1522 int open_container(int fd
)
1524 /* 'fd' is a block device. Find out if it is in use
1525 * by a container, and return an open fd on that container.
1536 if (fstat(fd
, &st
) != 0)
1538 sprintf(path
, "/sys/dev/block/%d:%d/holders",
1539 (int)major(st
.st_rdev
), (int)minor(st
.st_rdev
));
1540 e
= path
+ strlen(path
);
1542 dir
= opendir(path
);
1545 while ((de
= readdir(dir
))) {
1548 if (de
->d_name
[0] == '.')
1550 /* Need to make sure it is a container and not a volume */
1551 sprintf(e
, "/%s/md/metadata_version", de
->d_name
);
1552 dfd
= open(path
, O_RDONLY
);
1555 n
= read(dfd
, buf
, sizeof(buf
));
1557 if (n
<= 0 || (unsigned)n
>= sizeof(buf
))
1560 if (strncmp(buf
, "external", 8) != 0 ||
1564 sprintf(e
, "/%s/dev", de
->d_name
);
1565 dfd
= open(path
, O_RDONLY
);
1568 n
= read(dfd
, buf
, sizeof(buf
));
1570 if (n
<= 0 || (unsigned)n
>= sizeof(buf
))
1573 if (sscanf(buf
, "%d:%d", &major
, &minor
) != 2)
1575 sprintf(buf
, "%d:%d", major
, minor
);
1576 dfd
= dev_open(buf
, O_RDONLY
);
1586 struct superswitch
*version_to_superswitch(char *vers
)
1590 for (i
= 0; superlist
[i
]; i
++) {
1591 struct superswitch
*ss
= superlist
[i
];
1593 if (strcmp(vers
, ss
->name
) == 0)
1600 int metadata_container_matches(char *metadata
, char *devnm
)
1602 /* Check if 'devnm' is the container named in 'metadata'
1604 * /containername/componentname or
1605 * -containername/componentname
1608 if (*metadata
!= '/' && *metadata
!= '-')
1611 if (strncmp(metadata
+1, devnm
, l
) != 0)
1613 if (metadata
[l
+1] != '/')
1618 int metadata_subdev_matches(char *metadata
, char *devnm
)
1620 /* Check if 'devnm' is the subdev named in 'metadata'
1622 * /containername/subdev or
1623 * -containername/subdev
1626 if (*metadata
!= '/' && *metadata
!= '-')
1628 sl
= strchr(metadata
+1, '/');
1631 if (strcmp(sl
+1, devnm
) == 0)
1636 int is_subarray_active(char *subarray
, char *container
)
1638 struct mdstat_ent
*mdstat
= mdstat_read(0, 0);
1639 struct mdstat_ent
*ent
;
1641 for (ent
= mdstat
; ent
; ent
= ent
->next
)
1642 if (is_container_member(ent
, container
))
1643 if (strcmp(to_subarray(ent
, container
), subarray
) == 0)
1646 free_mdstat(mdstat
);
1651 /* open_subarray - opens a subarray in a container
1652 * @dev: container device name
1653 * @st: empty supertype
1654 * @quiet: block reporting errors flag
1656 * On success returns an fd to a container and fills in *st
1658 int open_subarray(char *dev
, char *subarray
, struct supertype
*st
, int quiet
)
1661 struct mdinfo
*info
;
1665 fd
= open(dev
, O_RDWR
|O_EXCL
);
1668 pr_err("Couldn't open %s, aborting\n",
1673 _devnm
= fd2devnm(fd
);
1674 if (_devnm
== NULL
) {
1676 pr_err("Failed to determine device number for %s\n",
1680 snprintf(st
->devnm
, sizeof(st
->devnm
), "%s", _devnm
);
1682 mdi
= sysfs_read(fd
, st
->devnm
, GET_VERSION
|GET_LEVEL
);
1685 pr_err("Failed to read sysfs for %s\n",
1690 if (mdi
->array
.level
!= UnSet
) {
1692 pr_err("%s is not a container\n", dev
);
1696 st
->ss
= version_to_superswitch(mdi
->text_version
);
1699 pr_err("Operation not supported for %s metadata\n",
1704 if (st
->devnm
[0] == 0) {
1706 pr_err("Failed to allocate device name\n");
1710 if (!st
->ss
->load_container
) {
1712 pr_err("%s is not a container\n", dev
);
1716 if (st
->ss
->load_container(st
, fd
, NULL
)) {
1718 pr_err("Failed to load metadata for %s\n",
1723 info
= st
->ss
->container_content(st
, subarray
);
1726 pr_err("Failed to find subarray-%s in %s\n",
1736 st
->ss
->free_super(st
);
1749 int add_disk(int mdfd
, struct supertype
*st
,
1750 struct mdinfo
*sra
, struct mdinfo
*info
)
1752 /* Add a device to an array, in one of 2 ways. */
1755 if (st
->ss
->external
) {
1756 if (info
->disk
.state
& (1<<MD_DISK_SYNC
))
1757 info
->recovery_start
= MaxSector
;
1759 info
->recovery_start
= 0;
1760 rv
= sysfs_add_disk(sra
, info
, 0);
1763 for (sd2
= sra
->devs
; sd2
; sd2
=sd2
->next
)
1767 sd2
= xmalloc(sizeof(*sd2
));
1769 sd2
->next
= sra
->devs
;
1774 rv
= ioctl(mdfd
, ADD_NEW_DISK
, &info
->disk
);
1778 int remove_disk(int mdfd
, struct supertype
*st
,
1779 struct mdinfo
*sra
, struct mdinfo
*info
)
1783 /* Remove the disk given by 'info' from the array */
1784 if (st
->ss
->external
)
1785 rv
= sysfs_set_str(sra
, info
, "slot", STR_COMMON_NONE
);
1787 rv
= ioctl(mdfd
, HOT_REMOVE_DISK
, makedev(info
->disk
.major
,
1792 int hot_remove_disk(int mdfd
, unsigned long dev
, int force
)
1794 int cnt
= force
? 500 : 5;
1797 /* HOT_REMOVE_DISK can fail with EBUSY if there are
1798 * outstanding IO requests to the device.
1799 * In this case, it can be helpful to wait a little while,
1800 * up to 5 seconds if 'force' is set, or 50 msec if not.
1802 while ((ret
= ioctl(mdfd
, HOT_REMOVE_DISK
, dev
)) == -1 &&
1805 sleep_for(0, MSEC_TO_NSEC(10), true);
1810 int sys_hot_remove_disk(int statefd
, int force
)
1812 int cnt
= force
? 500 : 5;
1816 int ret
= sysfs_set_memb_state_fd(statefd
, MEMB_STATE_REMOVE
, &err
);
1818 if (ret
== MDADM_STATUS_SUCCESS
)
1824 sleep_for(0, MSEC_TO_NSEC(10), true);
1830 int set_array_info(int mdfd
, struct supertype
*st
, struct mdinfo
*info
)
1832 /* Initialise kernel's knowledge of array.
1833 * This varies between externally managed arrays
1836 mdu_array_info_t inf
;
1839 if (st
->ss
->external
)
1840 return sysfs_set_array(info
);
1842 memset(&inf
, 0, sizeof(inf
));
1843 inf
.major_version
= info
->array
.major_version
;
1844 inf
.minor_version
= info
->array
.minor_version
;
1845 rv
= md_set_array_info(mdfd
, &inf
);
1850 unsigned long long min_recovery_start(struct mdinfo
*array
)
1852 /* find the minimum recovery_start in an array for metadata
1853 * formats that only record per-array recovery progress instead
1856 unsigned long long recovery_start
= MaxSector
;
1859 for (d
= array
->devs
; d
; d
= d
->next
)
1860 recovery_start
= min(recovery_start
, d
->recovery_start
);
1862 return recovery_start
;
1865 int mdmon_pid(const char *devnm
)
1872 sprintf(path
, "%s/%s.pid", MDMON_DIR
, devnm
);
1874 fd
= open(path
, O_RDONLY
| O_NOATIME
, 0);
1878 n
= read(fd
, pid
, 9);
1885 int mdmon_running(const char *devnm
)
1887 int pid
= mdmon_pid(devnm
);
1890 if (kill(pid
, 0) == 0)
1896 * wait_for_mdmon_control_socket() - Waits for mdmon control socket
1897 * to be created within specified time.
1898 * @container_devnm: Device for which mdmon control socket should start.
1900 * In foreground mode, when mdadm is trying to connect to control
1901 * socket it is possible that the mdmon has not created it yet.
1902 * Give some time to mdmon to create socket. Timeout set to 2 sec.
1904 * Return: MDADM_STATUS_SUCCESS if connect succeed, otherwise return
1907 mdadm_status_t
wait_for_mdmon_control_socket(const char *container_devnm
)
1909 enum mdadm_status status
= MDADM_STATUS_SUCCESS
;
1910 int sfd
, rv
, retry_count
= 0;
1911 struct sockaddr_un addr
;
1912 char path
[PATH_MAX
];
1914 snprintf(path
, PATH_MAX
, "%s/%s.sock", MDMON_DIR
, container_devnm
);
1915 sfd
= socket(PF_LOCAL
, SOCK_STREAM
, 0);
1916 if (!is_fd_valid(sfd
))
1917 return MDADM_STATUS_ERROR
;
1919 addr
.sun_family
= PF_LOCAL
;
1920 strncpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
) - 1);
1921 addr
.sun_path
[sizeof(addr
.sun_path
) - 1] = '\0';
1923 for (retry_count
= 0; retry_count
< 10; retry_count
++) {
1924 rv
= connect(sfd
, (struct sockaddr
*)&addr
, sizeof(addr
));
1926 sleep_for(0, MSEC_TO_NSEC(200), true);
1933 pr_err("Failed to connect to control socket.\n");
1934 status
= MDADM_STATUS_ERROR
;
1941 * wait_for_mdmon() - Waits for mdmon within specified time.
1942 * @devnm: Device for which mdmon should start.
1944 * Function waits for mdmon to start. It may need few seconds
1945 * to start, we set timeout to 5, it should be sufficient.
1946 * Do not wait if mdmon has been started.
1948 * Return: MDADM_STATUS_SUCCESS if mdmon is running, error code otherwise.
1950 mdadm_status_t
wait_for_mdmon(const char *devnm
)
1952 const time_t mdmon_timeout
= 5;
1953 time_t start_time
= time(0);
1955 if (mdmon_running(devnm
))
1956 return MDADM_STATUS_SUCCESS
;
1958 pr_info("Waiting for mdmon to start\n");
1959 while (time(0) - start_time
< mdmon_timeout
) {
1960 sleep_for(0, MSEC_TO_NSEC(200), true);
1961 if (mdmon_running(devnm
))
1962 return MDADM_STATUS_SUCCESS
;
1965 pr_err("Timeout waiting for mdmon\n");
1966 return MDADM_STATUS_ERROR
;
1969 int start_mdmon(char *devnm
)
1975 char *prefix
= in_initrd() ? "initrd-" : "";
1984 if (check_env("MDADM_NO_MDMON"))
1986 if (continue_via_systemd(devnm
, MDMON_SERVICE
, prefix
) == MDADM_STATUS_SUCCESS
)
1989 /* That failed, try running mdmon directly */
1990 len
= readlink("/proc/self/exe", pathbuf
, sizeof(pathbuf
)-1);
1994 sl
= strrchr(pathbuf
, '/');
1999 strcpy(sl
, "mdmon");
2006 for (i
= 0; paths
[i
]; i
++)
2008 execl(paths
[i
], paths
[i
],
2012 case -1: pr_err("cannot run mdmon. Array remains readonly\n");
2014 default: /* parent - good */
2015 pid
= wait(&status
);
2016 if (pid
< 0 || status
!= 0) {
2017 pr_err("failed to launch mdmon. Array remains readonly\n");
2024 __u32
random32(void)
2027 int rfd
= open("/dev/urandom", O_RDONLY
);
2028 if (rfd
< 0 || read(rfd
, &rv
, 4) != 4)
2035 void random_uuid(__u8
*buf
)
2040 fd
= open("/dev/urandom", O_RDONLY
);
2043 len
= read(fd
, buf
, 16);
2051 for (i
= 0; i
< 4; i
++)
2056 int flush_metadata_updates(struct supertype
*st
)
2060 st
->update_tail
= NULL
;
2064 sfd
= connect_monitor(st
->container_devnm
);
2068 while (st
->updates
) {
2069 struct metadata_update
*mu
= st
->updates
;
2070 st
->updates
= mu
->next
;
2072 send_message(sfd
, mu
, 0);
2080 st
->update_tail
= NULL
;
2084 void append_metadata_update(struct supertype
*st
, void *buf
, int len
)
2087 struct metadata_update
*mu
= xmalloc(sizeof(*mu
));
2092 mu
->space_list
= NULL
;
2094 *st
->update_tail
= mu
;
2095 st
->update_tail
= &mu
->next
;
2099 /* tinyc doesn't optimize this check in ioctl.h out ... */
2100 unsigned int __invalid_size_argument_for_IOC
= 0;
2104 * disk_fd_matches_criteria() - check if device matches spare criteria.
2105 * @st: supertype, not NULL.
2106 * @disk_fd: file descriptor of the disk.
2107 * @sc: criteria to test.
2109 * Return: true if disk matches criteria, false otherwise.
2111 bool disk_fd_matches_criteria(struct supertype
*st
, int disk_fd
, struct spare_criteria
*sc
)
2113 unsigned int dev_sector_size
= 0;
2114 unsigned long long dev_size
= 0;
2116 if (!sc
->criteria_set
)
2119 if (!get_dev_size(disk_fd
, NULL
, &dev_size
) || dev_size
< sc
->min_size
)
2122 if (!get_dev_sector_size(disk_fd
, NULL
, &dev_sector_size
) ||
2123 sc
->sector_size
!= dev_sector_size
)
2126 if (drive_test_and_add_policies(st
, &sc
->pols
, disk_fd
, 0))
2133 * devid_matches_criteria() - check if device referenced by devid matches spare criteria.
2134 * @st: supertype, not NULL.
2135 * @devid: devid of the device to check.
2136 * @sc: criteria to test.
2138 * Return: true if disk matches criteria, false otherwise.
2140 bool devid_matches_criteria(struct supertype
*st
, dev_t devid
, struct spare_criteria
*sc
)
2146 if (!sc
->criteria_set
)
2149 snprintf(buf
, NAME_MAX
, "%d:%d", major(devid
), minor(devid
));
2151 fd
= dev_open(buf
, O_RDONLY
);
2152 if (!is_fd_valid(fd
))
2155 /* Error code inherited */
2156 ret
= disk_fd_matches_criteria(st
, fd
, sc
);
2162 /* Pick all spares matching given criteria from a container
2163 * if min_size == 0 do not check size
2164 * if domlist == NULL do not check domains
2165 * if spare_group given add it to domains of each spare
2166 * metadata allows to test domains using metadata of destination array */
2167 struct mdinfo
*container_choose_spares(struct supertype
*st
,
2168 struct spare_criteria
*criteria
,
2169 struct domainlist
*domlist
,
2171 const char *metadata
, int get_one
)
2173 struct mdinfo
*d
, **dp
, *disks
= NULL
;
2175 /* get list of all disks in container */
2176 if (st
->ss
->getinfo_super_disks
)
2177 disks
= st
->ss
->getinfo_super_disks(st
);
2181 /* find spare devices on the list */
2183 disks
->array
.spare_disks
= 0;
2188 if (d
->disk
.state
== 0) {
2189 dev_t dev
= makedev(d
->disk
.major
,d
->disk
.minor
);
2191 found
= devid_matches_criteria(st
, dev
, criteria
);
2193 /* check if domain matches */
2194 if (found
&& domlist
) {
2195 struct dev_policy
*pol
= devid_policy(dev
);
2197 pol_add(&pol
, pol_domain
,
2199 if (domain_test(domlist
, pol
, metadata
) != 1)
2202 dev_policy_free(pol
);
2207 disks
->array
.spare_disks
++;
2221 /* Checks if paths point to the same device
2222 * Returns 0 if they do.
2223 * Returns 1 if they don't.
2224 * Returns -1 if something went wrong,
2225 * e.g. paths are empty or the files
2226 * they point to don't exist */
2227 int compare_paths (char* path1
, char* path2
)
2229 struct stat st1
,st2
;
2231 if (path1
== NULL
|| path2
== NULL
)
2233 if (stat(path1
,&st1
) != 0)
2235 if (stat(path2
,&st2
) != 0)
2237 if ((st1
.st_ino
== st2
.st_ino
) && (st1
.st_dev
== st2
.st_dev
))
2242 /* Make sure we can open as many devices as needed */
2243 void enable_fds(int devices
)
2245 unsigned int fds
= 20 + devices
;
2247 if (getrlimit(RLIMIT_NOFILE
, &lim
) != 0 || lim
.rlim_cur
>= fds
)
2249 if (lim
.rlim_max
< fds
)
2252 setrlimit(RLIMIT_NOFILE
, &lim
);
2255 /* Close all opened descriptors if needed and redirect
2256 * streams to /dev/null.
2257 * For debug purposed, leave STDOUT and STDERR untouched
2259 * 1- if any error occurred
2262 void manage_fork_fds(int close_all
)
2265 struct dirent
*dirent
;
2266 int fd
= open("/dev/null", O_RDWR
);
2268 if (is_fd_valid(fd
)) {
2280 dir
= opendir("/proc/self/fd");
2282 pr_err("Cannot open /proc/self/fd directory.\n");
2285 for (dirent
= readdir(dir
); dirent
; dirent
= readdir(dir
)) {
2288 if ((strcmp(dirent
->d_name
, ".") == 0) ||
2289 (strcmp(dirent
->d_name
, "..")) == 0)
2292 fd
= strtol(dirent
->d_name
, NULL
, 10);
2300 /* In a systemd/udev world, it is best to get systemd to
2301 * run daemon rather than running in the background.
2303 * MDADM_STATUS_SUCCESS - if systemd service has been started.
2304 * MDADM_STATUS_ERROR - otherwise.
2306 mdadm_status_t
continue_via_systemd(char *devnm
, char *service_name
, char *prefix
)
2309 char pathbuf
[PATH_MAX
];
2311 dprintf("Start %s service\n", service_name
);
2312 /* Simply return that service cannot be started */
2313 if (check_env("MDADM_NO_SYSTEMCTL"))
2314 return MDADM_STATUS_ERROR
;
2316 /* Fork in attempt to start services */
2318 case -1: /* Fork failed, just do it ourselves. */
2322 snprintf(pathbuf
, sizeof(pathbuf
), "%s@%s%s.service",
2323 service_name
, prefix
? prefix
: "", devnm
);
2325 /* Attempt to start service.
2326 * On success execl() will "kill" the fork, and return status of systemctl call.
2328 execl("/usr/bin/systemctl", "systemctl", "restart", pathbuf
, NULL
);
2329 execl("/bin/systemctl", "systemctl", "restart", pathbuf
, NULL
);
2330 exit(MDADM_STATUS_ERROR
);
2331 default: /* parent */
2332 /* Check if forked process successfully trigered service */
2333 pid
= wait(&status
);
2334 if (pid
>= 0 && status
== 0)
2335 return MDADM_STATUS_SUCCESS
;
2337 return MDADM_STATUS_ERROR
;
2342 return access("/etc/initrd-release", F_OK
) >= 0;
2345 void reopen_mddev(int mdfd
)
2347 /* Re-open without any O_EXCL, but keep
2350 char *devnm
= fd2devnm(mdfd
);
2351 int fd
= open_dev(devnm
);
2353 if (!is_fd_valid(fd
))
2361 static struct cmap_hooks
*cmap_hooks
= NULL
;
2362 static int is_cmap_hooks_ready
= 0;
2364 void set_cmap_hooks(void)
2366 cmap_hooks
= xmalloc(sizeof(struct cmap_hooks
));
2367 cmap_hooks
->cmap_handle
= dlopen("libcmap.so.4", RTLD_NOW
| RTLD_LOCAL
);
2368 if (!cmap_hooks
->cmap_handle
)
2371 cmap_hooks
->initialize
=
2372 dlsym(cmap_hooks
->cmap_handle
, "cmap_initialize");
2373 cmap_hooks
->get_string
=
2374 dlsym(cmap_hooks
->cmap_handle
, "cmap_get_string");
2375 cmap_hooks
->finalize
= dlsym(cmap_hooks
->cmap_handle
, "cmap_finalize");
2377 if (!cmap_hooks
->initialize
|| !cmap_hooks
->get_string
||
2378 !cmap_hooks
->finalize
)
2379 dlclose(cmap_hooks
->cmap_handle
);
2381 is_cmap_hooks_ready
= 1;
2384 int get_cluster_name(char **cluster_name
)
2387 cmap_handle_t handle
;
2389 if (!is_cmap_hooks_ready
)
2392 rv
= cmap_hooks
->initialize(&handle
);
2396 rv
= cmap_hooks
->get_string(handle
, "totem.cluster_name", cluster_name
);
2398 free(*cluster_name
);
2405 cmap_hooks
->finalize(handle
);
2410 void set_dlm_hooks(void)
2412 dlm_hooks
= xmalloc(sizeof(struct dlm_hooks
));
2413 dlm_hooks
->dlm_handle
= dlopen("libdlm_lt.so.3", RTLD_NOW
| RTLD_LOCAL
);
2414 if (!dlm_hooks
->dlm_handle
)
2417 dlm_hooks
->open_lockspace
=
2418 dlsym(dlm_hooks
->dlm_handle
, "dlm_open_lockspace");
2419 dlm_hooks
->create_lockspace
=
2420 dlsym(dlm_hooks
->dlm_handle
, "dlm_create_lockspace");
2421 dlm_hooks
->release_lockspace
=
2422 dlsym(dlm_hooks
->dlm_handle
, "dlm_release_lockspace");
2423 dlm_hooks
->ls_lock
= dlsym(dlm_hooks
->dlm_handle
, "dlm_ls_lock");
2424 dlm_hooks
->ls_unlock_wait
=
2425 dlsym(dlm_hooks
->dlm_handle
, "dlm_ls_unlock_wait");
2426 dlm_hooks
->ls_get_fd
= dlsym(dlm_hooks
->dlm_handle
, "dlm_ls_get_fd");
2427 dlm_hooks
->dispatch
= dlsym(dlm_hooks
->dlm_handle
, "dlm_dispatch");
2429 if (!dlm_hooks
->open_lockspace
|| !dlm_hooks
->create_lockspace
||
2430 !dlm_hooks
->ls_lock
|| !dlm_hooks
->ls_unlock_wait
||
2431 !dlm_hooks
->release_lockspace
|| !dlm_hooks
->ls_get_fd
||
2432 !dlm_hooks
->dispatch
)
2433 dlclose(dlm_hooks
->dlm_handle
);
2435 is_dlm_hooks_ready
= 1;
2438 void set_hooks(void)
2444 int zero_disk_range(int fd
, unsigned long long sector
, size_t count
)
2450 size_t len
= count
* 512;
2453 fd_zero
= open("/dev/zero", O_RDONLY
);
2455 pr_err("Cannot open /dev/zero\n");
2459 if (lseek64(fd
, sector
* 512, SEEK_SET
) < 0) {
2461 pr_err("Failed to seek offset for zeroing\n");
2465 addr
= mmap(NULL
, len
, PROT_READ
, MAP_PRIVATE
, fd_zero
, 0);
2467 if (addr
== MAP_FAILED
) {
2469 pr_err("Mapping /dev/zero failed\n");
2474 n
= write(fd
, addr
+ written
, len
- written
);
2479 pr_err("Zeroing disk range failed\n");
2483 } while (written
!= len
);
2493 * sleep_for() - Sleeps for specified time.
2494 * @sec: Seconds to sleep for.
2495 * @nsec: Nanoseconds to sleep for, has to be less than one second.
2496 * @wake_after_interrupt: If set, wake up if interrupted.
2498 * Function immediately returns if error different than EINTR occurs.
2500 void sleep_for(unsigned int sec
, long nsec
, bool wake_after_interrupt
)
2502 struct timespec delay
= {.tv_sec
= sec
, .tv_nsec
= nsec
};
2504 assert(nsec
< MSEC_TO_NSEC(1000));
2508 nanosleep(&delay
, &delay
);
2509 if (errno
!= 0 && errno
!= EINTR
) {
2510 pr_err("Error sleeping for %us %ldns: %s\n", sec
, nsec
, strerror(errno
));
2513 } while (!wake_after_interrupt
&& errno
== EINTR
);
2516 /* is_directory() - Checks if directory provided by path is indeed a regular directory.
2517 * @path: directory path to be checked
2519 * Doesn't accept symlinks.
2521 * Return: true if is a directory, false if not
2523 bool is_directory(const char *path
)
2527 if (lstat(path
, &st
) != 0) {
2528 pr_err("%s: %s\n", strerror(errno
), path
);
2532 if (!S_ISDIR(st
.st_mode
))
2539 * is_file() - Checks if file provided by path is indeed a regular file.
2540 * @path: file path to be checked
2542 * Doesn't accept symlinks.
2544 * Return: true if is a file, false if not
2546 bool is_file(const char *path
)
2550 if (lstat(path
, &st
) != 0) {
2551 pr_err("%s: %s\n", strerror(errno
), path
);
2555 if (!S_ISREG(st
.st_mode
))