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