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
);
701 int fstat_is_blkdev(int fd
, char *devname
, dev_t
*rdev
)
705 if (fstat(fd
, &stb
) != 0) {
706 pr_err("fstat failed for %s: %s\n", devname
, strerror(errno
));
709 if ((S_IFMT
& stb
.st_mode
) != S_IFBLK
) {
710 pr_err("%s is not a block device.\n", devname
);
718 int stat_is_blkdev(char *devname
, dev_t
*rdev
)
722 if (stat(devname
, &stb
) != 0) {
723 pr_err("stat failed for %s: %s\n", devname
, strerror(errno
));
726 if ((S_IFMT
& stb
.st_mode
) != S_IFBLK
) {
727 pr_err("%s is not a block device.\n", devname
);
736 * ask() - prompt user for "yes/no" dialog.
737 * @mesg: message to be printed, without '?' sign.
738 * Returns: 1 if 'Y/y', 0 otherwise.
740 * The default value is 'N/n', thus the caps on "N" on prompt.
746 fprintf(stderr
, "%s [y/N]? ", mesg
);
748 if (fgets(buf
, 3, stdin
) == NULL
)
750 if (strlen(buf
) == 1) {
751 pr_err("assuming no.\n");
756 if (toupper(buf
[0]) == 'Y')
758 if (toupper(buf
[0]) == 'N')
761 pr_err("bad option.\n");
765 unsigned long calc_csum(void *super
, int bytes
)
767 unsigned long long newcsum
= 0;
770 unsigned int *superc
= (unsigned int*) super
;
772 for(i
= 0; i
< bytes
/4; i
++)
773 newcsum
+= superc
[i
];
774 csum
= (newcsum
& 0xffffffff) + (newcsum
>>32);
776 /* The in-kernel checksum calculation is always 16bit on
777 * the alpha, though it is 32 bit on i386...
778 * I wonder what it is elsewhere... (it uses an API in
779 * a way that it shouldn't).
781 csum
= (csum
& 0xffff) + (csum
>> 16);
782 csum
= (csum
& 0xffff) + (csum
>> 16);
787 char *human_size(long long bytes
)
791 /* We convert bytes to either centi-M{ega,ibi}bytes,
792 * centi-G{igi,ibi}bytes or centi-T{era,ebi}bytes
793 * with appropriate rounding, and then print
794 * 1/100th of those as a decimal.
795 * We allow upto 2048Megabytes before converting to
796 * gigabytes and 2048Gigabytes before converting to
797 * terabytes, as that shows more precision and isn't
798 * too large a number.
801 if (bytes
< 5000*1024)
803 else if (bytes
< 2*1024LL*1024LL*1024LL) {
804 long cMiB
= (bytes
* 200LL / (1LL<<20) + 1) / 2;
805 long cMB
= (bytes
/ ( 1000000LL / 200LL ) +1) /2;
806 snprintf(buf
, sizeof(buf
), " (%ld.%02ld MiB %ld.%02ld MB)",
807 cMiB
/100, cMiB
% 100, cMB
/100, cMB
% 100);
808 } else if (bytes
< 2*1024LL*1024LL*1024LL*1024LL) {
809 long cGiB
= (bytes
* 200LL / (1LL<<30) +1) / 2;
810 long cGB
= (bytes
/ (1000000000LL/200LL ) +1) /2;
811 snprintf(buf
, sizeof(buf
), " (%ld.%02ld GiB %ld.%02ld GB)",
812 cGiB
/100, cGiB
% 100, cGB
/100, cGB
% 100);
814 long cTiB
= (bytes
* 200LL / (1LL<<40) + 1) / 2;
815 long cTB
= (bytes
/ (1000000000000LL / 200LL) + 1) / 2;
816 snprintf(buf
, sizeof(buf
), " (%ld.%02ld TiB %ld.%02ld TB)",
817 cTiB
/100, cTiB
% 100, cTB
/100, cTB
% 100);
822 char *human_size_brief(long long bytes
, int prefix
)
826 /* We convert bytes to either centi-M{ega,ibi}bytes,
827 * centi-G{igi,ibi}bytes or centi-T{era,ebi}bytes
828 * with appropriate rounding, and then print
829 * 1/100th of those as a decimal.
830 * We allow upto 2048Megabytes before converting to
831 * gigabytes and 2048Gigabytes before converting to
832 * terabytes, as that shows more precision and isn't
833 * too large a number.
835 * If prefix == IEC, we mean prefixes like kibi,mebi,gibi etc.
836 * If prefix == JEDEC, we mean prefixes like kilo,mega,giga etc.
839 if (bytes
< 5000*1024)
841 else if (prefix
== IEC
) {
842 if (bytes
< 2*1024LL*1024LL*1024LL) {
843 long cMiB
= (bytes
* 200LL / (1LL<<20) +1) /2;
844 snprintf(buf
, sizeof(buf
), "%ld.%02ldMiB",
845 cMiB
/100, cMiB
% 100);
846 } else if (bytes
< 2*1024LL*1024LL*1024LL*1024LL) {
847 long cGiB
= (bytes
* 200LL / (1LL<<30) +1) /2;
848 snprintf(buf
, sizeof(buf
), "%ld.%02ldGiB",
849 cGiB
/100, cGiB
% 100);
851 long cTiB
= (bytes
* 200LL / (1LL<<40) + 1) / 2;
852 snprintf(buf
, sizeof(buf
), "%ld.%02ldTiB",
853 cTiB
/100, cTiB
% 100);
856 else if (prefix
== JEDEC
) {
857 if (bytes
< 2*1024LL*1024LL*1024LL) {
858 long cMB
= (bytes
/ ( 1000000LL / 200LL ) +1) /2;
859 snprintf(buf
, sizeof(buf
), "%ld.%02ldMB",
861 } else if (bytes
< 2*1024LL*1024LL*1024LL*1024LL) {
862 long cGB
= (bytes
/ (1000000000LL/200LL ) +1) /2;
863 snprintf(buf
, sizeof(buf
), "%ld.%02ldGB",
866 long cTB
= (bytes
/ (1000000000000LL / 200LL) + 1) / 2;
867 snprintf(buf
, sizeof(buf
), "%ld.%02ldTB",
877 void print_r10_layout(int layout
)
879 int near
= layout
& 255;
880 int far
= (layout
>> 8) & 255;
881 int offset
= (layout
&0x10000);
885 printf("%s near=%d", sep
, near
);
889 printf("%s %s=%d", sep
, offset
?"offset":"far", far
);
891 printf("NO REDUNDANCY");
894 unsigned long long calc_array_size(int level
, int raid_disks
, int layout
,
895 int chunksize
, unsigned long long devsize
)
899 devsize
&= ~(unsigned long long)((chunksize
>>9)-1);
900 return get_data_disks(level
, layout
, raid_disks
) * devsize
;
903 int get_data_disks(int level
, int layout
, int raid_disks
)
907 case 0: data_disks
= raid_disks
;
909 case 1: data_disks
= 1;
912 case 5: data_disks
= raid_disks
- 1;
914 case 6: data_disks
= raid_disks
- 2;
916 case 10: data_disks
= raid_disks
/ (layout
& 255) / ((layout
>>8)&255);
923 dev_t
devnm2devid(char *devnm
)
925 /* First look in /sys/block/$DEVNM/dev for %d:%d
926 * If that fails, try parsing out a number
933 snprintf(path
, sizeof(path
), "/sys/block/%s/dev", devnm
);
934 fd
= open(path
, O_RDONLY
);
937 int n
= read(fd
, buf
, sizeof(buf
));
941 if (n
> 0 && sscanf(buf
, "%d:%d\n", &mjr
, &mnr
) == 2)
942 return makedev(mjr
, mnr
);
944 if (strncmp(devnm
, "md_d", 4) == 0 &&
946 (mnr
= strtoul(devnm
+4, &ep
, 10)) >= 0 &&
947 ep
> devnm
&& *ep
== 0)
948 return makedev(get_mdp_major(), mnr
<< MdpMinorShift
);
950 if (strncmp(devnm
, "md", 2) == 0 &&
952 (mnr
= strtoul(devnm
+2, &ep
, 10)) >= 0 &&
953 ep
> devnm
&& *ep
== 0)
954 return makedev(MD_MAJOR
, mnr
);
960 * is_devname_numbered() - helper for numbered devname verification.
961 * @devname: path or name to check.
962 * @pref: expected devname prefix.
963 * @pref_len: prefix len.
965 static bool is_devname_numbered(const char *devname
, const char *pref
, const int pref_len
)
969 assert(devname
&& pref
);
971 if (strncmp(devname
, pref
, pref_len
) != 0)
974 if (parse_num(&val
, devname
+ pref_len
) != 0)
977 /* Allow any number that represents a valid minor number */
978 if (val
>= (1 << 20))
985 * is_devname_md_numbered() - check if &devname is numbered MD device (md).
986 * @devname: path or name to check.
988 bool is_devname_md_numbered(const char *devname
)
990 return is_devname_numbered(devname
, DEV_NUM_PREF
, DEV_NUM_PREF_LEN
);
994 * is_devname_md_d_numbered() - check if &devname is secondary numbered MD device (md_d).
995 * @devname: path or name to check.
997 bool is_devname_md_d_numbered(const char *devname
)
999 static const char d_dev
[] = DEV_NUM_PREF
"_d";
1001 return is_devname_numbered(devname
, d_dev
, sizeof(d_dev
) - 1);
1005 * get_md_name() - Get main dev node of the md device.
1006 * @devnm: Md device name or path.
1008 * Function checks if the full name was passed and returns md name
1009 * if it is the MD device.
1011 * Return: Main dev node of the md device or NULL if not found.
1013 char *get_md_name(char *devnm
)
1015 static char devname
[NAME_MAX
];
1018 if (strncmp(devnm
, "/dev/", 5) == 0)
1019 snprintf(devname
, sizeof(devname
), "%s", devnm
);
1021 snprintf(devname
, sizeof(devname
), "/dev/%s", devnm
);
1023 if (!is_mddev(devname
))
1025 if (stat(devname
, &stb
) == 0 && (S_IFMT
&stb
.st_mode
) == S_IFBLK
)
1031 void put_md_name(char *name
)
1033 if (strncmp(name
, "/dev/.tmp.md", 12) == 0)
1037 int get_maj_min(char *dev
, int *major
, int *minor
)
1040 *major
= strtoul(dev
, &e
, 0);
1041 return (e
> dev
&& *e
== ':' && e
[1] &&
1042 (*minor
= strtoul(e
+1, &e
, 0)) >= 0 &&
1047 * is_bit_set() - get bit value by index.
1049 * @index: index of the bit (LSB numbering).
1051 * Return: bit value.
1053 bool is_bit_set(int *val
, unsigned char index
)
1055 if ((*val
) & (1 << index
))
1060 int dev_open(char *dev
, int flags
)
1062 /* like 'open', but if 'dev' matches %d:%d, create a temp
1063 * block device and open that
1074 if (get_maj_min(dev
, &major
, &minor
)) {
1075 snprintf(devname
, sizeof(devname
), "/dev/.tmp.md.%d:%d:%d",
1076 (int)getpid(), major
, minor
);
1077 if (mknod(devname
, S_IFBLK
|0600, makedev(major
, minor
)) == 0) {
1078 fd
= open(devname
, flags
);
1082 fd
= open(dev
, flags
);
1086 int open_dev_flags(char *devnm
, int flags
)
1091 devid
= devnm2devid(devnm
);
1092 sprintf(buf
, "%d:%d", major(devid
), minor(devid
));
1093 return dev_open(buf
, flags
);
1096 int open_dev(char *devnm
)
1098 return open_dev_flags(devnm
, O_RDONLY
);
1101 int open_dev_excl(char *devnm
)
1106 dev_t devid
= devnm2devid(devnm
);
1107 unsigned int delay
= 1; // miliseconds
1109 sprintf(buf
, "%d:%d", major(devid
), minor(devid
));
1110 for (i
= 0; i
< 25; i
++) {
1111 int fd
= dev_open(buf
, flags
|O_EXCL
);
1114 if (errno
== EACCES
&& flags
== O_RDWR
) {
1120 sleep_for(0, MSEC_TO_NSEC(delay
), true);
1127 int same_dev(char *one
, char *two
)
1129 struct stat st1
, st2
;
1130 if (stat(one
, &st1
) != 0)
1132 if (stat(two
, &st2
) != 0)
1134 if ((st1
.st_mode
& S_IFMT
) != S_IFBLK
)
1136 if ((st2
.st_mode
& S_IFMT
) != S_IFBLK
)
1138 return st1
.st_rdev
== st2
.st_rdev
;
1141 void wait_for(char *dev
, int fd
)
1144 struct stat stb_want
;
1145 unsigned int delay
= 1; // miliseconds
1147 if (fstat(fd
, &stb_want
) != 0 ||
1148 (stb_want
.st_mode
& S_IFMT
) != S_IFBLK
)
1151 for (i
= 0; i
< 25; i
++) {
1153 if (stat(dev
, &stb
) == 0 &&
1154 (stb
.st_mode
& S_IFMT
) == S_IFBLK
&&
1155 (stb
.st_rdev
== stb_want
.st_rdev
))
1157 sleep_for(0, MSEC_TO_NSEC(delay
), true);
1162 pr_err("timeout waiting for %s\n", dev
);
1165 struct superswitch
*superlist
[] =
1168 &super_ddf
, &super_imsm
,
1173 struct supertype
*super_by_fd(int fd
, char **subarrayp
)
1175 mdu_array_info_t array
;
1178 struct supertype
*st
= NULL
;
1183 char *subarray
= NULL
;
1184 char container
[32] = "";
1187 devnm
= fd2devnm(fd
);
1191 sra
= sysfs_read(fd
, NULL
, GET_VERSION
);
1194 vers
= sra
->array
.major_version
;
1195 minor
= sra
->array
.minor_version
;
1196 verstr
= sra
->text_version
;
1198 if (md_get_array_info(fd
, &array
))
1199 array
.major_version
= array
.minor_version
= 0;
1200 vers
= array
.major_version
;
1201 minor
= array
.minor_version
;
1206 sprintf(version
, "%d.%d", vers
, minor
);
1209 if (minor
== -2 && is_subarray(verstr
)) {
1210 char *dev
= verstr
+1;
1212 subarray
= strchr(dev
, '/');
1215 subarray
= xstrdup(subarray
);
1217 snprintf(container
, sizeof(container
), "%s", dev
);
1219 sra
= sysfs_read(-1, container
, GET_VERSION
);
1220 if (sra
&& sra
->text_version
[0])
1221 verstr
= sra
->text_version
;
1223 verstr
= "-no-metadata-";
1226 for (i
= 0; st
== NULL
&& superlist
[i
]; i
++)
1227 st
= superlist
[i
]->match_metadata_desc(verstr
);
1233 *subarrayp
= subarray
;
1234 strcpy(st
->container_devnm
, container
);
1235 strncpy(st
->devnm
, devnm
, MD_NAME_MAX
- 1);
1242 struct supertype
*dup_super(struct supertype
*orig
)
1244 struct supertype
*st
;
1248 st
= xcalloc(1, sizeof(*st
));
1250 st
->max_devs
= orig
->max_devs
;
1251 st
->minor_version
= orig
->minor_version
;
1252 st
->ignore_hw_compat
= orig
->ignore_hw_compat
;
1253 st
->data_offset
= orig
->data_offset
;
1259 struct supertype
*guess_super_type(int fd
, enum guess_types guess_type
)
1261 /* try each load_super to find the best match,
1262 * and return the best superswitch
1264 struct superswitch
*ss
;
1265 struct supertype
*st
;
1266 unsigned int besttime
= 0;
1270 st
= xcalloc(1, sizeof(*st
));
1271 st
->container_devnm
[0] = 0;
1273 for (i
= 0; superlist
[i
]; i
++) {
1276 if (guess_type
== guess_array
&& ss
->add_to_super
== NULL
)
1278 if (guess_type
== guess_partitions
&& ss
->add_to_super
!= NULL
)
1280 memset(st
, 0, sizeof(*st
));
1281 st
->ignore_hw_compat
= 1;
1282 rv
= ss
->load_super(st
, fd
, NULL
);
1285 st
->ss
->getinfo_super(st
, &info
, NULL
);
1286 if (bestsuper
== -1 ||
1287 besttime
< info
.array
.ctime
) {
1289 besttime
= info
.array
.ctime
;
1294 if (bestsuper
!= -1) {
1296 memset(st
, 0, sizeof(*st
));
1297 st
->ignore_hw_compat
= 1;
1298 rv
= superlist
[bestsuper
]->load_super(st
, fd
, NULL
);
1300 superlist
[bestsuper
]->free_super(st
);
1308 /* Return size of device in bytes */
1309 int get_dev_size(int fd
, char *dname
, unsigned long long *sizep
)
1311 unsigned long long ldsize
;
1314 if (fstat(fd
, &st
) != -1 && S_ISREG(st
.st_mode
))
1315 ldsize
= (unsigned long long)st
.st_size
;
1318 if (ioctl(fd
, BLKGETSIZE64
, &ldsize
) != 0)
1321 unsigned long dsize
;
1322 if (ioctl(fd
, BLKGETSIZE
, &dsize
) == 0) {
1327 pr_err("Cannot get size of %s: %s\n",
1328 dname
, strerror(errno
));
1336 /* Return sector size of device in bytes */
1337 int get_dev_sector_size(int fd
, char *dname
, unsigned int *sectsizep
)
1339 unsigned int sectsize
;
1341 if (ioctl(fd
, BLKSSZGET
, §size
) != 0) {
1343 pr_err("Cannot get sector size of %s: %s\n",
1344 dname
, strerror(errno
));
1348 *sectsizep
= sectsize
;
1352 /* Return true if this can only be a container, not a member device.
1353 * i.e. is and md device and size is zero
1355 int must_be_container(int fd
)
1358 unsigned long long size
;
1360 mdi
= sysfs_read(fd
, NULL
, GET_VERSION
);
1365 if (get_dev_size(fd
, NULL
, &size
) == 0)
1372 /* Sets endofpart parameter to the last block used by the last GPT partition on the device.
1373 * Returns: 1 if successful
1374 * -1 for unknown partition type
1375 * 0 for other errors
1377 static int get_gpt_last_partition_end(int fd
, unsigned long long *endofpart
)
1380 unsigned char empty_gpt_entry
[16]= {0};
1381 struct GPT_part_entry
*part
;
1383 unsigned long long curr_part_end
;
1384 unsigned all_partitions
, entry_size
;
1386 unsigned int sector_size
= 0;
1390 BUILD_BUG_ON(sizeof(gpt
) != 512);
1391 /* skip protective MBR */
1392 if (!get_dev_sector_size(fd
, NULL
, §or_size
))
1394 if (lseek(fd
, sector_size
, SEEK_SET
) == -1L)
1396 /* read GPT header */
1397 if (read(fd
, &gpt
, 512) != 512)
1400 /* get the number of partition entries and the entry size */
1401 all_partitions
= __le32_to_cpu(gpt
.part_cnt
);
1402 entry_size
= __le32_to_cpu(gpt
.part_size
);
1404 /* Check GPT signature*/
1405 if (gpt
.magic
!= GPT_SIGNATURE_MAGIC
)
1409 if (all_partitions
> 1024 ||
1410 entry_size
> sizeof(buf
))
1413 part
= (struct GPT_part_entry
*)buf
;
1415 /* set offset to third block (GPT entries) */
1416 if (lseek(fd
, sector_size
*2, SEEK_SET
) == -1L)
1418 for (part_nr
= 0; part_nr
< all_partitions
; part_nr
++) {
1419 /* read partition entry */
1420 if (read(fd
, buf
, entry_size
) != (ssize_t
)entry_size
)
1423 /* is this valid partition? */
1424 if (memcmp(part
->type_guid
, empty_gpt_entry
, 16) != 0) {
1425 /* check the last lba for the current partition */
1426 curr_part_end
= __le64_to_cpu(part
->ending_lba
);
1427 if (curr_part_end
> *endofpart
)
1428 *endofpart
= curr_part_end
;
1435 /* Sets endofpart parameter to the last block used by the last partition on the device.
1436 * Returns: 1 if successful
1437 * -1 for unknown partition type
1438 * 0 for other errors
1440 static int get_last_partition_end(int fd
, unsigned long long *endofpart
)
1442 struct MBR boot_sect
;
1443 unsigned long long curr_part_end
;
1445 unsigned int sector_size
;
1450 BUILD_BUG_ON(sizeof(boot_sect
) != 512);
1452 if (lseek(fd
, 0, 0) == -1L)
1454 if (read(fd
, &boot_sect
, 512) != 512)
1457 /* check MBP signature */
1458 if (boot_sect
.magic
== MBR_SIGNATURE_MAGIC
) {
1460 /* found the correct signature */
1462 for (part_nr
= 0; part_nr
< MBR_PARTITIONS
; part_nr
++) {
1464 * Have to make every access through boot_sect rather
1465 * than using a pointer to the partition table (or an
1466 * entry), since the entries are not properly aligned.
1469 /* check for GPT type */
1470 if (boot_sect
.parts
[part_nr
].part_type
==
1471 MBR_GPT_PARTITION_TYPE
) {
1472 retval
= get_gpt_last_partition_end(fd
, endofpart
);
1475 /* check the last used lba for the current partition */
1477 __le32_to_cpu(boot_sect
.parts
[part_nr
].first_sect_lba
) +
1478 __le32_to_cpu(boot_sect
.parts
[part_nr
].blocks_num
);
1479 if (curr_part_end
> *endofpart
)
1480 *endofpart
= curr_part_end
;
1483 /* Unknown partition table */
1486 /* calculate number of 512-byte blocks */
1487 if (get_dev_sector_size(fd
, NULL
, §or_size
))
1488 *endofpart
*= (sector_size
/ 512);
1493 int check_partitions(int fd
, char *dname
, unsigned long long freesize
,
1494 unsigned long long size
)
1497 * Check where the last partition ends
1499 unsigned long long endofpart
;
1501 if (get_last_partition_end(fd
, &endofpart
) > 0) {
1502 /* There appears to be a partition table here */
1503 if (freesize
== 0) {
1504 /* partitions will not be visible in new device */
1505 pr_err("partition table exists on %s but will be lost or\n"
1506 " meaningless after creating array\n",
1509 } else if (endofpart
> freesize
) {
1510 /* last partition overlaps metadata */
1511 pr_err("metadata will over-write last partition on %s.\n",
1514 } else if (size
&& endofpart
> size
) {
1515 /* partitions will be truncated in new device */
1516 pr_err("array size is too small to cover all partitions on %s.\n",
1524 int open_container(int fd
)
1526 /* 'fd' is a block device. Find out if it is in use
1527 * by a container, and return an open fd on that container.
1538 if (fstat(fd
, &st
) != 0)
1540 sprintf(path
, "/sys/dev/block/%d:%d/holders",
1541 (int)major(st
.st_rdev
), (int)minor(st
.st_rdev
));
1542 e
= path
+ strlen(path
);
1544 dir
= opendir(path
);
1547 while ((de
= readdir(dir
))) {
1550 if (de
->d_name
[0] == '.')
1552 /* Need to make sure it is a container and not a volume */
1553 sprintf(e
, "/%s/md/metadata_version", de
->d_name
);
1554 dfd
= open(path
, O_RDONLY
);
1557 n
= read(dfd
, buf
, sizeof(buf
));
1559 if (n
<= 0 || (unsigned)n
>= sizeof(buf
))
1562 if (strncmp(buf
, "external", 8) != 0 ||
1566 sprintf(e
, "/%s/dev", de
->d_name
);
1567 dfd
= open(path
, O_RDONLY
);
1570 n
= read(dfd
, buf
, sizeof(buf
));
1572 if (n
<= 0 || (unsigned)n
>= sizeof(buf
))
1575 if (sscanf(buf
, "%d:%d", &major
, &minor
) != 2)
1577 sprintf(buf
, "%d:%d", major
, minor
);
1578 dfd
= dev_open(buf
, O_RDONLY
);
1588 struct superswitch
*version_to_superswitch(char *vers
)
1592 for (i
= 0; superlist
[i
]; i
++) {
1593 struct superswitch
*ss
= superlist
[i
];
1595 if (strcmp(vers
, ss
->name
) == 0)
1602 int metadata_container_matches(char *metadata
, char *devnm
)
1604 /* Check if 'devnm' is the container named in 'metadata'
1606 * /containername/componentname or
1607 * -containername/componentname
1610 if (*metadata
!= '/' && *metadata
!= '-')
1613 if (strncmp(metadata
+1, devnm
, l
) != 0)
1615 if (metadata
[l
+1] != '/')
1620 int metadata_subdev_matches(char *metadata
, char *devnm
)
1622 /* Check if 'devnm' is the subdev named in 'metadata'
1624 * /containername/subdev or
1625 * -containername/subdev
1628 if (*metadata
!= '/' && *metadata
!= '-')
1630 sl
= strchr(metadata
+1, '/');
1633 if (strcmp(sl
+1, devnm
) == 0)
1638 int is_subarray_active(char *subarray
, char *container
)
1640 struct mdstat_ent
*mdstat
= mdstat_read(0, 0);
1641 struct mdstat_ent
*ent
;
1643 for (ent
= mdstat
; ent
; ent
= ent
->next
)
1644 if (is_container_member(ent
, container
))
1645 if (strcmp(to_subarray(ent
, container
), subarray
) == 0)
1648 free_mdstat(mdstat
);
1653 /* open_subarray - opens a subarray in a container
1654 * @dev: container device name
1655 * @st: empty supertype
1656 * @quiet: block reporting errors flag
1658 * On success returns an fd to a container and fills in *st
1660 int open_subarray(char *dev
, char *subarray
, struct supertype
*st
, int quiet
)
1663 struct mdinfo
*info
;
1667 fd
= open(dev
, O_RDWR
|O_EXCL
);
1670 pr_err("Couldn't open %s, aborting\n",
1675 _devnm
= fd2devnm(fd
);
1676 if (_devnm
== NULL
) {
1678 pr_err("Failed to determine device number for %s\n",
1682 snprintf(st
->devnm
, sizeof(st
->devnm
), "%s", _devnm
);
1684 mdi
= sysfs_read(fd
, st
->devnm
, GET_VERSION
|GET_LEVEL
);
1687 pr_err("Failed to read sysfs for %s\n",
1692 if (mdi
->array
.level
!= UnSet
) {
1694 pr_err("%s is not a container\n", dev
);
1698 st
->ss
= version_to_superswitch(mdi
->text_version
);
1701 pr_err("Operation not supported for %s metadata\n",
1706 if (st
->devnm
[0] == 0) {
1708 pr_err("Failed to allocate device name\n");
1712 if (!st
->ss
->load_container
) {
1714 pr_err("%s is not a container\n", dev
);
1718 if (st
->ss
->load_container(st
, fd
, NULL
)) {
1720 pr_err("Failed to load metadata for %s\n",
1725 info
= st
->ss
->container_content(st
, subarray
);
1728 pr_err("Failed to find subarray-%s in %s\n",
1738 st
->ss
->free_super(st
);
1751 int add_disk(int mdfd
, struct supertype
*st
,
1752 struct mdinfo
*sra
, struct mdinfo
*info
)
1754 /* Add a device to an array, in one of 2 ways. */
1757 if (st
->ss
->external
) {
1758 if (info
->disk
.state
& (1<<MD_DISK_SYNC
))
1759 info
->recovery_start
= MaxSector
;
1761 info
->recovery_start
= 0;
1762 rv
= sysfs_add_disk(sra
, info
, 0);
1765 for (sd2
= sra
->devs
; sd2
; sd2
=sd2
->next
)
1769 sd2
= xmalloc(sizeof(*sd2
));
1771 sd2
->next
= sra
->devs
;
1776 rv
= ioctl(mdfd
, ADD_NEW_DISK
, &info
->disk
);
1780 int remove_disk(int mdfd
, struct supertype
*st
,
1781 struct mdinfo
*sra
, struct mdinfo
*info
)
1785 /* Remove the disk given by 'info' from the array */
1786 if (st
->ss
->external
)
1787 rv
= sysfs_set_str(sra
, info
, "slot", STR_COMMON_NONE
);
1789 rv
= ioctl(mdfd
, HOT_REMOVE_DISK
, makedev(info
->disk
.major
,
1794 int hot_remove_disk(int mdfd
, unsigned long dev
, int force
)
1796 int cnt
= force
? 500 : 5;
1799 /* HOT_REMOVE_DISK can fail with EBUSY if there are
1800 * outstanding IO requests to the device.
1801 * In this case, it can be helpful to wait a little while,
1802 * up to 5 seconds if 'force' is set, or 50 msec if not.
1804 while ((ret
= ioctl(mdfd
, HOT_REMOVE_DISK
, dev
)) == -1 &&
1807 sleep_for(0, MSEC_TO_NSEC(10), true);
1812 int sys_hot_remove_disk(int statefd
, int force
)
1814 int cnt
= force
? 500 : 5;
1818 int ret
= sysfs_set_memb_state_fd(statefd
, MEMB_STATE_REMOVE
, &err
);
1820 if (ret
== MDADM_STATUS_SUCCESS
)
1826 sleep_for(0, MSEC_TO_NSEC(10), true);
1832 int set_array_info(int mdfd
, struct supertype
*st
, struct mdinfo
*info
)
1834 /* Initialise kernel's knowledge of array.
1835 * This varies between externally managed arrays
1838 mdu_array_info_t inf
;
1841 if (st
->ss
->external
)
1842 return sysfs_set_array(info
);
1844 memset(&inf
, 0, sizeof(inf
));
1845 inf
.major_version
= info
->array
.major_version
;
1846 inf
.minor_version
= info
->array
.minor_version
;
1847 rv
= md_set_array_info(mdfd
, &inf
);
1852 unsigned long long min_recovery_start(struct mdinfo
*array
)
1854 /* find the minimum recovery_start in an array for metadata
1855 * formats that only record per-array recovery progress instead
1858 unsigned long long recovery_start
= MaxSector
;
1861 for (d
= array
->devs
; d
; d
= d
->next
)
1862 recovery_start
= min(recovery_start
, d
->recovery_start
);
1864 return recovery_start
;
1867 int mdmon_pid(const char *devnm
)
1874 sprintf(path
, "%s/%s.pid", MDMON_DIR
, devnm
);
1876 fd
= open(path
, O_RDONLY
| O_NOATIME
, 0);
1880 n
= read(fd
, pid
, 9);
1887 int mdmon_running(const char *devnm
)
1889 int pid
= mdmon_pid(devnm
);
1892 if (kill(pid
, 0) == 0)
1898 * wait_for_mdmon_control_socket() - Waits for mdmon control socket
1899 * to be created within specified time.
1900 * @container_devnm: Device for which mdmon control socket should start.
1902 * In foreground mode, when mdadm is trying to connect to control
1903 * socket it is possible that the mdmon has not created it yet.
1904 * Give some time to mdmon to create socket. Timeout set to 2 sec.
1906 * Return: MDADM_STATUS_SUCCESS if connect succeed, otherwise return
1909 mdadm_status_t
wait_for_mdmon_control_socket(const char *container_devnm
)
1911 enum mdadm_status status
= MDADM_STATUS_SUCCESS
;
1912 int sfd
, rv
, retry_count
= 0;
1913 struct sockaddr_un addr
;
1914 char path
[PATH_MAX
];
1916 snprintf(path
, PATH_MAX
, "%s/%s.sock", MDMON_DIR
, container_devnm
);
1917 sfd
= socket(PF_LOCAL
, SOCK_STREAM
, 0);
1918 if (!is_fd_valid(sfd
))
1919 return MDADM_STATUS_ERROR
;
1921 addr
.sun_family
= PF_LOCAL
;
1922 strncpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
) - 1);
1923 addr
.sun_path
[sizeof(addr
.sun_path
) - 1] = '\0';
1925 for (retry_count
= 0; retry_count
< 10; retry_count
++) {
1926 rv
= connect(sfd
, (struct sockaddr
*)&addr
, sizeof(addr
));
1928 sleep_for(0, MSEC_TO_NSEC(200), true);
1935 pr_err("Failed to connect to control socket.\n");
1936 status
= MDADM_STATUS_ERROR
;
1943 * wait_for_mdmon() - Waits for mdmon within specified time.
1944 * @devnm: Device for which mdmon should start.
1946 * Function waits for mdmon to start. It may need few seconds
1947 * to start, we set timeout to 5, it should be sufficient.
1948 * Do not wait if mdmon has been started.
1950 * Return: MDADM_STATUS_SUCCESS if mdmon is running, error code otherwise.
1952 mdadm_status_t
wait_for_mdmon(const char *devnm
)
1954 const time_t mdmon_timeout
= 5;
1955 time_t start_time
= time(0);
1957 if (mdmon_running(devnm
))
1958 return MDADM_STATUS_SUCCESS
;
1960 pr_info("Waiting for mdmon to start\n");
1961 while (time(0) - start_time
< mdmon_timeout
) {
1962 sleep_for(0, MSEC_TO_NSEC(200), true);
1963 if (mdmon_running(devnm
))
1964 return MDADM_STATUS_SUCCESS
;
1967 pr_err("Timeout waiting for mdmon\n");
1968 return MDADM_STATUS_ERROR
;
1971 int start_mdmon(char *devnm
)
1977 char *prefix
= in_initrd() ? "initrd-" : "";
1986 if (check_env("MDADM_NO_MDMON"))
1988 if (continue_via_systemd(devnm
, MDMON_SERVICE
, prefix
) == MDADM_STATUS_SUCCESS
)
1991 /* That failed, try running mdmon directly */
1992 len
= readlink("/proc/self/exe", pathbuf
, sizeof(pathbuf
)-1);
1996 sl
= strrchr(pathbuf
, '/');
2001 strcpy(sl
, "mdmon");
2008 for (i
= 0; paths
[i
]; i
++)
2010 execl(paths
[i
], paths
[i
],
2014 case -1: pr_err("cannot run mdmon. Array remains readonly\n");
2016 default: /* parent - good */
2017 pid
= wait(&status
);
2018 if (pid
< 0 || status
!= 0) {
2019 pr_err("failed to launch mdmon. Array remains readonly\n");
2026 __u32
random32(void)
2029 int rfd
= open("/dev/urandom", O_RDONLY
);
2030 if (rfd
< 0 || read(rfd
, &rv
, 4) != 4)
2037 void random_uuid(__u8
*buf
)
2042 fd
= open("/dev/urandom", O_RDONLY
);
2045 len
= read(fd
, buf
, 16);
2053 for (i
= 0; i
< 4; i
++)
2058 int flush_metadata_updates(struct supertype
*st
)
2062 st
->update_tail
= NULL
;
2066 sfd
= connect_monitor(st
->container_devnm
);
2070 while (st
->updates
) {
2071 struct metadata_update
*mu
= st
->updates
;
2072 st
->updates
= mu
->next
;
2074 send_message(sfd
, mu
, 0);
2082 st
->update_tail
= NULL
;
2086 void append_metadata_update(struct supertype
*st
, void *buf
, int len
)
2089 struct metadata_update
*mu
= xmalloc(sizeof(*mu
));
2094 mu
->space_list
= NULL
;
2096 *st
->update_tail
= mu
;
2097 st
->update_tail
= &mu
->next
;
2101 /* tinyc doesn't optimize this check in ioctl.h out ... */
2102 unsigned int __invalid_size_argument_for_IOC
= 0;
2106 * disk_fd_matches_criteria() - check if device matches spare criteria.
2107 * @st: supertype, not NULL.
2108 * @disk_fd: file descriptor of the disk.
2109 * @sc: criteria to test.
2111 * Return: true if disk matches criteria, false otherwise.
2113 bool disk_fd_matches_criteria(struct supertype
*st
, int disk_fd
, struct spare_criteria
*sc
)
2115 unsigned int dev_sector_size
= 0;
2116 unsigned long long dev_size
= 0;
2118 if (!sc
->criteria_set
)
2121 if (!get_dev_size(disk_fd
, NULL
, &dev_size
) || dev_size
< sc
->min_size
)
2124 if (!get_dev_sector_size(disk_fd
, NULL
, &dev_sector_size
) ||
2125 sc
->sector_size
!= dev_sector_size
)
2128 if (drive_test_and_add_policies(st
, &sc
->pols
, disk_fd
, 0))
2135 * devid_matches_criteria() - check if device referenced by devid matches spare criteria.
2136 * @st: supertype, not NULL.
2137 * @devid: devid of the device to check.
2138 * @sc: criteria to test.
2140 * Return: true if disk matches criteria, false otherwise.
2142 bool devid_matches_criteria(struct supertype
*st
, dev_t devid
, struct spare_criteria
*sc
)
2148 if (!sc
->criteria_set
)
2151 snprintf(buf
, NAME_MAX
, "%d:%d", major(devid
), minor(devid
));
2153 fd
= dev_open(buf
, O_RDONLY
);
2154 if (!is_fd_valid(fd
))
2157 /* Error code inherited */
2158 ret
= disk_fd_matches_criteria(st
, fd
, sc
);
2164 /* Pick all spares matching given criteria from a container
2165 * if min_size == 0 do not check size
2166 * if domlist == NULL do not check domains
2167 * if spare_group given add it to domains of each spare
2168 * metadata allows to test domains using metadata of destination array */
2169 struct mdinfo
*container_choose_spares(struct supertype
*st
,
2170 struct spare_criteria
*criteria
,
2171 struct domainlist
*domlist
,
2173 const char *metadata
, int get_one
)
2175 struct mdinfo
*d
, **dp
, *disks
= NULL
;
2177 /* get list of all disks in container */
2178 if (st
->ss
->getinfo_super_disks
)
2179 disks
= st
->ss
->getinfo_super_disks(st
);
2183 /* find spare devices on the list */
2185 disks
->array
.spare_disks
= 0;
2190 if (d
->disk
.state
== 0) {
2191 dev_t dev
= makedev(d
->disk
.major
,d
->disk
.minor
);
2193 found
= devid_matches_criteria(st
, dev
, criteria
);
2195 /* check if domain matches */
2196 if (found
&& domlist
) {
2197 struct dev_policy
*pol
= devid_policy(dev
);
2199 pol_add(&pol
, pol_domain
,
2201 if (domain_test(domlist
, pol
, metadata
) != 1)
2204 dev_policy_free(pol
);
2209 disks
->array
.spare_disks
++;
2223 /* Checks if paths point to the same device
2224 * Returns 0 if they do.
2225 * Returns 1 if they don't.
2226 * Returns -1 if something went wrong,
2227 * e.g. paths are empty or the files
2228 * they point to don't exist */
2229 int compare_paths (char* path1
, char* path2
)
2231 struct stat st1
,st2
;
2233 if (path1
== NULL
|| path2
== NULL
)
2235 if (stat(path1
,&st1
) != 0)
2237 if (stat(path2
,&st2
) != 0)
2239 if ((st1
.st_ino
== st2
.st_ino
) && (st1
.st_dev
== st2
.st_dev
))
2244 /* Make sure we can open as many devices as needed */
2245 void enable_fds(int devices
)
2247 unsigned int fds
= 20 + devices
;
2249 if (getrlimit(RLIMIT_NOFILE
, &lim
) != 0 || lim
.rlim_cur
>= fds
)
2251 if (lim
.rlim_max
< fds
)
2254 setrlimit(RLIMIT_NOFILE
, &lim
);
2257 /* Close all opened descriptors if needed and redirect
2258 * streams to /dev/null.
2259 * For debug purposed, leave STDOUT and STDERR untouched
2261 * 1- if any error occurred
2264 void manage_fork_fds(int close_all
)
2267 struct dirent
*dirent
;
2268 int fd
= open("/dev/null", O_RDWR
);
2270 if (is_fd_valid(fd
)) {
2282 dir
= opendir("/proc/self/fd");
2284 pr_err("Cannot open /proc/self/fd directory.\n");
2287 for (dirent
= readdir(dir
); dirent
; dirent
= readdir(dir
)) {
2290 if ((strcmp(dirent
->d_name
, ".") == 0) ||
2291 (strcmp(dirent
->d_name
, "..")) == 0)
2294 fd
= strtol(dirent
->d_name
, NULL
, 10);
2302 /* In a systemd/udev world, it is best to get systemd to
2303 * run daemon rather than running in the background.
2305 * MDADM_STATUS_SUCCESS - if systemd service has been started.
2306 * MDADM_STATUS_ERROR - otherwise.
2308 mdadm_status_t
continue_via_systemd(char *devnm
, char *service_name
, char *prefix
)
2311 char pathbuf
[PATH_MAX
];
2313 dprintf("Start %s service\n", service_name
);
2314 /* Simply return that service cannot be started */
2315 if (check_env("MDADM_NO_SYSTEMCTL"))
2316 return MDADM_STATUS_ERROR
;
2318 /* Fork in attempt to start services */
2320 case -1: /* Fork failed, just do it ourselves. */
2324 snprintf(pathbuf
, sizeof(pathbuf
), "%s@%s%s.service",
2325 service_name
, prefix
? prefix
: "", devnm
);
2327 /* Attempt to start service.
2328 * On success execl() will "kill" the fork, and return status of systemctl call.
2330 execl("/usr/bin/systemctl", "systemctl", "restart", pathbuf
, NULL
);
2331 execl("/bin/systemctl", "systemctl", "restart", pathbuf
, NULL
);
2332 exit(MDADM_STATUS_ERROR
);
2333 default: /* parent */
2334 /* Check if forked process successfully trigered service */
2335 pid
= wait(&status
);
2336 if (pid
>= 0 && status
== 0)
2337 return MDADM_STATUS_SUCCESS
;
2339 return MDADM_STATUS_ERROR
;
2344 return access("/etc/initrd-release", F_OK
) >= 0;
2347 void reopen_mddev(int mdfd
)
2349 /* Re-open without any O_EXCL, but keep
2352 char *devnm
= fd2devnm(mdfd
);
2353 int fd
= open_dev(devnm
);
2355 if (!is_fd_valid(fd
))
2363 static struct cmap_hooks
*cmap_hooks
= NULL
;
2364 static int is_cmap_hooks_ready
= 0;
2366 void set_cmap_hooks(void)
2368 cmap_hooks
= xmalloc(sizeof(struct cmap_hooks
));
2369 cmap_hooks
->cmap_handle
= dlopen("libcmap.so.4", RTLD_NOW
| RTLD_LOCAL
);
2370 if (!cmap_hooks
->cmap_handle
)
2373 cmap_hooks
->initialize
=
2374 dlsym(cmap_hooks
->cmap_handle
, "cmap_initialize");
2375 cmap_hooks
->get_string
=
2376 dlsym(cmap_hooks
->cmap_handle
, "cmap_get_string");
2377 cmap_hooks
->finalize
= dlsym(cmap_hooks
->cmap_handle
, "cmap_finalize");
2379 if (!cmap_hooks
->initialize
|| !cmap_hooks
->get_string
||
2380 !cmap_hooks
->finalize
)
2381 dlclose(cmap_hooks
->cmap_handle
);
2383 is_cmap_hooks_ready
= 1;
2386 int get_cluster_name(char **cluster_name
)
2389 cmap_handle_t handle
;
2391 if (!is_cmap_hooks_ready
)
2394 rv
= cmap_hooks
->initialize(&handle
);
2398 rv
= cmap_hooks
->get_string(handle
, "totem.cluster_name", cluster_name
);
2400 free(*cluster_name
);
2407 cmap_hooks
->finalize(handle
);
2412 void set_dlm_hooks(void)
2414 dlm_hooks
= xmalloc(sizeof(struct dlm_hooks
));
2415 dlm_hooks
->dlm_handle
= dlopen("libdlm_lt.so.3", RTLD_NOW
| RTLD_LOCAL
);
2416 if (!dlm_hooks
->dlm_handle
)
2419 dlm_hooks
->open_lockspace
=
2420 dlsym(dlm_hooks
->dlm_handle
, "dlm_open_lockspace");
2421 dlm_hooks
->create_lockspace
=
2422 dlsym(dlm_hooks
->dlm_handle
, "dlm_create_lockspace");
2423 dlm_hooks
->release_lockspace
=
2424 dlsym(dlm_hooks
->dlm_handle
, "dlm_release_lockspace");
2425 dlm_hooks
->ls_lock
= dlsym(dlm_hooks
->dlm_handle
, "dlm_ls_lock");
2426 dlm_hooks
->ls_unlock_wait
=
2427 dlsym(dlm_hooks
->dlm_handle
, "dlm_ls_unlock_wait");
2428 dlm_hooks
->ls_get_fd
= dlsym(dlm_hooks
->dlm_handle
, "dlm_ls_get_fd");
2429 dlm_hooks
->dispatch
= dlsym(dlm_hooks
->dlm_handle
, "dlm_dispatch");
2431 if (!dlm_hooks
->open_lockspace
|| !dlm_hooks
->create_lockspace
||
2432 !dlm_hooks
->ls_lock
|| !dlm_hooks
->ls_unlock_wait
||
2433 !dlm_hooks
->release_lockspace
|| !dlm_hooks
->ls_get_fd
||
2434 !dlm_hooks
->dispatch
)
2435 dlclose(dlm_hooks
->dlm_handle
);
2437 is_dlm_hooks_ready
= 1;
2440 void set_hooks(void)
2446 int zero_disk_range(int fd
, unsigned long long sector
, size_t count
)
2452 size_t len
= count
* 512;
2455 fd_zero
= open("/dev/zero", O_RDONLY
);
2457 pr_err("Cannot open /dev/zero\n");
2461 if (lseek(fd
, sector
* 512, SEEK_SET
) < 0) {
2463 pr_err("Failed to seek offset for zeroing\n");
2467 addr
= mmap(NULL
, len
, PROT_READ
, MAP_PRIVATE
, fd_zero
, 0);
2469 if (addr
== MAP_FAILED
) {
2471 pr_err("Mapping /dev/zero failed\n");
2476 n
= write(fd
, addr
+ written
, len
- written
);
2481 pr_err("Zeroing disk range failed\n");
2485 } while (written
!= len
);
2495 * sleep_for() - Sleeps for specified time.
2496 * @sec: Seconds to sleep for.
2497 * @nsec: Nanoseconds to sleep for, has to be less than one second.
2498 * @wake_after_interrupt: If set, wake up if interrupted.
2500 * Function immediately returns if error different than EINTR occurs.
2502 void sleep_for(unsigned int sec
, long nsec
, bool wake_after_interrupt
)
2504 struct timespec delay
= {.tv_sec
= sec
, .tv_nsec
= nsec
};
2506 assert(nsec
< MSEC_TO_NSEC(1000));
2510 nanosleep(&delay
, &delay
);
2511 if (errno
!= 0 && errno
!= EINTR
) {
2512 pr_err("Error sleeping for %us %ldns: %s\n", sec
, nsec
, strerror(errno
));
2515 } while (!wake_after_interrupt
&& errno
== EINTR
);
2518 /* is_directory() - Checks if directory provided by path is indeed a regular directory.
2519 * @path: directory path to be checked
2521 * Doesn't accept symlinks.
2523 * Return: true if is a directory, false if not
2525 bool is_directory(const char *path
)
2529 if (lstat(path
, &st
) != 0) {
2530 pr_err("%s: %s\n", strerror(errno
), path
);
2534 if (!S_ISDIR(st
.st_mode
))
2541 * is_file() - Checks if file provided by path is indeed a regular file.
2542 * @path: file path to be checked
2544 * Doesn't accept symlinks.
2546 * Return: true if is a file, false if not
2548 bool is_file(const char *path
)
2552 if (lstat(path
, &st
) != 0) {
2553 pr_err("%s: %s\n", strerror(errno
), path
);
2557 if (!S_ISREG(st
.st_mode
))
2563 bool set_md_mod_parameter(const char *name
, const char *value
)
2569 snprintf(path
, sizeof(path
), "/sys/module/md_mod/parameters/%s", name
);
2571 fd
= open(path
, O_WRONLY
);
2573 pr_err("Can't open %s\n", path
);
2577 if (write(fd
, value
, strlen(value
)) != (ssize_t
)strlen(value
)) {
2578 pr_err("Failed to write to %s\n", path
);
2586 /* Init kernel md_mod parameters here if needed */
2587 bool init_md_mod_param(void)
2592 * In kernel 9e59d609763f calls del_gendisk in sync way. So device
2593 * node can be removed after stop command. But it can introduce a
2594 * regression which can be fixed by github pr182. New mdadm version
2595 * with pr182 can work well with new kernel. But users who don't
2596 * update mdadm and update to new kernel, they can't assemble array
2597 * anymore. So kernel adds a kernel parameter legacy_async_del_gendisk
2598 * and uses async as default.
2599 * We'll use sync mode since 6.18 rather than async mode. So in future
2600 * the kernel parameter will be removed.
2602 if (get_linux_version() >= 6018000)
2603 ret
= set_md_mod_parameter(MD_MOD_ASYNC_DEL_GENDISK
, "N");