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