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