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